/* CRM Customers — agent bar + segments + table + detail drawer */
const { useState: useCs, useMemo: useCsm, useEffect: useCse, useRef: useCsr } = React;


const STATUS_LABEL = {
  new:     { label: "New",         chip: "" },
  qualify: { label: "Qualifying",  chip: "accent" },
  active:  { label: "Active",      chip: "accent" },
  waiting: { label: "Waiting",     chip: "" },
  renewal: { label: "Renewal",     chip: "warn" },
  won:     { label: "Won",         chip: "solid-accent" },
  cold:    { label: "Cold",        chip: "" },
};

function CustomerAgentBar({ selected, onProposeNew, onAnalyze, customers }) {
  const [text, setText] = useCs("");
  const [pending, setPending] = useCs(false);
  const [reply, setReply] = useCs(null);
  const [proposal, setProposal] = useCs(null);

  const mode = selected ? "analyze" : "extract";

  const run = async () => {
    const t = text.trim();
    if (!t || pending) return;
    setPending(true);
    setReply(null);
    setProposal(null);

    try {
      if (mode === "extract") {
        const prompt = `You extract structured customer records from sales notes. Return ONLY valid JSON, no prose, no markdown fences. Schema: {"name":"string","company":"string","size":"string with 'ppl' suffix or empty","source":"one of: Trade show, Referral, Web, Cold email, Cold call, Email, LinkedIn","value":number_in_dollars_or_0,"status":"one of: new, qualify, active, waiting, renewal, won, cold","note":"one short sentence","nextAction":"short action phrase"}\n\nNotes:\n${t}\n\nJSON:`;
        const out = await window.claude.complete(prompt);
        let parsed = null;
        try {
          const cleaned = (out || "").trim().replace(/^```json?/i, "").replace(/```$/, "").trim();
          parsed = JSON.parse(cleaned);
        } catch (e) {
          setReply("Couldn't parse a record from that. Try adding name, company, and a hint of intent.");
        }
        if (parsed) setProposal(parsed);
      } else {
        const c = selected;
        const prompt = `You are a CRM analyst. The user is asking about a specific customer. Be brief (2-4 sentences), specific, and actionable. Don't use markdown.\n\nCustomer:\nName: ${c.name}\nCompany: ${c.company}\nSize: ${c.size}\nSource: ${c.source}\nValue: $${c.value.toLocaleString()}\nStatus: ${STATUS_LABEL[c.status]?.label}\nLast touch: ${c.lastTouch} ago\nNote: ${c.note}\nNext action: ${c.nextAction}\n\nQuestion: ${t}\n\nAnswer:`;
        const out = await window.claude.complete(prompt);
        setReply((out || "").trim());
      }
    } catch (e) {
      setReply("Agent unavailable right now. Try again in a moment.");
    } finally {
      setPending(false);
    }
  };

  const accept = () => {
    if (proposal && onProposeNew) onProposeNew({
      id: "c" + String(Date.now()).slice(-4),
      name: proposal.name || "Unknown",
      company: proposal.company || "—",
      size: proposal.size || "—",
      source: proposal.source || "Web",
      value: Number(proposal.value) || 0,
      status: proposal.status || "new",
      lastTouch: "now",
      owner: "JM",
      note: proposal.note || "",
      nextAction: proposal.nextAction || "",
    });
    setProposal(null);
    setText("");
    setReply("Added.");
  };

  return (
    <div className="cust-agent">
      <div className="cust-agent-head">
        <span className="cust-agent-title">
          <span className="stat-dot active" />
          Customer Agent {selected ? <em>· analyzing {selected.name}</em> : <em>· paste notes to add a customer</em>}
        </span>
        <span className="cust-agent-mode">{mode === "extract" ? "Extract mode" : "Analyze mode"}</span>
      </div>
      <div className="cust-agent-body">
        <textarea
          placeholder={selected
            ? `Ask about ${selected.name} — e.g. "How healthy is this account?" or "Draft a check-in email."`
            : `Paste notes — e.g. "Met Karen at the Whistler trade show, runs a 12-person landscape co, interested in our Q3 package, $12k range, follow up next week."`}
          value={text}
          onChange={e => setText(e.target.value)}
          onKeyDown={e => { if (e.key === "Enter" && (e.metaKey || e.ctrlKey)) run(); }}
        />
        <div className="cust-agent-foot">
          <span className="hint">⌘ ↵ to run · {mode === "extract" ? "Aris will draft a record for you to confirm" : "Aris will analyze the selected customer"}</span>
          <button className="btn-sm solid" onClick={run} disabled={pending || !text.trim()}>
            {pending ? "Working…" : (mode === "extract" ? "Extract record →" : "Ask Aris →")}
          </button>
        </div>

        {proposal && (
          <div className="cust-proposal">
            <div className="cust-proposal-head">
              <span>Draft record · review and confirm</span>
              <button className="link" onClick={() => setProposal(null)}>discard</button>
            </div>
            <div className="cust-proposal-grid">
              <div><label>Name</label><span>{proposal.name || "—"}</span></div>
              <div><label>Company</label><span>{proposal.company || "—"}</span></div>
              <div><label>Size</label><span>{proposal.size || "—"}</span></div>
              <div><label>Source</label><span>{proposal.source || "—"}</span></div>
              <div><label>Value</label><span>${(Number(proposal.value)||0).toLocaleString()}</span></div>
              <div><label>Status</label><span>{STATUS_LABEL[proposal.status]?.label || proposal.status || "—"}</span></div>
              <div className="span-2"><label>Note</label><span>{proposal.note || "—"}</span></div>
              <div className="span-2"><label>Next action</label><span>{proposal.nextAction || "—"}</span></div>
            </div>
            <div className="cust-proposal-foot">
              <button className="btn-sm" onClick={() => setProposal(null)}>Edit later</button>
              <button className="btn-sm solid" onClick={accept}>+ Add customer</button>
            </div>
          </div>
        )}

        {reply && !proposal && (
          <div className="cust-reply">{reply}</div>
        )}
      </div>
    </div>
  );
}

