/* CRM Leads — agent capture bar + source segments + table + convert action */
const { useState: useLd, useMemo: useLdm, useEffect: useLde } = React;


const SOURCE_META = {
  "website":       { label: "Website",     icon: "globe",  color: "var(--accent)" },
  "manual":        { label: "Manual",      icon: "pencil", color: "var(--ink-2)" },
  "sales-agent":   { label: "Sales Agent", icon: "bot",    color: "#9C7AC0" },
  "inbound-email": { label: "Inbound",     icon: "mail",   color: "#5A8AB0" },
  "referral":      { label: "Referral",    icon: "link",   color: "var(--warning)" },
};

const LEAD_STATUS = {
  new:       { label: "New",       chip: "accent" },
  qualified: { label: "Qualified", chip: "solid-accent" },
  draft:     { label: "Draft",     chip: "" },
  lost:      { label: "Lost",      chip: "" },
};

function SourceIcon({ kind, size = 14, color = "currentColor" }) {
  const p = { width: size, height: size, viewBox: "0 0 16 16", fill: "none", stroke: color, strokeWidth: 1.4, strokeLinecap: "round", strokeLinejoin: "round" };
  switch (kind) {
    case "globe":  return <svg {...p}><circle cx="8" cy="8" r="6"/><path d="M2 8h12M8 2c2 2.5 2 9 0 12M8 2c-2 2.5-2 9 0 12"/></svg>;
    case "pencil": return <svg {...p}><path d="M3 13l1-3 7-7 2 2-7 7-3 1z"/><path d="M10 4l2 2"/></svg>;
    case "bot":    return <svg {...p}><rect x="3" y="5" width="10" height="8" rx="2"/><circle cx="6" cy="9" r="0.8" fill={color}/><circle cx="10" cy="9" r="0.8" fill={color}/><path d="M8 3v2M5 13v2M11 13v2"/></svg>;
    case "mail":   return <svg {...p}><rect x="2" y="4" width="12" height="9" rx="1"/><path d="M2 5l6 4 6-4"/></svg>;
    case "link":   return <svg {...p}><path d="M7 9a3 3 0 014 0M9 7a3 3 0 010 4"/><path d="M5 11l-1 1a2 2 0 11-3-3l2-2M11 5l1-1a2 2 0 113 3l-2 2"/></svg>;
    default: return null;
  }
}

function LeadAgentBar({ onPropose }) {
  const [text, setText] = useLd("");
  const [pending, setPending] = useLd(false);
  const [proposal, setProposal] = useLd(null);
  const [error, setError] = useLd(null);

  const run = async () => {
    const t = text.trim();
    if (!t || pending) return;
    setPending(true);
    setError(null);
    setProposal(null);
    try {
      const res = await fetch(window.API_BASE + "/api/agents/extract-lead/", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ text: t }),
      });
      const parsed = await res.json();
      if (parsed.error) throw new Error(parsed.error);
      setProposal(parsed);
    } catch (e) {
      setError("Couldn't parse a lead. Add a name, company, and a sentence on what they want.");
    } finally {
      setPending(false);
    }
  };

  const accept = () => {
    if (!proposal) return;
    const channel = proposal.channel || "Email";
    const source = channel === "Form" || channel === "Chat" ? "website"
                 : channel === "Referral" ? "referral"
                 : "manual";
    onPropose({
      id: "L" + String(Date.now()).slice(-4),
      name: proposal.name || "Unknown",
      company: proposal.company || "—",
      source,
      sourceDetail: proposal.source_detail || proposal.sourceDetail || "Captured by Lead Agent",
      intent: proposal.intent || "—",
      value: Number(proposal.value) || 0,
      status: "new",
      created: "now",
      channel,
    });
    setProposal(null);
    setText("");
  };

  return (
    <div className="cust-agent">
      <div className="cust-agent-head">
        <span className="cust-agent-title">
          <span className="stat-dot active" />
          Lead Agent <em>· paste anything that sounds like a lead</em>
        </span>
        <span className="cust-agent-mode">Capture mode</span>
      </div>
      <div className="cust-agent-body">
        <textarea
          placeholder={`Paste raw inquiry — e.g. "Hi, I run a 30-person plumbing co in Squamish, saw you at the trade show, looking for a quote on your Q3 package, ~$15k budget."`}
          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 capture · Aris will extract structured fields</span>
          <button className="btn-sm solid" onClick={run} disabled={pending || !text.trim()}>
            {pending ? "Capturing…" : "Capture lead →"}
          </button>
        </div>

        {error && <div className="cust-reply" style={{borderLeftColor:"#C57A35"}}>{error}</div>}

        {proposal && (
          <div className="cust-proposal">
            <div className="cust-proposal-head">
              <span>Draft lead · 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>Channel</label><span>{proposal.channel || "—"}</span></div>
              <div><label>Value</label><span>{proposal.value ? `$${Number(proposal.value).toLocaleString()}` : "—"}</span></div>
              <div className="span-2"><label>Intent</label><span>{proposal.intent || "—"}</span></div>
              <div className="span-2"><label>Context</label><span>{proposal.sourceDetail || "—"}</span></div>
            </div>
            <div className="cust-proposal-foot">
              <button className="btn-sm" onClick={() => setProposal(null)}>Discard</button>
              <button className="btn-sm solid" onClick={accept}>+ Add to leads</button>
            </div>
          </div>
        )}
      </div>
    </div>
  );
}

