/* =============================================================
   page-chat.jsx — Management communication center
   ============================================================= */
function PageChat({ model }) {
  const [scopeKind, setScopeKind] = React.useState("global");
  const [scopeId, setScopeId] = React.useState("");
  const [, force] = React.useState(0);
  React.useEffect(() => ChatStore.subscribe(() => force((n) => n + 1)), []);

  // Scope options derived from real data
  const opts = React.useMemo(() => {
    return PRData.scopeOptions(model);
  }, [model]);

  const allMsgs = ChatStore.all();
  const totalMsgs = allMsgs.length;
  // Threads with activity
  const threadActivity = React.useMemo(() => {
    const m = new Map();
    for (const msg of allMsgs) {
      const key = msg.scopeKind + ":" + (msg.scopeId || "");
      if (!m.has(key)) m.set(key, { scopeKind: msg.scopeKind, scopeId: msg.scopeId, count: 0, last: 0 });
      const e = m.get(key);
      e.count++;
      if (msg.ts > e.last) e.last = msg.ts;
    }
    return [...m.values()].sort((a, b) => b.last - a.last);
  }, [allMsgs]);

  const currentTitle = (() => {
    if (scopeKind === "global") return "Global project thread";
    if (!scopeId) return "Select a scope";
    return `${scopeKind[0].toUpperCase() + scopeKind.slice(1)} · ${scopeId}`;
  })();

  return (
    <div className="page">
      <PageHeader
        title="Communication"
        subtitle="Ask questions, share updates, escalate blockers — threads stay linked to scope (global / region / country / site / link)."
        right={
          <div className="flex gap-sm" style={{fontSize: 12, color: "var(--ink-500)"}}>
            <span><span className="mono" style={{color: "var(--ink-900)", fontWeight: 600}}>{totalMsgs}</span> messages</span>
            <span>·</span>
            <span><span className="mono" style={{color: "var(--ink-900)", fontWeight: 600}}>{threadActivity.length}</span> active threads</span>
          </div>
        }
      />

      <div style={{display: "grid", gridTemplateColumns: "300px 1fr", gap: 14, minHeight: "70vh"}}>
        {/* Threads sidebar */}
        <div className="card" style={{padding: 0, overflow: "hidden", display: "flex", flexDirection: "column"}}>
          <div style={{padding: "12px 14px", borderBottom: "1px solid var(--line-soft)", background: "var(--bg-elev)"}}>
            <div style={{fontSize: 11, color: "var(--ink-500)", textTransform: "uppercase", letterSpacing: "0.08em", marginBottom: 8}}>Open a thread</div>
            <select value={scopeKind} onChange={(e) => { setScopeKind(e.target.value); setScopeId(""); }}
                    style={{width: "100%", padding: "6px 8px", border: "1px solid var(--line)", borderRadius: 6, background: "var(--surface)", fontSize: 13, marginBottom: 6}}>
              <option value="global">Global project</option>
              <option value="region">Region</option>
              <option value="country">Country</option>
              <option value="site">Site</option>
              <option value="link">Link</option>
              <option value="change-request">Change request</option>
              <option value="migration-plan">Migration plan</option>
            </select>
            {scopeKind !== "global" && (<>
              <select value={scopeId} onChange={(e) => setScopeId(e.target.value)}
                      style={{width: "100%", padding: "6px 8px", border: "1px solid var(--line)", borderRadius: 6, background: "var(--surface)", fontSize: 13, display: ["change-request", "migration-plan"].includes(scopeKind) ? "none" : "block"}}>
                <option value="">Choose…</option>
                {(scopeKind === "region" ? opts.regions
                  : scopeKind === "country" ? opts.countries
                  : scopeKind === "site" ? opts.sites
                  : opts.links).map((o) => (
                  <option key={o} value={o}>{o}</option>
                ))}
              </select>
              {["change-request", "migration-plan"].includes(scopeKind) && (
                <input value={scopeId} onChange={(e) => setScopeId(e.target.value)}
                       placeholder={scopeKind === "change-request" ? "CR number or ID" : "Plan ID or site"}
                       style={{width: "100%", padding: "6px 8px", border: "1px solid var(--line)", borderRadius: 6, background: "var(--surface)", fontSize: 13}}/>
              )}
            </>)}
          </div>
          <div style={{padding: "8px 0", flex: 1, overflow: "auto"}}>
            <div style={{padding: "4px 14px 8px", fontSize: 11, color: "var(--ink-500)", textTransform: "uppercase", letterSpacing: "0.08em"}}>Recent threads</div>
            {threadActivity.length === 0 ? (
              <div className="muted" style={{padding: "14px 14px", fontSize: 12.5}}>No threads yet. Start one above.</div>
            ) : threadActivity.map((t) => {
              const sel = scopeKind === t.scopeKind && (scopeId || null) === (t.scopeId || null);
              return (
                <button key={t.scopeKind + (t.scopeId || "")}
                        onClick={() => { setScopeKind(t.scopeKind); setScopeId(t.scopeId || ""); }}
                        style={{
                          width: "100%", textAlign: "left", padding: "8px 14px",
                          border: 0, background: sel ? "var(--accent-soft)" : "transparent",
                          cursor: "pointer", borderLeft: sel ? "3px solid var(--accent)" : "3px solid transparent",
                        }}>
                  <div style={{fontSize: 12.5, fontWeight: 500, color: sel ? "var(--accent-ink)" : "var(--ink-900)"}}>
                    {t.scopeKind === "global" ? "Global project" : t.scopeId}
                  </div>
                  <div style={{fontSize: 11, color: "var(--ink-500)", marginTop: 2}}>
                    {t.scopeKind} · {t.count} message{t.count === 1 ? "" : "s"} · {new Date(t.last).toLocaleDateString()}
                  </div>
                </button>
              );
            })}
          </div>
        </div>

        {/* Thread body */}
        <div className="card" style={{padding: 0, display: "flex", flexDirection: "column", overflow: "hidden"}}>
          {scopeKind !== "global" && !scopeId ? (
            <div style={{flex: 1, display: "grid", placeItems: "center"}}>
              <Empty title="Choose a scope" sub="Pick a region, country, site or link from the sidebar to open its thread." />
            </div>
          ) : (
            <ChatThread scopeKind={scopeKind} scopeId={scopeKind === "global" ? null : scopeId} title={currentTitle}/>
          )}
        </div>
      </div>
    </div>
  );
}

window.PageChat = PageChat;