function SegmentBar({ counts, active, onChange }) {
  const segs = [
    { id: "all",     label: "All",          n: counts.all },
    { id: "active",  label: "Active",       n: counts.active },
    { id: "renewal", label: "Renewal soon", n: counts.renewal },
    { id: "qualify", label: "Qualifying",   n: counts.qualify },
    { id: "new",     label: "New",          n: counts.new },
    { id: "waiting", label: "Waiting",      n: counts.waiting },
    { id: "cold",    label: "Cold",         n: counts.cold },
    { id: "won",     label: "Won",          n: counts.won },
  ];
  return (
    <div className="cust-segments">
      {segs.map(s => (
        <button
          key={s.id}
          className={`cust-seg ${active === s.id ? "active" : ""}`}
          onClick={() => onChange(s.id)}
        >
          <span>{s.label}</span>
          <span className="n">{s.n}</span>
        </button>
      ))}
    </div>
  );
}

function CustomerTable({ rows, sort, onSort, onSelect, selectedId }) {
  const cols = [
    { id: "name",       label: "Name" },
    { id: "company",    label: "Company" },
    { id: "status",     label: "Status" },
    { id: "owner",      label: "Owner" },
    { id: "lastTouch",  label: "Last touch" },
    { id: "value",      label: "Value", right: true },
  ];
  return (
    <div className="card">
      <div className="card-head">
        <span className="title">Customers · {rows.length}</span>
        <span className="meta">Click a row to open</span>
      </div>
      <div className="card-body" style={{padding:0}}>
        <table className="cust-table">
          <thead>
            <tr>
              {cols.map(c => (
                <th
                  key={c.id}
                  style={{textAlign: c.right ? "right" : "left"}}
                  onClick={() => onSort(c.id)}
                >
                  {c.label}
                  {sort.key === c.id && <span className="sort-arrow"> {sort.dir === "asc" ? "↑" : "↓"}</span>}
                </th>
              ))}
            </tr>
          </thead>
          <tbody>
            {rows.length === 0 && (
              <tr>
                <td colSpan={6} style={{padding:"52px 24px", textAlign:"center", color:"var(--fog)", fontFamily:"var(--font-mono)", fontSize:11, letterSpacing:"0.1em"}}>
                  NO CUSTOMERS YET · USE THE AGENT BAR ABOVE TO ADD YOUR FIRST RECORD
                </td>
              </tr>
            )}
            {rows.map(r => {
              const s = STATUS_LABEL[r.status] || { label: r.status, chip: "" };
              return (
                <tr key={r.id} className={selectedId === r.id ? "selected" : ""} onClick={() => onSelect(r)}>
                  <td>
                    <div className="cust-name-cell">
                      <span className="cust-avatar">{r.name.split(" ").map(p => p[0]).slice(0,2).join("")}</span>
                      {r.name}
                    </div>
                  </td>
                  <td className="dim">{r.company}<div className="sub">{r.size}</div></td>
                  <td><span className={`chip ${s.chip}`}>{s.label}</span></td>
                  <td className="dim">{r.owner}</td>
                  <td className="dim">{r.lastTouch} ago</td>
                  <td style={{textAlign:"right"}} className="amount">${r.value.toLocaleString()}</td>
                </tr>
              );
            })}
          </tbody>
        </table>
      </div>
    </div>
  );
}

