// =============================================================================
// CRM TAB - Lovejoy planning pipeline.
// Display phase buckets are OWNED BY THE THEME (window.JD_THEME.PHASES) and the
// adapter must return client.phase as one of those strings. Do not hardcode
// phase names here — they are read from theme so Codex can adjust in one place.
// =============================================================================

(function () {
  const { useState } = React;
  const { C, PHASES } = window.JD_THEME;
  const { card, ct, bg, Empty, Loading, ErrorBox } = window.JD_STYLES;

  function CRM() {
    const clientsQ = window.useJarvisData("clients");
    const clients = clientsQ.data || [];
    const [expanded, setExpanded] = useState(null);

    const counts = clients.reduce((a, c) => { a[c.phase] = (a[c.phase] || 0) + 1; return a; }, {});
    const aumValues = clients.map(c => parseAUM(c.aum)).filter(n => n != null);
    const aumTotal = aumValues.length ? formatAUM(aumValues.reduce((a, b) => a + b, 0)) : "—";

    return (
      <div>
        <div style={{ display: "grid", gridTemplateColumns: "repeat(4,1fr)", gap: 12, marginBottom: 14 }}>
          {[
            ["Active Cases", clients.length, C.gold],
            ["Assets Under Mgmt", aumTotal, C.green],
            ["Urgent Flags", clients.filter(c => c.status === "urgent").length, C.red],
            ["Stalling", clients.filter(c => c.status === "stalling").length, C.yellow],
          ].map(([l, v, c]) => (
            <div key={l} style={card()}>
              <div style={{ fontSize: 12, color: C.muted, letterSpacing: "0.16em", textTransform: "uppercase", marginBottom: 6 }}>{l}</div>
              <div style={{ fontSize: 28, color: c, fontVariantNumeric: "tabular-nums" }}>{v}</div>
            </div>
          ))}
        </div>
        <div style={card({ marginBottom: 14 })}>
          <div style={ct}>Pipeline · Lovejoy Planning Process</div>
          <div style={{ display: "flex", gap: 6, marginTop: 6 }}>
            {PHASES.map((p, i) => {
              const n = counts[p] || 0;
              return (
                <div key={p} style={{ flex: 1, padding: "14px 12px", borderRadius: 8, background: n > 0 ? "rgba(159,117,9,0.12)" : C.card2, border: "0.5px solid " + (n > 0 ? "rgba(159,117,9,0.3)" : "rgba(222,214,185,0.06)") }}>
                  <div style={{ fontSize: 12, color: n > 0 ? C.gold : C.muted, letterSpacing: "0.18em", textTransform: "uppercase", marginBottom: 6 }}>{i + 1}D · {p}</div>
                  <div style={{ fontSize: 24, color: n > 0 ? C.cream : C.muted, fontVariantNumeric: "tabular-nums" }}>{n}</div>
                  <div style={{ fontSize: 12, color: C.muted, marginTop: 2 }}>{n === 1 ? "case" : "cases"}</div>
                </div>
              );
            })}
          </div>
        </div>
        <div style={{ marginBottom: 14, fontSize: 15, color: "rgba(10,21,32,0.6)", display: "flex", justifyContent: "space-between", alignItems: "center" }}>
          <span>Active cases — alphabetical by last name</span>
          <div style={{ display: "flex", gap: 6 }}>
            <button style={{ padding: "5px 14px", borderRadius: 6, border: "0.5px solid rgba(10,21,32,0.18)", background: "transparent", color: "rgba(10,21,32,0.7)", cursor: "pointer", fontSize: 13, fontFamily: "Georgia,serif" }}>+ Add Case</button>
            <button style={{ padding: "5px 14px", borderRadius: 6, border: "0.5px solid rgba(159,117,9,0.4)", background: "rgba(159,117,9,0.15)", color: C.gold, cursor: "pointer", fontSize: 13, fontFamily: "Georgia,serif" }}>Filter</button>
          </div>
        </div>
        {clientsQ.loading && <div style={card()}><Loading /></div>}
        {clientsQ.error && <div style={card()}><ErrorBox message={clientsQ.error.message} /></div>}
        {!clientsQ.loading && !clientsQ.error && clients.length === 0 && (
          <div style={card()}><Empty label="No clients yet" sub="Adapter returned an empty client list" /></div>
        )}
        {[...clients].sort((a, b) => a.last.localeCompare(b.last)).map(c => (
          <div key={c.id} onClick={() => setExpanded(expanded === c.id ? null : c.id)} style={card({ marginBottom: 8, border: "0.5px solid " + (c.status === "urgent" ? "rgba(224,82,82,0.35)" : c.status === "stalling" ? "rgba(212,160,23,0.35)" : C.border), cursor: "pointer" })}>
            <div style={{ display: "flex", alignItems: "center", gap: 14 }}>
              <div style={{ width: 42, height: 42, borderRadius: "50%", background: c.status === "urgent" ? "rgba(224,82,82,0.18)" : c.status === "stalling" ? "rgba(212,160,23,0.18)" : "rgba(159,117,9,0.2)", border: "0.5px solid " + (c.status === "urgent" ? "rgba(224,82,82,0.4)" : c.status === "stalling" ? "rgba(212,160,23,0.4)" : "rgba(159,117,9,0.4)"), display: "flex", alignItems: "center", justifyContent: "center", fontSize: 14, color: c.status === "urgent" ? C.red : c.status === "stalling" ? C.yellow : C.gold, flexShrink: 0, fontWeight: 500 }}>{c.last[0]}{c.first[0]}</div>
              <div style={{ flex: 1, minWidth: 0 }}>
                <div style={{ display: "flex", alignItems: "center", gap: 8, flexWrap: "wrap" }}>
                  <div style={{ fontSize: 19, color: C.cream, fontWeight: 500 }}>{c.last}, {c.first}</div>
                  {c.alert && <span style={{ fontSize: 12, padding: "3px 10px", borderRadius: 10, background: c.status === "urgent" ? "rgba(224,82,82,0.18)" : "rgba(212,160,23,0.18)", color: c.status === "urgent" ? C.red : C.yellow, border: "0.5px solid " + (c.status === "urgent" ? "rgba(224,82,82,0.35)" : "rgba(212,160,23,0.35)"), letterSpacing: "0.06em" }}>{c.alert}</span>}
                </div>
                <div style={{ fontSize: 14, color: C.muted, marginTop: 3 }}>{c.desc}</div>
                <div style={{ display: "flex", gap: 14, marginTop: 6, flexWrap: "wrap" }}>
                  <span style={{ fontSize: 13, color: "rgba(222,214,185,0.78)" }}><span style={{ color: C.muted }}>Household:</span> {c.household}</span>
                  <span style={{ fontSize: 13, color: "rgba(222,214,185,0.78)" }}><span style={{ color: C.muted }}>AUM:</span> {c.aum}</span>
                </div>
              </div>
              <div style={{ textAlign: "right", flexShrink: 0 }}>
                <div style={{ fontSize: 12, padding: "3px 10px", borderRadius: 10, background: "rgba(159,117,9,0.15)", color: C.gold, border: "0.5px solid rgba(159,117,9,0.3)", marginBottom: 6, letterSpacing: "0.08em" }}>{c.phase}</div>
                <div style={{ fontSize: 13, color: C.muted }}>Last touch · {c.touch}</div>
              </div>
              <div style={{ color: C.muted, fontSize: 14, marginLeft: 8 }}>{expanded === c.id ? "▲" : "▼"}</div>
            </div>
            {expanded === c.id && (
              <div style={{ marginTop: 14, paddingTop: 14, borderTop: "0.5px solid rgba(222,214,185,0.1)" }} onClick={e => e.stopPropagation()}>
                <div style={{ padding: "12px 14px", background: "rgba(159,117,9,0.08)", borderRadius: 8, border: "0.5px solid rgba(159,117,9,0.22)", marginBottom: 14, display: "flex", gap: 14, alignItems: "center" }}>
                  <div style={{ fontSize: 12, color: C.gold, letterSpacing: "0.16em", textTransform: "uppercase", flexShrink: 0 }}>Next Action</div>
                  <div style={{ fontSize: 15, color: C.cream, flex: 1 }}>{c.next}</div>
                </div>
                <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 12, marginBottom: 14 }}>
                  <div style={{ padding: "12px 14px", background: C.card2, borderRadius: 8, border: "0.5px solid " + C.border }}>
                    <div style={{ fontSize: 12, color: C.muted, letterSpacing: "0.16em", textTransform: "uppercase", marginBottom: 10 }}>Deliverables</div>
                    {(c.deliverables || []).map((d, j) => (
                      <div key={j} style={{ display: "flex", alignItems: "flex-start", gap: 8, padding: "6px 0", borderBottom: j < c.deliverables.length - 1 ? "0.5px solid rgba(222,214,185,0.06)" : "none" }}>
                        <div style={{ width: 13, height: 13, borderRadius: 3, border: "1.5px solid " + (d.ok ? C.green : "rgba(222,214,185,0.3)"), background: d.ok ? C.green : "transparent", display: "flex", alignItems: "center", justifyContent: "center", flexShrink: 0, marginTop: 3 }}>
                          {d.ok && <span style={{ color: C.bg, fontSize: 10, fontWeight: "bold" }}>✓</span>}
                        </div>
                        <div style={{ flex: 1 }}>
                          <div style={{ fontSize: 14, color: d.ok ? "rgba(222,214,185,0.55)" : C.cream, textDecoration: d.ok ? "line-through" : "none" }}>{d.t}</div>
                          <div style={{ fontSize: 12, color: (d.d || "").toLowerCase().includes("overdue") ? C.red : C.muted }}>{d.d}</div>
                        </div>
                      </div>
                    ))}
                  </div>
                  <div style={{ padding: "12px 14px", background: C.card2, borderRadius: 8, border: "0.5px solid " + C.border }}>
                    <div style={{ fontSize: 12, color: C.muted, letterSpacing: "0.16em", textTransform: "uppercase", marginBottom: 10 }}>Recent Comms</div>
                    {(c.comms || []).map((m, j) => (
                      <div key={j} style={{ padding: "7px 0", borderBottom: j < c.comms.length - 1 ? "0.5px solid rgba(222,214,185,0.06)" : "none" }}>
                        <div style={{ display: "flex", justifyContent: "space-between", alignItems: "baseline", gap: 8 }}>
                          <span style={{ fontSize: 11, color: C.gold, letterSpacing: "0.12em", textTransform: "uppercase" }}>{m.ch}</span>
                          <span style={{ fontSize: 12, color: C.muted }}>{m.d}</span>
                        </div>
                        <div style={{ fontSize: 14, color: "rgba(222,214,185,0.82)", marginTop: 2, lineHeight: 1.4 }}>{m.note}</div>
                      </div>
                    ))}
                  </div>
                </div>
                <div style={{ padding: "12px 14px", background: C.card2, borderRadius: 8, border: "0.5px solid " + C.border, marginBottom: 12 }}>
                  <div style={{ fontSize: 12, color: C.gold, letterSpacing: "0.16em", marginBottom: 6, textTransform: "uppercase" }}>CFP Insight · Jarvis</div>
                  <div style={{ fontSize: 15, color: "rgba(222,214,185,0.85)", lineHeight: 1.6 }}>{c.insight || <span style={{ fontStyle: "italic", color: C.muted }}>No cached insight. Wire adapter.getClientInsight(id) to populate.</span>}</div>
                </div>
                <div style={{ display: "flex", gap: 8, flexWrap: "wrap" }}>
                  <button style={bg}>Prep Meeting Brief</button>
                  <button style={{ ...bg, borderColor: "rgba(74,159,212,0.4)", color: C.blue }}>Open Drive Folder</button>
                  <button style={{ ...bg, borderColor: "rgba(62,207,142,0.4)", color: C.green }}>Gmail Thread</button>
                  <button style={{ ...bg, borderColor: "rgba(139,127,212,0.4)", color: C.purple }}>RightCapital</button>
                  <button style={{ ...bg, borderColor: "rgba(212,160,23,0.4)", color: C.yellow }}>Log Touchpoint</button>
                </div>
              </div>
            )}
          </div>
        ))}
      </div>
    );
  }

  // --- helpers --------------------------------------------------------------
  function parseAUM(s) {
    if (!s) return null;
    const m = String(s).match(/\$?([\d.]+)([KMB]?)/i);
    if (!m) return null;
    const n = parseFloat(m[1]);
    const mult = m[2].toUpperCase() === "B" ? 1e9 : m[2].toUpperCase() === "M" ? 1e6 : m[2].toUpperCase() === "K" ? 1e3 : 1;
    return n * mult;
  }
  function formatAUM(n) {
    if (n >= 1e9) return "$" + (n / 1e9).toFixed(1) + "B";
    if (n >= 1e6) return "$" + (n / 1e6).toFixed(1) + "M";
    if (n >= 1e3) return "$" + (n / 1e3).toFixed(0) + "K";
    return "$" + n;
  }

  window.JD_TABS = window.JD_TABS || {};
  window.JD_TABS.CRM = CRM;
})();