function LeadIncomingFeed({ leads }) {
  const recent = leads.slice(0, 4);
  return (
    <div className="leads-feed">
      <div className="leads-feed-head">
        <span><span className="stat-dot active" /> Incoming · live</span>
        <span className="dim">last 24h</span>
      </div>
      <div className="leads-feed-body">
        {recent.length === 0 && (
          <div style={{padding:"20px 16px", color:"var(--fog)", fontFamily:"var(--font-mono)", fontSize:11, letterSpacing:"0.1em"}}>
            NO INCOMING LEADS YET
          </div>
        )}
        {recent.map(l => {
          const s = SOURCE_META[l.source];
          return (
            <div key={l.id} className="leads-feed-row">
              <span className="leads-feed-icon" style={{color: s.color}}><SourceIcon kind={s.icon} size={14} /></span>
              <div className="leads-feed-text">
                <div className="t1">{l.name} <span className="dim">· {l.company}</span></div>
                <div className="t2">{l.sourceDetail}</div>
              </div>
              <span className="leads-feed-time">{l.created}</span>
            </div>
          );
        })}
      </div>
    </div>
  );
}

function LeadsTable({ rows, onConvert, onDismiss }) {
  return (
    <div className="card">
      <div className="card-head">
        <span className="title">Leads · {rows.length}</span>
        <span className="meta">Sorted newest first</span>
      </div>
      <div className="card-body" style={{padding: 0}}>
        <table className="cust-table">
          <thead>
            <tr>
              <th>ID</th>
              <th>Lead</th>
              <th>Source</th>
              <th>Intent</th>
              <th>Status</th>
              <th>Created</th>
              <th style={{textAlign:"right"}}>Value</th>
              <th style={{textAlign:"right"}}>Action</th>
            </tr>
          </thead>
          <tbody>
            {rows.length === 0 && (
              <tr>
                <td colSpan={8} style={{padding:"52px 24px", textAlign:"center", color:"var(--fog)", fontFamily:"var(--font-mono)", fontSize:11, letterSpacing:"0.1em"}}>
                  NO LEADS YET · USE THE AGENT BAR ABOVE TO CAPTURE YOUR FIRST LEAD
                </td>
              </tr>
            )}
            {rows.map(r => {
              const s = SOURCE_META[r.source];
              const st = LEAD_STATUS[r.status];
              const isNew = /^\d+m$/.test(r.created) || /^\d+h$/.test(r.created);
              return (
                <tr key={r.id}>
                  <td className="dim" style={{fontFamily:"var(--font-mono)", fontSize:11.5}}>{r.id}</td>
                  <td>
                    <div className="cust-name-cell">
                      <span className="cust-avatar">{r.name.split(" ").map(p=>p[0]).slice(0,2).join("")}</span>
                      <div>
                        <div style={{display:"flex", alignItems:"center", gap:6}}>
                          {r.name}
                          {isNew && <span className="dot-new" title="New" />}
                        </div>
                        <div className="sub">{r.company}</div>
                      </div>
                    </div>
                  </td>
                  <td>
                    <span className="lead-source-pill" style={{borderColor: s.color, color: s.color}}>
                      <SourceIcon kind={s.icon} size={12} />
                      {s.label}
                    </span>
                    <div className="sub" style={{marginTop:4}}>{r.sourceDetail}</div>
                  </td>
                  <td className="dim" style={{maxWidth: 220}}>{r.intent}</td>
                  <td><span className={`chip ${st.chip}`}>{st.label}</span></td>
                  <td className="dim">{r.created} ago</td>
                  <td style={{textAlign:"right"}} className="amount">{r.value ? `$${r.value.toLocaleString()}` : <span className="dim">—</span>}</td>
                  <td style={{textAlign:"right"}}>
                    <div style={{display:"inline-flex", gap:6, justifyContent:"flex-end"}}>
                      <button
                        className="row-action"
                        onClick={() => onConvert(r)}
                        disabled={r.status === "lost"}
                        title="Promote to a customer record"
                      >Convert →</button>
                      <button className="row-action ghost" onClick={() => onDismiss(r)} title="Dismiss">×</button>
                    </div>
                  </td>
                </tr>
              );
            })}
          </tbody>
        </table>
      </div>
    </div>
  );
}