function CustomerDrawer({ customer, onClose, onAsk }) {
  if (!customer) return null;
  const s = STATUS_LABEL[customer.status] || { label: customer.status, chip: "" };
  const timeline = [
    { ts: "Today",        agent: "CLIENT",     desc: "Email opened — proposal v2" },
    { ts: "Yesterday",    agent: "ARIS",       desc: "Auto-summary added to record" },
    { ts: "3 days ago",   agent: "FINANCE",    desc: "Invoice #284 sent · $4,400" },
    { ts: "Last week",    agent: "PRODUCTION", desc: "Site survey scheduled · Whistler" },
    { ts: "2 weeks ago",  agent: "CLIENT",     desc: "Discovery call · 38 min" },
  ];
  return (
    <>
      <div className="cust-drawer-scrim" onClick={onClose} />
      <aside className="cust-drawer">
        <header className="cust-drawer-head">
          <div className="cust-drawer-id">
            <span className="cust-avatar lg">{customer.name.split(" ").map(p => p[0]).slice(0,2).join("")}</span>
            <div>
              <div className="name">{customer.name}</div>
              <div className="company">{customer.company} · {customer.size}</div>
            </div>
          </div>
          <button className="cust-drawer-close" onClick={onClose}>✕</button>
        </header>

        <div className="cust-drawer-pills">
          <span className={`chip ${s.chip}`}>{s.label}</span>
          <span className="chip">{customer.source}</span>
          <span className="chip">Owner · {customer.owner}</span>
          <span className="chip">Last touch · {customer.lastTouch} ago</span>
        </div>

        <div className="cust-drawer-stats">
          <div><label>Deal value</label><span>${customer.value.toLocaleString()}</span></div>
          <div><label>Health</label><span>{customer.status === "cold" ? "At risk" : customer.status === "renewal" ? "Watch" : "Healthy"}</span></div>
          <div><label>Next action</label><span>{customer.nextAction}</span></div>
        </div>

        <div className="cust-drawer-section">
          <div className="cust-drawer-section-head">
            <span>Note</span>
          </div>
          <p className="cust-drawer-note">{customer.note}</p>
        </div>

        <div className="cust-drawer-section">
          <div className="cust-drawer-section-head">
            <span>Activity</span>
            <span className="dim">5 events</span>
          </div>
          <div className="cust-drawer-timeline">
            {timeline.map((t, i) => (
              <div key={i} className="cust-tl-row">
                <span className="cust-tl-dot" />
                <div className="cust-tl-body">
                  <div className="cust-tl-line"><strong>{t.agent}</strong> · {t.desc}</div>
                  <div className="cust-tl-ts">{t.ts}</div>
                </div>
              </div>
            ))}
          </div>
        </div>

        <div className="cust-drawer-foot">
          <button className="btn-sm" onClick={onAsk}>Ask the agent ↑</button>
          <button className="btn-sm solid">Open full record →</button>
        </div>
      </aside>
    </>
  );
}

