/* LEADS & PIPELINE — kanban board + lead detail. window.SCREENS.Leads */
(function () {
  const { useState } = React;
  const I = window.ICONS;
  const { Avatar, Pill, Btn, LoanMeta, fmtMoney, fmtMoneyK } = window.UI;
  const { leads, leadById, STAGES, threads } = window.DATA;

  const SOURCE_COLOR = { Zillow: "var(--green-lift)", Realtor: "var(--gold)", Website: "var(--ink-soft)", Referral: "var(--green-lift)", Repeat: "var(--gold)" };

  function LeadCard({ l, onClick }) {
    return (
      <div className="panel" onClick={onClick} style={{ padding: 13, cursor: "pointer", display: "flex", flexDirection: "column", gap: 9 }}>
        <div style={{ display: "flex", alignItems: "center", gap: 9 }}>
          <Avatar init={l.init} size={28} />
          <span style={{ fontSize: 13.5, fontWeight: 600, flex: 1, minWidth: 0, whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis" }}>{l.name}</span>
          {l.days >= 7 && <span className="unread-dot" style={{ background: "var(--st-reject)" }} title="Stale"></span>}
        </div>
        <div style={{ display: "flex", alignItems: "baseline", justifyContent: "space-between" }}>
          <span className="num" style={{ fontSize: 22 }}>{fmtMoneyK(l.amount)}</span>
          <span className="mono" style={{ fontSize: 10, color: "var(--ink-faint)", letterSpacing: "0.08em", textTransform: "uppercase" }}>{l.loan}</span>
        </div>
        <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between" }}>
          <span className="mono" style={{ fontSize: 9.5, letterSpacing: "0.1em", textTransform: "uppercase", color: SOURCE_COLOR[l.source] }}>● {l.source}</span>
          <span className="mono" style={{ fontSize: 10, color: l.days >= 7 ? "var(--st-reject)" : "var(--ink-faint)" }}>{l.days === 0 ? "today" : l.days + "d"}</span>
        </div>
      </div>
    );
  }

  function Board({ onOpen }) {
    return (
      <div style={{ display: "grid", gridTemplateColumns: `repeat(${STAGES.length}, minmax(176px, 1fr))`, gap: 12, overflowX: "auto" }} className="hide-scroll">
        {STAGES.map(stage => {
          const col = leads.filter(l => l.stage === stage);
          const val = col.reduce((a, l) => a + l.amount, 0);
          return (
            <div key={stage} style={{ display: "flex", flexDirection: "column", gap: 10, minWidth: 176 }}>
              <div style={{ paddingBottom: 9, borderBottom: "1px solid var(--gold-line)" }}>
                <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between" }}>
                  <span className="mono" style={{ fontSize: 10.5, letterSpacing: "0.12em", textTransform: "uppercase", color: "var(--ink-soft)" }}>{stage}</span>
                  <span className="num" style={{ fontSize: 16 }}>{col.length}</span>
                </div>
                <div className="mono" style={{ fontSize: 9.5, color: "var(--ink-faint)", marginTop: 3 }}>{fmtMoneyK(val)}</div>
              </div>
              {col.map(l => <LeadCard key={l.id} l={l} onClick={() => onOpen(l.id)} />)}
            </div>
          );
        })}
      </div>
    );
  }

  function Timeline({ l }) {
    const events = [
      { t: "Now", label: `Stage: ${l.stage}`, tone: "sent", note: "Current" },
      { t: l.days === 0 ? "Today" : `${l.days}d ago`, label: "Last contact logged", tone: "plain", note: l.loan + " thread" },
      { t: "5d ago", label: "AI draft approved & sent", tone: "sent", note: "SMS · in your voice" },
      { t: "6d ago", label: "Lead entered pipeline", tone: "gold", note: `Source: ${l.source}` },
      { t: "6d ago", label: "Assistant created lead record", tone: "plain", note: "Auto-captured from CRM" },
    ];
    return (
      <div style={{ display: "flex", flexDirection: "column" }}>
        {events.map((e, i) => (
          <div key={i} style={{ display: "grid", gridTemplateColumns: "72px 1fr", gap: 14 }}>
            <span className="mono" style={{ fontSize: 10.5, color: "var(--ink-faint)", paddingTop: 2, textAlign: "right" }}>{e.t}</span>
            <div style={{ borderLeft: "1px solid var(--line)", paddingLeft: 16, paddingBottom: 18, position: "relative" }}>
              <span style={{ position: "absolute", left: -4, top: 4, width: 7, height: 7, borderRadius: 999,
                background: e.tone === "sent" ? "var(--green-lift)" : e.tone === "gold" ? "var(--gold)" : "var(--ink-faint)" }}></span>
              <div style={{ fontSize: 13.5, fontWeight: 500 }}>{e.label}</div>
              <div className="mono" style={{ fontSize: 10.5, color: "var(--ink-faint)", marginTop: 2 }}>{e.note}</div>
            </div>
          </div>
        ))}
      </div>
    );
  }

  function Detail({ id, onBack }) {
    const l = leadById[id];
    const thread = threads[id] || [];
    return (
      <div className="page">
        <button className="btn sm" onClick={onBack} style={{ marginBottom: 18 }}><I.chevL width={13} height={13} /> Back to pipeline</button>
        <div style={{ display: "grid", gridTemplateColumns: "minmax(0,1fr) 340px", gap: 16, alignItems: "start" }}>
          {/* left */}
          <div style={{ display: "flex", flexDirection: "column", gap: 16 }}>
            <div className="panel panel-pad" style={{ display: "flex", gap: 16, alignItems: "center" }}>
              <Avatar init={l.init} size={52} gold />
              <div style={{ flex: 1 }}>
                <h1 className="display" style={{ fontSize: 34 }}>{l.name}</h1>
                <LoanMeta lead={l} />
              </div>
              <div style={{ display: "flex", gap: 8 }}>
                <Btn sm icon={I.phone}>Call</Btn>
                <Btn sm kind="primary" icon={I.msg}>Message</Btn>
              </div>
            </div>

            <div className="panel">
              <div className="panel-head"><span className="eyebrow">Message history</span><span className="mono" style={{ fontSize: 10, color: "var(--ink-faint)" }}>{thread.length} messages</span></div>
              <div className="panel-pad" style={{ display: "flex", flexDirection: "column", gap: 11, maxHeight: 320, overflowY: "auto" }}>
                {thread.length ? thread.map((m, i) => (
                  <div key={i} style={{ display: "flex", justifyContent: m.from === "me" ? "flex-end" : "flex-start" }}>
                    <div style={{ maxWidth: "78%" }}>
                      <div style={{ padding: "9px 13px", fontSize: 14, lineHeight: 1.5,
                        background: m.from === "me" ? "var(--green)" : "var(--bg-2)", border: "1px solid var(--line)" }}>{m.text}</div>
                      <div className="mono" style={{ fontSize: 9, color: "var(--ink-faint)", marginTop: 3, textAlign: m.from === "me" ? "right" : "left" }}>{m.time}</div>
                    </div>
                  </div>
                )) : <div style={{ color: "var(--ink-faint)", fontSize: 13 }}>No messages logged yet.</div>}
              </div>
            </div>
          </div>

          {/* right */}
          <div style={{ display: "flex", flexDirection: "column", gap: 16 }}>
            <div className="panel">
              <div className="panel-head"><span className="eyebrow">Loan details</span></div>
              <div className="panel-pad" style={{ display: "flex", flexDirection: "column", gap: 0 }}>
                {[["Loan type", l.loan], ["Amount", fmtMoney(l.amount)], ["Stage", l.stage], ["Source", l.source], ["Phone", l.phone], ["Last contact", l.days === 0 ? "Today" : l.days + " days ago"]].map(([k, v], i, a) => (
                  <div key={k} style={{ display: "flex", justifyContent: "space-between", padding: "9px 0", borderBottom: i < a.length - 1 ? "1px solid var(--line)" : "none" }}>
                    <span className="mono" style={{ fontSize: 11, color: "var(--ink-faint)", letterSpacing: "0.06em", textTransform: "uppercase" }}>{k}</span>
                    <span style={{ fontSize: 13.5, fontWeight: 500 }}>{v}</span>
                  </div>
                ))}
              </div>
            </div>
            <div className="panel">
              <div className="panel-head"><span className="eyebrow">Status timeline · audit trail</span></div>
              <div className="panel-pad"><Timeline l={l} /></div>
            </div>
          </div>
        </div>
      </div>
    );
  }

  function Leads() {
    const [open, setOpen] = useState(null);
    const [view, setView] = useState("board");
    if (open) return <Detail id={open} onBack={() => setOpen(null)} />;
    return (
      <div className="page" style={{ maxWidth: "none" }}>
        <div className="sec-head">
          <div>
            <div className="eyebrow" style={{ marginBottom: 8 }}>Pipeline</div>
            <h1 className="display" style={{ fontSize: 34 }}>{leads.length} active leads</h1>
          </div>
          <div className="sec-meta" style={{ display: "flex", alignItems: "center", gap: 8 }}>
            <Btn sm kind={view === "board" ? "ghost-gold" : ""} icon={I.grid} onClick={() => setView("board")}>Board</Btn>
            <Btn sm icon={I.plus}>Add lead</Btn>
          </div>
        </div>
        <Board onOpen={setOpen} />
      </div>
    );
  }

  window.SCREENS = window.SCREENS || {};
  window.SCREENS.Leads = Leads;
})();