/* Transform a backend Lead record into the frontend shape */
function adaptLead(l) {
  const src = window.mapLeadSource(l.source);
  const srcMeta = {
    website:       { detail: "Website inquiry",     channel: "Form" },
    manual:        { detail: "Manually added",      channel: "Phone" },
    "sales-agent": { detail: "Aris Sales outbound", channel: "Email" },
    "inbound-email":{ detail: "Inbound email",      channel: "Email" },
    referral:      { detail: l.source || "Referral",channel: "Referral" },
  };
  const meta = srcMeta[src] || { detail: l.source || "—", channel: "Email" };
  return {
    id:           "L" + String(l.id).padStart(4, "0"),
    name:         l.name || "Unknown",
    company:      l.company || "—",
    source:       src,
    sourceDetail: l.notes ? l.notes.slice(0, 60) : meta.detail,
    intent:       l.notes || "—",
    value:        parseFloat(l.value) || 0,
    status:       window.mapLeadStatus(l.stage),
    created:      window.timeSince(l.created_at),
    channel:      meta.channel,
  };
}

/* ── Manual new-lead form ────────────────────────────────────────────────── */
function NewLeadModal({ onAdd, onClose }) {
  const CHANNELS = ["Email", "Phone", "Form", "Chat", "Referral", "In-person", "LinkedIn"];
  const SOURCES  = [
    { id: "manual",        label: "Manual entry" },
    { id: "website",       label: "Website" },
    { id: "referral",      label: "Referral" },
    { id: "inbound-email", label: "Inbound email" },
    { id: "sales-agent",   label: "Sales Agent" },
  ];
  const [f, setF] = useLd({
    name: "", company: "", channel: "Email", source: "manual",
    sourceDetail: "", intent: "", value: "",
  });
  const [saving, setSaving] = useLd(false);

  const set = (k, v) => setF(prev => ({ ...prev, [k]: v }));

  const submit = async () => {
    if (!f.name.trim()) return;
    setSaving(true);
    const lead = {
      id:           "L" + String(Date.now()).slice(-4),
      name:         f.name.trim(),
      company:      f.company.trim() || "—",
      source:       f.source,
      sourceDetail: f.sourceDetail.trim() || "Manually added",
      intent:       f.intent.trim() || "—",
      value:        parseFloat(f.value) || 0,
      status:       "new",
      created:      "now",
      channel:      f.channel,
    };
    /* Persist to backend */
    try {
      await fetch(window.API_BASE + "/api/leads/", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({
          name:    lead.name,
          company: lead.company,
          source:  f.sourceDetail || f.channel,
          stage:   "new",
          value:   lead.value,
          notes:   lead.intent,
        }),
      });
    } catch (_) {}
    onAdd(lead);
    setSaving(false);
    onClose();
  };

  return (
    <>
      <div className="cust-drawer-scrim" onClick={onClose} />
      <aside className="cust-drawer" style={{maxWidth: 420}}>
        <header className="cust-drawer-head">
          <div style={{fontFamily:"var(--font-serif)", fontSize:20, fontWeight:400}}>New Lead</div>
          <button className="cust-drawer-close" onClick={onClose}>✕</button>
        </header>
        <div style={{padding:"16px 24px", display:"flex", flexDirection:"column", gap:14}}>
          {[
            { label:"Name *",         key:"name",         type:"text",   placeholder:"Full name" },
            { label:"Company",        key:"company",      type:"text",   placeholder:"Company name" },
            { label:"Intent / notes", key:"intent",       type:"text",   placeholder:"What are they looking for?" },
            { label:"Source detail",  key:"sourceDetail", type:"text",   placeholder:"e.g. Met at Whistler trade show" },
            { label:"Value ($)",      key:"value",        type:"number", placeholder:"0" },
          ].map(({ label, key, type, placeholder }) => (
            <div key={key}>
              <div style={{fontSize:10, letterSpacing:"0.12em", textTransform:"uppercase", color:"var(--ink-2)", marginBottom:5}}>{label}</div>
              <input
                type={type}
                placeholder={placeholder}
                value={f[key]}
                onChange={e => set(key, e.target.value)}
                style={{width:"100%", background:"var(--canvas)", border:"1px solid var(--rule)", color:"var(--ink-1)", padding:"7px 10px", borderRadius:2, fontSize:13, boxSizing:"border-box"}}
              />
            </div>
          ))}
          <div style={{display:"grid", gridTemplateColumns:"1fr 1fr", gap:12}}>
            <div>
              <div style={{fontSize:10, letterSpacing:"0.12em", textTransform:"uppercase", color:"var(--ink-2)", marginBottom:5}}>Source</div>
              <select value={f.source} onChange={e => set("source", e.target.value)}
                style={{width:"100%", background:"var(--canvas)", border:"1px solid var(--rule)", color:"var(--ink-1)", padding:"7px 10px", borderRadius:2, fontSize:13}}>
                {SOURCES.map(s => <option key={s.id} value={s.id}>{s.label}</option>)}
              </select>
            </div>
            <div>
              <div style={{fontSize:10, letterSpacing:"0.12em", textTransform:"uppercase", color:"var(--ink-2)", marginBottom:5}}>Channel</div>
              <select value={f.channel} onChange={e => set("channel", e.target.value)}
                style={{width:"100%", background:"var(--canvas)", border:"1px solid var(--rule)", color:"var(--ink-1)", padding:"7px 10px", borderRadius:2, fontSize:13}}>
                {CHANNELS.map(c => <option key={c} value={c}>{c}</option>)}
              </select>
            </div>
          </div>
        </div>
        <div className="cust-drawer-foot">
          <button className="btn-sm" onClick={onClose}>Cancel</button>
          <button className="btn-sm solid" onClick={submit} disabled={saving || !f.name.trim()}>
            {saving ? "Saving…" : "+ Add lead"}
          </button>
        </div>
      </aside>
    </>
  );
}

