/* ============================================================
   Vela — S2 · Action queue (landing) + All Cases
   ============================================================ */
(function () {
  const { useState } = React;
  const { fmtEur, CaseStatus, Avatar, Progress, caseProgress, templateOf } = window.UI;

  const KIND = {
    review:   { c: "var(--gold)",  bg: "var(--gold-soft)",  icon: "target", action: "Open review" },
    conflict: { c: "var(--amber)", bg: "var(--amber-soft)", icon: "warn",   action: "Resolve conflicts" },
    error:    { c: "var(--red)",   bg: "var(--red-soft)",   icon: "alert",  action: "Resolve" },
  };

  function QueueCard({ c, openCase, i }) {
    const k = KIND[c.queue.kind] || KIND.review;
    const isReview = c.queue.kind === "review";
    return (
      <div className="card anim-fadeup" style={{ display: "flex", alignItems: "stretch", overflow: "hidden", animationDelay: i * 0.05 + "s", boxShadow: "var(--sh-sm)" }}>
        <div style={{ width: 4, background: isReview ? "linear-gradient(var(--gold), var(--cyan))" : k.c, flexShrink: 0 }} />
        <div style={{ flex: 1, display: "flex", alignItems: "center", gap: 17, padding: "19px 22px", minWidth: 0 }}>
          <Avatar initials={c.initials} size={46} tone="soft" />
          <div style={{ minWidth: 0, flex: 1 }}>
            <div style={{ fontSize: 15.5, fontWeight: 600, color: "var(--ink)", marginBottom: 7, whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis" }}>{c.borrower}</div>
            <span className="chip" style={{ background: k.bg, color: k.c }}><Icon name={k.icon} size={12} stroke={2.4} />{c.queue.reason}</span>
          </div>
          <button className={"btn " + (isReview ? "btn-gold" : "btn-ghost")} onClick={() => openCase(c.id)} style={{ flexShrink: 0 }}>
            {k.action} <Icon name="arrowR" size={14} />
          </button>
        </div>
      </div>
    );
  }

  // Light recent-case row — collected/total count; full breakdown on click
  function RecentRow({ c, openCase, last }) {
    const sm = window.UI.CASE_COLOR[c.status] || window.UI.CASE_COLOR.DRAFT;
    const label = window.VELA.STATUS[c.status] ? window.VELA.STATUS[c.status].label : c.status;
    const pr = caseProgress(c);
    return (
      <div onClick={() => openCase(c.id)} className="focusable" tabIndex={0} onKeyDown={(e) => e.key === "Enter" && openCase(c.id)}
        style={{ display: "flex", alignItems: "center", gap: 15, padding: "0 8px", height: 62, cursor: "pointer", borderBottom: last ? "none" : "1px solid var(--line)", transition: "background .1s" }}
        onMouseEnter={(e) => e.currentTarget.style.background = "var(--surface-2)"} onMouseLeave={(e) => e.currentTarget.style.background = "transparent"}>
        <Avatar initials={c.initials} size={36} tone="soft" />
        <div style={{ minWidth: 0, flex: 1 }}>
          <div style={{ fontSize: 14, fontWeight: 600, color: "var(--ink)", whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis" }}>{c.borrower}</div>
          <div style={{ fontSize: 11.5, color: "var(--ink-3)" }}>
            <span className="mono" style={{ color: c.status === "COMPLETED" ? "var(--green)" : "var(--ink-2)", fontWeight: 600 }}>{pr.done}/{pr.total}</span> documents collected
          </div>
        </div>
        <span className="chip" style={{ background: sm.bg, color: sm.c }}><span className="chip-dot" style={{ background: sm.c }} />{label}</span>
        <Icon name="chevR" size={16} style={{ color: "var(--ink-4)" }} />
      </div>
    );
  }

  function AllCasesRow({ c, openCase }) {
    const tpl = templateOf(c.template);
    const pr = caseProgress(c);
    return (
      <div onClick={() => openCase(c.id)} className="focusable" tabIndex={0} onKeyDown={(e) => e.key === "Enter" && openCase(c.id)}
        style={{ display: "flex", alignItems: "center", gap: 16, padding: "14px 20px", cursor: "pointer", borderBottom: "1px solid var(--line)", transition: "background .1s" }}
        onMouseEnter={(e) => e.currentTarget.style.background = "var(--surface-2)"} onMouseLeave={(e) => e.currentTarget.style.background = "transparent"}>
        <Avatar initials={c.initials} size={38} tone="soft" />
        <div style={{ minWidth: 0, width: 230 }}>
          <div style={{ fontSize: 14, fontWeight: 600, whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis" }}>{c.borrower}</div>
          <div style={{ fontSize: 11.5, color: "var(--ink-3)" }}><span className="mono">{c.id}</span> · {tpl.label}</div>
        </div>
        <div style={{ width: 130, flexShrink: 0 }}><CaseStatus status={c.status} dot /></div>
        <div style={{ flex: 1, minWidth: 90 }}>
          {c.status === "COLLECTING" ? (
            <div>
              <div style={{ fontSize: 11.5, color: "var(--ink-3)", marginBottom: 5 }}>{pr.done} / {pr.total} documents</div>
              <Progress value={pr.pct} height={5} color="var(--blue)" />
            </div>
          ) : c.status === "COMPLETED" ? (
            <span style={{ fontSize: 12, color: "var(--green)", display: "flex", alignItems: "center", gap: 6 }}><Icon name="check" size={13} stroke={2.5} /> All documents validated</span>
          ) : c.status === "DRAFT" ? (
            <span style={{ fontSize: 12, color: "var(--ink-4)" }}>Not started — {pr.total} documents to collect</span>
          ) : (
            <span style={{ fontSize: 12, color: "var(--gold)" }}>Ready for your review</span>
          )}
        </div>
        <span style={{ fontSize: 12, color: "var(--ink-4)", whiteSpace: "nowrap", width: 90, textAlign: "right" }}>{c.activity}</span>
        <Icon name="chevR" size={16} style={{ color: "var(--ink-4)" }} />
      </div>
    );
  }

  function Queue({ go, openCase, onNew, search }) {
    const { cases } = window.VELA;
    const queueItems = cases.filter((c) => c.queue);
    const recent = cases.slice(0, 4);

    return (
      <div style={{ padding: "38px 44px 48px", maxWidth: 900, margin: "0 auto" }}>
        {/* header */}
        <div className="anim-fadeup" style={{ marginBottom: 26 }}>
          <div style={{ fontSize: 13, color: "var(--ink-3)", marginBottom: 8 }}>Good morning, Elena.</div>
          <h1 className="serif" style={{ fontSize: 28, color: "var(--ink)", lineHeight: 1.15 }}>
            {queueItems.length > 0
              ? <><span style={{ color: "var(--gold)" }}>{queueItems.length} cases</span> need your attention.</>
              : <>You're all caught up.</>}
          </h1>
          {queueItems.length > 0 && (
            <div style={{ fontSize: 13.5, color: "var(--ink-3)", marginTop: 9 }}>Everything else is collecting on track — the agent will flag anything that needs you.</div>
          )}
        </div>

        {/* the queue */}
        {queueItems.length > 0 ? (
          <div style={{ display: "flex", flexDirection: "column", gap: 14, marginBottom: 40 }}>
            {queueItems.map((c, i) => <QueueCard key={c.id} c={c} openCase={openCase} i={i} />)}
          </div>
        ) : (
          <div className="card anim-fadeup" style={{ padding: "44px", textAlign: "center", marginBottom: 40 }}>
            <div style={{ width: 56, height: 56, borderRadius: "50%", background: "var(--green-soft)", color: "var(--green)", display: "flex", alignItems: "center", justifyContent: "center", margin: "0 auto 14px" }}>
              <Icon name="check" size={28} stroke={2.5} />
            </div>
            <div className="serif" style={{ fontSize: 20, marginBottom: 6 }}>You're all caught up</div>
            <div style={{ fontSize: 13.5, color: "var(--ink-3)" }}>Nothing needs you right now. New items appear here the moment the agent escalates or a case is ready to review.</div>
          </div>
        )}

        {/* recent cases — light peek; full table lives in Cases */}
        <div style={{ display: "flex", alignItems: "baseline", justifyContent: "space-between", marginBottom: 14 }}>
          <h2 className="serif" style={{ fontSize: 16 }}>Recent cases</h2>
          <button onClick={() => go({ name: "cases" })} className="btn-quiet" style={{ border: 0, background: "none", display: "inline-flex", alignItems: "center", gap: 5, fontSize: 13, fontWeight: 600, color: "var(--gold)", padding: "2px 4px", borderRadius: 5 }}>
            View all {cases.length} <Icon name="arrowR" size={13} stroke={2.2} />
          </button>
        </div>
        <div className="card" style={{ padding: "4px 16px" }}>
          {recent.map((c, i) => <RecentRow key={c.id} c={c} openCase={openCase} last={i === recent.length - 1} />)}
        </div>
      </div>
    );
  }

  // Full "Cases" directory (secondary nav) — same list, no queue
  function CasesList({ openCase, search }) {
    const { cases } = window.VELA;
    const [filter, setFilter] = useState("ALL");
    const q = (search || "").toLowerCase();
    let all = cases.filter((c) => !q || c.borrower.toLowerCase().includes(q) || c.id.toLowerCase().includes(q));
    if (filter !== "ALL") all = all.filter((c) => c.status === filter);
    const FILTERS = [["ALL", "All"], ["COLLECTING", "Collecting"], ["UNDER_REVIEW", "Under review"], ["DRAFT", "Draft"], ["COMPLETED", "Completed"]];
    return (
      <div style={{ padding: "22px 28px 60px", maxWidth: 1120, margin: "0 auto" }} className="anim-fadein">
        <div style={{ display: "flex", gap: 6, marginBottom: 14, flexWrap: "wrap" }}>
          {FILTERS.map(([k, lbl]) => (
            <button key={k} onClick={() => setFilter(k)} style={{ border: "1px solid " + (filter === k ? "var(--ink)" : "var(--line)"), background: filter === k ? "var(--ink)" : "var(--surface)",
              color: filter === k ? "#fff" : "var(--ink-2)", borderRadius: 999, padding: "6px 13px", fontSize: 12, fontWeight: 600, cursor: "pointer" }}>{lbl}</button>
          ))}
        </div>
        <div className="card" style={{ overflow: "hidden" }}>
          {all.map((c) => <AllCasesRow key={c.id} c={c} openCase={openCase} />)}
        </div>
      </div>
    );
  }

  window.Queue = Queue;
  window.CasesList = CasesList;
})();