/* Transform a backend Customer record into the frontend shape */
function adaptCustomer(c) {
  return {
    id:         String(c.id),
    name:       c.name || "Unknown",
    company:    c.company || "—",
    size:       "—",
    source:     "Web",
    value:      0,
    status:     window.mapCustomerStatus(c.status),
    lastTouch:  window.timeSince(c.updated_at),
    owner:      "—",
    note:       c.notes || "",
    nextAction: "—",
    email:      c.email || "",
  };
}

function Customers() {
  const [list, setList] = useCs([]);
  const [loading, setLoading] = useCs(true);
  const [seg, setSeg] = useCs("all");
  const [sort, setSort] = useCs({ key: "lastTouch", dir: "asc" });
  const [selected, setSelected] = useCs(null);
  const [query, setQuery] = useCs("");

  /* Load customers from backend on mount */
  useCse(() => {
    fetch(window.API_BASE + "/api/customers/")
      .then(r => r.json())
      .then(data => {
        setList(Array.isArray(data) ? data.map(adaptCustomer) : []);
      })
      .catch(() => setList([]))
      .finally(() => setLoading(false));
  }, []);

  const counts = useCsm(() => {
    const c = { all: list.length, active: 0, renewal: 0, qualify: 0, new: 0, waiting: 0, cold: 0, won: 0 };
    list.forEach(r => { if (c[r.status] !== undefined) c[r.status]++; });
    return c;
  }, [list]);

  const rows = useCsm(() => {
    let r = list;
    if (seg !== "all") r = r.filter(x => x.status === seg);
    if (query.trim()) {
      const q = query.toLowerCase();
      r = r.filter(x => (x.name + " " + x.company).toLowerCase().includes(q));
    }
    const dir = sort.dir === "asc" ? 1 : -1;
    r = [...r].sort((a, b) => {
      const av = a[sort.key], bv = b[sort.key];
      if (typeof av === "number" && typeof bv === "number") return (av - bv) * dir;
      return String(av).localeCompare(String(bv)) * dir;
    });
    return r;
  }, [list, seg, sort, query]);

  const onSort = (key) => {
    setSort(prev => prev.key === key ? { key, dir: prev.dir === "asc" ? "desc" : "asc" } : { key, dir: "asc" });
  };

  const addCustomer = (c) => {
    setList(l => [c, ...l]);
    /* Persist to backend (best-effort) */
    fetch(window.API_BASE + "/api/customers/", {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({
        name:    c.name,
        company: c.company,
        email:   c.email || (c.name.toLowerCase().replace(/\s+/g,"") + "@placeholder.local"),
        status:  "prospect",
        notes:   c.note || "",
      }),
    }).catch(() => {/* silent — UI already updated */});
  };

  return (
    <>
      <div className="page-head">
        <div className="meta">
          <span className="coord">Customers</span>
          <span className="coord" style={{opacity: 0.6}}>{list.length} total · {counts.active} active</span>
        </div>
        <h1>Your <em>book of business.</em></h1>
        <div className="actions">
          <input
            type="text"
            placeholder="Search…"
            value={query}
            onChange={e => setQuery(e.target.value)}
            className="cust-search"
          />
          <button className="btn-sm">Export</button>
          <button className="btn-sm solid">+ New customer</button>
        </div>
      </div>

      <CustomerAgentBar
        selected={selected}
        onProposeNew={addCustomer}
        customers={list}
      />

      <SegmentBar counts={counts} active={seg} onChange={setSeg} />

      <CustomerTable
        rows={rows}
        sort={sort}
        onSort={onSort}
        onSelect={setSelected}
        selectedId={selected?.id}
      />

      <CustomerDrawer
        customer={selected}
        onClose={() => setSelected(null)}
        onAsk={() => { setSelected(null); window.scrollTo({ top: 0, behavior: "smooth" }); }}
      />
    </>
  );
}

Object.assign(window, { Customers });