function Leads() {
  const [list, setList] = useLd([]);
  const [loading, setLoading] = useLd(true);
  const [showForm, setShowForm] = useLd(false);
  const [seg, setSeg] = useLd("all");

  /* Load leads from backend on mount */
  useLde(() => {
    fetch(window.API_BASE + "/api/leads/")
      .then(r => r.json())
      .then(data => {
        setList(Array.isArray(data) ? data.map(adaptLead) : []);
      })
      .catch(() => setList([]))
      .finally(() => setLoading(false));
  }, []);
  const [toast, setToast] = useLd(null);

  const counts = useLdm(() => {
    const c = { all: list.length, website: 0, manual: 0, "sales-agent": 0, "inbound-email": 0, referral: 0 };
    list.forEach(r => { if (c[r.source] !== undefined) c[r.source]++; });
    return c;
  }, [list]);

  const rows = useLdm(() => seg === "all" ? list : list.filter(l => l.source === seg), [list, seg]);

  const addLead = (lead) => {
    setList(l => [lead, ...l]);
    setToast(`Added lead · ${lead.name}`);
    setTimeout(() => setToast(null), 2400);
    /* Persist to backend (best-effort) */
    fetch(window.API_BASE + "/api/leads/", {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({
        name:   lead.name,
        company: lead.company,
        source: lead.sourceDetail || lead.channel || "",
        stage:  "new",
        value:  lead.value || 0,
        notes:  lead.intent || "",
      }),
    }).catch(() => {/* silent — UI already updated */});
  };

  const convert = (lead) => {
    window.__customerStore.add({
      id: "c" + lead.id,
      name: lead.name,
      company: lead.company,
      size: "—",
      source: lead.channel || "Web",
      value: lead.value || 0,
      status: "new",
      lastTouch: "now",
      owner: "JM",
      note: `Converted from lead ${lead.id}. ${lead.intent}`,
      nextAction: "First call",
    });
    setList(l => l.filter(x => x.id !== lead.id));
    setToast(`${lead.name} promoted to Customers`);
    setTimeout(() => setToast(null), 2400);
  };

  const dismiss = (lead) => {
    setList(l => l.filter(x => x.id !== lead.id));
  };

  const segs = [
    { id: "all",            label: "All",          n: counts.all },
    { id: "website",        label: "Website",      n: counts.website },
    { id: "manual",         label: "Manual",       n: counts.manual },
    { id: "sales-agent",    label: "Sales Agent",  n: counts["sales-agent"] },
    { id: "inbound-email",  label: "Inbound",      n: counts["inbound-email"] },
    { id: "referral",       label: "Referral",     n: counts.referral },
  ];

  return (
    <>
      <div className="page-head">
        <div className="meta">
          <span className="coord">Leads</span>
          <span className="coord" style={{opacity: 0.6}}>{list.length} active · across {Object.keys(SOURCE_META).length} sources</span>
        </div>
        <h1>Leads, <em>wherever they come from.</em></h1>
        <div className="actions">
          <button className="btn-sm solid" onClick={() => setShowForm(true)}>+ New lead</button>
        </div>
      </div>

      <div className="leads-top-grid">
        <LeadAgentBar onPropose={addLead} />
        <LeadIncomingFeed leads={list} />
      </div>

      <div className="cust-segments">
        {segs.map(s => {
          const meta = SOURCE_META[s.id];
          return (
            <button
              key={s.id}
              className={`cust-seg ${seg === s.id ? "active" : ""}`}
              onClick={() => setSeg(s.id)}
            >
              {meta && <SourceIcon kind={meta.icon} size={12} />}
              <span>{s.label}</span>
              <span className="n">{s.n}</span>
            </button>
          );
        })}
      </div>

      <LeadsTable rows={rows} onConvert={convert} onDismiss={dismiss} />

      {toast && <div className="leads-toast">{toast}</div>}

      {showForm && (
        <NewLeadModal
          onAdd={addLead}
          onClose={() => setShowForm(false)}
        />
      )}
    </>
  );
}

Object.assign(window, { Leads });
