// SF Logistics — v2 CRM (luxury console)
const { useState: cuS, useEffect: cuE, useMemo: cuM } = React;

function StatusPill({ status }) {
  const map = { open:"s-open", booked:"s-booked", transit:"s-transit", delivered:"s-delivered",
    new:"s-new", review:"s-review", approved:"s-approved", rejected:"s-rejected" };
  return <span className={`status-pill ${map[status]||""}`}>{status === "transit" ? "in-transit" : status}</span>;
}

const PHASES = (window.SFL_DATA && window.SFL_DATA.phases) || [];
const phaseByKey = (k) => PHASES.find(p => p.key === k);
const phaseIdx = (k) => PHASES.findIndex(p => p.key === k);

function PhasePill({ phase, compact }) {
  const p = phaseByKey(phase) || { label: phase || "—", tone: "muted", short: "—" };
  return (
    <span className={`phase-pill phase-${p.tone}`} title={p.label}>
      <span className="dot"></span>
      <span className="lbl">{compact ? p.short : p.label}</span>
    </span>
  );
}

function PhaseTimeline({ phase, onAdvance, onSet }) {
  const idx = phaseIdx(phase);
  return (
    <div className="phase-timeline">
      {PHASES.map((p, i) => {
        const state = i < idx ? "done" : i === idx ? "current" : "future";
        return (
          <button key={p.key} type="button" className={`pt-step pt-${p.tone} pt-${state}`} onClick={() => onSet && onSet(p.key)}>
            <span className="pt-dot">
              {state === "done" && <span className="check">✓</span>}
              {state === "current" && <span className="ring"></span>}
            </span>
            <span className="pt-info">
              <span className="pt-stage">{p.stage}</span>
              <span className="pt-label">{p.label}</span>
            </span>
          </button>
        );
      })}
      {idx >= 0 && idx < PHASES.length - 1 && onAdvance && (
        <button type="button" className="btn btn-primary pt-advance" onClick={onAdvance}>
          Advance to "{PHASES[idx + 1].label}" →
        </button>
      )}
    </div>
  );
}

function CrmLogin({ onLogin }) {
  const [pw, setPw] = cuS("");
  const [err, setErr] = cuS(false);
  const submit = (e) => {
    e.preventDefault();
    if (pw === "demo") onLogin();
    else { setErr(true); setTimeout(() => setErr(false), 1400); }
  };
  return (
    <div className="crm-login">
      <form className="login-card" onSubmit={submit}>
        <div className="top-mark">
          <span className="brand-mark">SF</span>
          <span className="lbl">DISPATCH CONSOLE · INTERNAL</span>
        </div>
        <h1>Sign in to <span className="it">the desk.</span></h1>
        <p className="lead">Operator-only. The console aggregates loads from DAT, Truckstop, Sylectus + direct shippers, and the live driver application pipeline.</p>
        <label className="field">
          <span className="lbl">Password</span>
          <input type="password" value={pw} onChange={e => setPw(e.target.value)} placeholder="••••••••" autoFocus
            style={err ? { borderBottomColor: "var(--signal-bad)" } : {}} />
        </label>
        <button className="btn btn-primary dark-bg" type="submit" style={{justifyContent:"center"}}>Enter dispatch →</button>
        <div className="hint">DEMO · password is <strong>demo</strong></div>
      </form>
    </div>
  );
}

function Kpi({ k, v, suffix, delta, accent }) {
  return (
    <div className={`kpi ${accent ? "accent" : ""}`}>
      <div className="k">{k}</div>
      <div className="v">{v}{suffix && <small>{suffix}</small>}</div>
      {delta && <div className={`delta ${delta.startsWith("−")?"down":""}`}>{delta}</div>}
    </div>
  );
}

function Toolbar({ search, setSearch, filters, statuses, statusKey, equipKey, sourceKey, setStatusKey, setEquipKey, setSourceKey, equipments, sources }) {
  return (
    <div className="toolbar">
      <div className="search">
        <Icon name="search" size={15} />
        <input value={search} onChange={e => setSearch(e.target.value)} placeholder="Search lane, broker, ID, name…" />
      </div>
      {filters.map(f => (
        <button key={f.k} className={`chip ${statusKey === f.k ? "active" : ""}`} onClick={() => setStatusKey(f.k)}>
          {f.label} <span className="ct">{f.count}</span>
        </button>
      ))}
      {equipments && (
        <select value={equipKey} onChange={e => setEquipKey(e.target.value)}>
          <option value="">All equipment</option>
          {equipments.map(e => <option key={e}>{e}</option>)}
        </select>
      )}
      {sources && (
        <select value={sourceKey} onChange={e => setSourceKey(e.target.value)}>
          <option value="">All sources</option>
          {sources.map(s => <option key={s}>{s}</option>)}
        </select>
      )}
    </div>
  );
}

function LoadsTab({ loads, setLoads, openLoad }) {
  const [search, setSearch] = cuS("");
  const [statusKey, setStatusKey] = cuS("all");
  const [equipKey, setEquipKey] = cuS("");
  const [sourceKey, setSourceKey] = cuS("");
  const equipments = cuM(() => [...new Set(loads.map(l => l.equipment))], [loads]);
  const sources = cuM(() => [...new Set(loads.map(l => l.source))], [loads]);

  const counts = cuM(() => ({
    all: loads.length,
    open: loads.filter(l => l.status === "open").length,
    booked: loads.filter(l => l.status === "booked").length,
    transit: loads.filter(l => l.status === "transit").length,
    delivered: loads.filter(l => l.status === "delivered").length,
  }), [loads]);

  const filters = [
    { k: "all", label: "All", count: counts.all },
    { k: "open", label: "Open", count: counts.open },
    { k: "booked", label: "Booked", count: counts.booked },
    { k: "transit", label: "In-transit", count: counts.transit },
    { k: "delivered", label: "Delivered", count: counts.delivered },
  ];

  const filtered = cuM(() => loads.filter(l => {
    if (statusKey !== "all" && l.status !== statusKey) return false;
    if (equipKey && l.equipment !== equipKey) return false;
    if (sourceKey && l.source !== sourceKey) return false;
    if (search) {
      const q = search.toLowerCase();
      const hay = `${l.id} ${l.origin} ${l.dest} ${l.broker} ${l.commodity}`.toLowerCase();
      if (!hay.includes(q)) return false;
    }
    return true;
  }), [loads, statusKey, equipKey, sourceKey, search]);

  const totalRev = loads.reduce((a,l) => a + (l.rate || 0), 0);
  const openRev = loads.filter(l => l.status === "open").reduce((a,l) => a + (l.rate || 0), 0);
  const inTransitRev = loads.filter(l => l.status === "transit").reduce((a,l) => a + (l.rate || 0), 0);
  const ratedLoads = loads.filter(l => l.rate > 0 && l.rpm > 0);
  const avgRpm = ratedLoads.length ? (ratedLoads.reduce((a,l)=>a+l.rpm,0)/ratedLoads.length).toFixed(2) : "—";

  const exportCsv = () => {
    const headers = ["id","origin","dest","equipment","rate","rpm","broker","source","status"];
    const rows = filtered.map(l => headers.map(h => `"${l[h]||""}"`).join(","));
    const csv = [headers.join(","), ...rows].join("\n");
    const blob = new Blob([csv], { type: "text/csv" });
    const a = document.createElement("a");
    a.href = URL.createObjectURL(blob);
    a.download = `sfl-loads-${Date.now()}.csv`;
    a.click();
  };

  return (
    <React.Fragment>
      <div className="crm-head">
        <div>
          <div className="sub"><span className="live-dot"></span>LIVE · DAT · TRUCKSTOP · SYLECTUS · DIRECT</div>
          <h1>Load board.</h1>
        </div>
        <div className="crm-head-actions">
          <button className="btn" onClick={exportCsv}><Icon name="export" size={14} /> Export CSV</button>
          <button className="btn btn-primary">+ New load</button>
        </div>
      </div>

      <div className="kpis">
        <Kpi k="Total loads" v={loads.length} delta="+12 today" accent />
        <Kpi k="Open" v={counts.open} suffix={`/ ${loads.length}`} />
        <Kpi k="In-transit" v={counts.transit} />
        <Kpi k="Pipeline value" v={`$${(totalRev/1000).toFixed(1)}k`} delta="+8.4%" />
        <Kpi k="Avg RPM" v={avgRpm} suffix={avgRpm === "—" ? "" : "$/mi"} delta={avgRpm === "—" ? null : "+0.18"} />
      </div>

      <Toolbar search={search} setSearch={setSearch} filters={filters}
        statusKey={statusKey} setStatusKey={setStatusKey}
        equipKey={equipKey} setEquipKey={setEquipKey}
        sourceKey={sourceKey} setSourceKey={setSourceKey}
        equipments={equipments} sources={sources} />

      <div className="table">
        <div className="table-head cells-loads">
          <div>ID</div><div>Lane</div><div>Equipment</div><div>Pickup → Delv</div><div>Source</div><div>Rate</div><div>Status</div>
        </div>
        {filtered.map(l => (
          <div key={l.id} className={`table-row cells-loads${l.isLead ? " is-lead" : ""}`} onClick={() => openLoad(l)}>
            <div className="tcell-id">{l.id}{l.isLead && <span className="lead-tag">NEW</span>}</div>
            <div className="tcell-lane">
              <span className="ln1">{l.origin} → {l.dest}</span>
              <span className="ln2">{l.miles ? `${l.miles.toLocaleString()} mi · ` : ""}{l.broker}</span>
            </div>
            <div className="tcell-mono">{l.equipment}</div>
            <div className="tcell-mono">{l.pickup} → {l.delivery}</div>
            <div className="tcell-mono">{l.source}</div>
            <div className="tcell-rate">{l.rate ? `$${l.rate.toLocaleString()}` : "TBD"}{l.rate ? <small>${l.rpm.toFixed(2)}/mi</small> : null}</div>
            <div><StatusPill status={l.status} /></div>
          </div>
        ))}
        {filtered.length === 0 && (
          <div style={{padding:"60px 20px", textAlign:"center", color:"var(--text-dark-mute)", fontFamily:"var(--font-mono)", fontSize:13, letterSpacing:"0.12em"}}>
            NO LOADS MATCH YOUR FILTERS
          </div>
        )}
      </div>
    </React.Fragment>
  );
}

function DriversTab({ drivers, setDrivers, openDriver }) {
  const [search, setSearch] = cuS("");
  const [statusKey, setStatusKey] = cuS("all");
  const [phaseKey, setPhaseKey] = cuS("");
  const [typeKey, setTypeKey] = cuS("");
  const [stateKey, setStateKey] = cuS("");
  const types = cuM(() => [...new Set(drivers.map(d => d.type))], [drivers]);
  const states = cuM(() => [...new Set(drivers.map(d => d.state))], [drivers]);

  const counts = cuM(() => ({
    all: drivers.length,
    new: drivers.filter(d => d.status === "new").length,
    review: drivers.filter(d => d.status === "review").length,
    approved: drivers.filter(d => d.status === "approved").length,
    rejected: drivers.filter(d => d.status === "rejected").length,
  }), [drivers]);

  const phaseCounts = cuM(() => {
    const m = {};
    PHASES.forEach(p => m[p.key] = drivers.filter(d => d.phase === p.key).length);
    return m;
  }, [drivers]);

  const filters = [
    { k: "all", label: "All", count: counts.all },
    { k: "new", label: "New", count: counts.new },
    { k: "review", label: "In review", count: counts.review },
    { k: "approved", label: "Approved", count: counts.approved },
    { k: "rejected", label: "Rejected", count: counts.rejected },
  ];

  const filtered = cuM(() => drivers.filter(d => {
    if (statusKey !== "all" && d.status !== statusKey) return false;
    if (phaseKey && d.phase !== phaseKey) return false;
    if (typeKey && d.type !== typeKey) return false;
    if (stateKey && d.state !== stateKey) return false;
    if (search) {
      const q = search.toLowerCase();
      const hay = `${d.name} ${d.city} ${d.state} ${d.id}`.toLowerCase();
      if (!hay.includes(q)) return false;
    }
    return true;
  }), [drivers, statusKey, phaseKey, typeKey, stateKey, search]);

  return (
    <React.Fragment>
      <div className="crm-head">
        <div>
          <div className="sub"><span className="live-dot"></span>LIVE · APPLICATION PIPELINE</div>
          <h1>Drivers.</h1>
        </div>
        <div className="crm-head-actions">
          <button className="btn"><Icon name="export" size={14} /> Export CSV</button>
          <button className="btn btn-primary">+ Add driver</button>
        </div>
      </div>

      <div className="kpis">
        <Kpi k="Total applicants" v={drivers.length} delta="+3 today" accent />
        <Kpi k="New (24h)" v={counts.new} />
        <Kpi k="In review" v={counts.review} />
        <Kpi k="Approved YTD" v={counts.approved} />
        <Kpi k="Avg yrs experience" v={(drivers.reduce((a,d)=>a+d.years,0)/drivers.length).toFixed(1)} />
      </div>

      <div className="toolbar">
        <div className="search">
          <Icon name="search" size={15} />
          <input value={search} onChange={e => setSearch(e.target.value)} placeholder="Search name, city, state, ID…" />
        </div>
        {filters.map(f => (
          <button key={f.k} className={`chip ${statusKey === f.k ? "active" : ""}`} onClick={() => setStatusKey(f.k)}>
            {f.label} <span className="ct">{f.count}</span>
          </button>
        ))}
        <select value={typeKey} onChange={e => setTypeKey(e.target.value)}>
          <option value="">All types</option>
          {types.map(t => <option key={t}>{t}</option>)}
        </select>
        <select value={stateKey} onChange={e => setStateKey(e.target.value)}>
          <option value="">All states</option>
          {states.map(s => <option key={s}>{s}</option>)}
        </select>
      </div>

      <div className="phase-strip">
        <div className="phase-strip-head">RECRUITING + ONBOARDING PIPELINE</div>
        <div className="phase-strip-row">
          <button type="button" className={`phase-cell phase-muted ${phaseKey === "" ? "active" : ""}`} onClick={() => setPhaseKey("")}>
            <span className="pc-count">{drivers.length}</span>
            <span className="pc-label">All phases</span>
          </button>
          {PHASES.map(p => (
            <button key={p.key} type="button" className={`phase-cell phase-${p.tone} ${phaseKey === p.key ? "active" : ""}`} onClick={() => setPhaseKey(phaseKey === p.key ? "" : p.key)}>
              <span className="pc-count">{phaseCounts[p.key] || 0}</span>
              <span className="pc-label">{p.label}</span>
            </button>
          ))}
        </div>
      </div>

      <div className="table">
        <div className="table-head cells-drivers">
          <div>ID</div><div>Name</div><div>Type</div><div>Location</div><div>Phase</div><div>Yrs</div><div>Status</div>
        </div>
        {filtered.map(d => (
          <div key={d.id} className={`table-row cells-drivers${d.isLead ? " is-lead" : ""}`} onClick={() => openDriver(d)}>
            <div className="tcell-id">{d.id}{d.isLead && <span className="lead-tag">NEW</span>}</div>
            <div className="tcell-lane">
              <span className="ln1">{d.name}</span>
              <span className="ln2">Applied {d.appliedAt}</span>
            </div>
            <div className="tcell-mono">{d.type}</div>
            <div className="tcell-mono">{d.city}, {d.state}</div>
            <div><PhasePill phase={d.phase || "applied"} /></div>
            <div className="tcell-mono">{d.years}y</div>
            <div><StatusPill status={d.status} /></div>
          </div>
        ))}
        {filtered.length === 0 && (
          <div style={{padding:"60px 20px", textAlign:"center", color:"var(--text-dark-mute)", fontFamily:"var(--font-mono)", fontSize:13, letterSpacing:"0.12em"}}>
            NO APPLICANTS MATCH YOUR FILTERS
          </div>
        )}
      </div>
    </React.Fragment>
  );
}

function LoadDrawer({ load, onClose, onStatus }) {
  const next = { open: "booked", booked: "transit", transit: "delivered", delivered: "delivered" };
  return (
    <React.Fragment>
      <div className="drawer-backdrop" onClick={onClose}></div>
      <aside className="drawer">
        <div className="drawer-head">
          <div>
            <div className="id">{load.id} · {load.source}</div>
            <h2>{load.origin}<br/><span style={{color:"var(--brass-deep)"}}>→</span> {load.dest}</h2>
          </div>
          <button className="drawer-close" onClick={onClose}><Icon name="x" size={16} /></button>
        </div>
        <div className="drawer-body">
          <div className="drawer-section">
            <h4>Status</h4>
            <div style={{display:"flex", justifyContent:"space-between", alignItems:"center"}}>
              <StatusPill status={load.status} />
              {load.status !== "delivered" && (
                <button className="btn btn-primary" style={{padding:"10px 16px", fontSize:11}} onClick={() => onStatus(load.id, next[load.status])}>
                  Mark as {next[load.status]} →
                </button>
              )}
            </div>
          </div>

          <div className="drawer-section">
            <h4>Lane + Rate</h4>
            <div className="drawer-grid">
              <div className="dg-item"><span className="k">Miles</span><span className="v">{load.miles.toLocaleString()} mi</span></div>
              <div className="dg-item"><span className="k">Equipment</span><span className="v">{load.equipment}</span></div>
              <div className="dg-item"><span className="k">Total rate</span><span className="v big">${load.rate.toLocaleString()}</span></div>
              <div className="dg-item"><span className="k">Rate per mile</span><span className="v big">${load.rpm.toFixed(2)}</span></div>
              <div className="dg-item"><span className="k">Pickup</span><span className="v">{load.pickup}</span></div>
              <div className="dg-item"><span className="k">Delivery</span><span className="v">{load.delivery}</span></div>
            </div>
          </div>

          <div className="drawer-section">
            <h4>Freight</h4>
            <div className="drawer-grid">
              <div className="dg-item"><span className="k">Weight</span><span className="v">{load.weight}</span></div>
              <div className="dg-item"><span className="k">Commodity</span><span className="v">{load.commodity}</span></div>
              <div className="dg-item"><span className="k">Broker</span><span className="v">{load.broker}</span></div>
              <div className="dg-item"><span className="k">References</span><span className="v">{load.refs || "—"}</span></div>
            </div>
          </div>

          {load.driverId && (
            <div className="drawer-section">
              <h4>Assigned</h4>
              <div className="dg-item"><span className="k">Driver</span><span className="v">{load.driverId}</span></div>
            </div>
          )}
        </div>
        <div className="drawer-foot">
          <button className="btn">Edit</button>
          <button className="btn">Send rate-con</button>
          <button className="btn btn-primary">Assign driver →</button>
        </div>
      </aside>
    </React.Fragment>
  );
}

function DriverDrawer({ driver, onClose, onStatus, onPhase }) {
  const idx = phaseIdx(driver.phase || "applied");
  const advance = () => {
    if (idx >= 0 && idx < PHASES.length - 1) onPhase(driver.id, PHASES[idx + 1].key);
  };
  return (
    <React.Fragment>
      <div className="drawer-backdrop" onClick={onClose}></div>
      <aside className="drawer drawer-wide">
        <div className="drawer-head">
          <div>
            <div className="id">{driver.id} · {driver.type.toUpperCase()}</div>
            <h2>{driver.name}</h2>
          </div>
          <button className="drawer-close" onClick={onClose}><Icon name="x" size={16} /></button>
        </div>
        <div className="drawer-body">
          <div className="drawer-section">
            <h4>Status + Phase</h4>
            <div style={{display:"flex", gap:10, alignItems:"center", flexWrap:"wrap"}}>
              <StatusPill status={driver.status} />
              <PhasePill phase={driver.phase || "applied"} />
            </div>
          </div>

          <div className="drawer-section">
            <h4>Recruiting + Onboarding pipeline</h4>
            <PhaseTimeline phase={driver.phase || "applied"} onAdvance={advance} onSet={(k) => onPhase(driver.id, k)} />
          </div>

          <div className="drawer-section">
            <h4>Contact</h4>
            <div className="drawer-grid">
              <div className="dg-item"><span className="k">Email</span><span className="v">{driver.email}</span></div>
              <div className="dg-item"><span className="k">Phone</span><span className="v">{driver.phone}</span></div>
              <div className="dg-item"><span className="k">Location</span><span className="v">{driver.city}, {driver.state}</span></div>
              <div className="dg-item"><span className="k">Applied</span><span className="v">{driver.appliedAt}</span></div>
            </div>
          </div>

          <div className="drawer-section">
            <h4>Credentials</h4>
            <div className="drawer-grid">
              <div className="dg-item"><span className="k">CDL</span><span className="v">{driver.cdl}</span></div>
              <div className="dg-item"><span className="k">Endorsements</span><span className="v">{driver.endorsements.length ? driver.endorsements.join(", ") : "None"}</span></div>
              <div className="dg-item"><span className="k">Years OTR</span><span className="v big">{driver.years}y</span></div>
              <div className="dg-item"><span className="k">Accidents (3y)</span><span className="v big">{driver.accidents}</span></div>
            </div>
          </div>

          <div className="drawer-section">
            <h4>Equipment</h4>
            <div className="drawer-grid">
              <div className="dg-item"><span className="k">Has truck</span><span className="v">{driver.hasTruck ? "Yes" : "No"}</span></div>
              <div className="dg-item"><span className="k">Truck</span><span className="v">{driver.truck || "—"}</span></div>
              <div className="dg-item"><span className="k">Trailer</span><span className="v">{driver.trailer || "—"}</span></div>
              <div className="dg-item"><span className="k">Interest</span><span className="v">{driver.leaseInterest || "—"}</span></div>
            </div>
          </div>

          <div className="drawer-section">
            <h4>Documents</h4>
            <div className="docs">
              {[
                { t: "CDL — Front", s: "PDF · 2.4 MB" },
                { t: "CDL — Back", s: "PDF · 2.1 MB" },
                { t: "DOT Medical Card", s: "PDF · 1.8 MB" },
                { t: "Social Security", s: "Encrypted · 0.9 MB" },
              ].map(d => (
                <div key={d.t} className="doc-item">
                  <span className="ico"><Icon name="doc" size={14} /></span>
                  <span className="nm"><span className="t">{d.t}</span><span className="s">{d.s}</span></span>
                </div>
              ))}
            </div>
          </div>
        </div>
        <div className="drawer-foot">
          <button className="btn" onClick={() => onStatus(driver.id, "rejected")}>Reject</button>
          <button className="btn" onClick={() => onStatus(driver.id, "review")}>Review</button>
          <button className="btn btn-primary" onClick={() => onStatus(driver.id, "approved")}>Approve →</button>
        </div>
      </aside>
    </React.Fragment>
  );
}

function PipelineTab({ drivers, openDriver }) {
  const stages = cuM(() => {
    const groups = {};
    PHASES.forEach(p => {
      if (!groups[p.stage]) groups[p.stage] = [];
      groups[p.stage].push(p);
    });
    return Object.entries(groups);
  }, []);

  return (
    <React.Fragment>
      <div className="crm-head">
        <div>
          <div className="sub"><span className="live-dot"></span>RECRUITING + ONBOARDING · LIVE PIPELINE</div>
          <h1>Pipeline.</h1>
        </div>
        <div className="crm-head-actions">
          <button className="btn"><Icon name="export" size={14} /> Export CSV</button>
        </div>
      </div>

      <div className="kpis">
        <Kpi k="In pipeline" v={drivers.filter(d => !["terminated","active","off-duty"].includes(d.phase || "applied")).length} accent />
        <Kpi k="Application stage" v={drivers.filter(d => ["applied","prescreen","mvr-psp","background","drug-screen","insurance"].includes(d.phase || "applied")).length} />
        <Kpi k="Onboarding stage" v={drivers.filter(d => ["qualified","travel","intransit","hotel","orientation","truck"].includes(d.phase)).length} />
        <Kpi k="On the road" v={drivers.filter(d => d.phase === "active").length} />
        <Kpi k="Off-duty / Closed" v={drivers.filter(d => ["off-duty","terminated"].includes(d.phase)).length} />
      </div>

      <div className="pipeline-board">
        {stages.map(([stage, phasesInStage]) => (
          <div key={stage} className="pipe-stage">
            <div className="pipe-stage-head">
              <span className="pipe-stage-name">{stage}</span>
              <span className="pipe-stage-count">{drivers.filter(d => phasesInStage.some(p => p.key === d.phase)).length}</span>
            </div>
            <div className="pipe-stage-cols">
              {phasesInStage.map(p => {
                const ds = drivers.filter(d => d.phase === p.key);
                return (
                  <div key={p.key} className={`pipe-col phase-${p.tone}`}>
                    <div className="pipe-col-head">
                      <span className="pc-label">{p.label}</span>
                      <span className="pc-count">{ds.length}</span>
                    </div>
                    <div className="pipe-col-body">
                      {ds.map(d => (
                        <button key={d.id} type="button" className="pipe-card" onClick={() => openDriver(d)}>
                          <div className="pc-name">{d.name}</div>
                          <div className="pc-meta">{d.id} · {d.type}</div>
                          <div className="pc-foot">
                            <span>{d.city}, {d.state}</span>
                            <span>{d.years}y</span>
                          </div>
                        </button>
                      ))}
                      {ds.length === 0 && <div className="pipe-empty">—</div>}
                    </div>
                  </div>
                );
              })}
            </div>
          </div>
        ))}
      </div>
    </React.Fragment>
  );
}

function PerformanceTab() {
  const data = window.SFL_DATA.performance;
  const active = data.filter(d => d.loadsYtd > 0);
  const avgRpm = active.length ? (active.reduce((a,d) => a + d.avgRpm, 0) / active.length).toFixed(2) : "—";
  const avgOnTime = active.length ? (active.reduce((a,d) => a + d.onTimePct, 0) / active.length).toFixed(1) : "—";
  const totalLoads = active.reduce((a,d) => a + d.loadsYtd, 0);
  const totalMiles = active.reduce((a,d) => a + d.milesYtd, 0);
  const totalSettle = active.reduce((a,d) => a + d.settlementsYtd, 0);
  const top = [...active].sort((a,b) => b.settlementsYtd - a.settlementsYtd)[0];

  const rowClass = (d) => {
    if (d.onTimePct >= 98) return "perf-row tone-ok";
    if (d.onTimePct >= 95) return "perf-row tone-warn";
    return "perf-row tone-muted";
  };

  return (
    <React.Fragment>
      <div className="crm-head">
        <div>
          <div className="sub"><span className="live-dot"></span>PERFORMANCE · YTD</div>
          <h1>Performance.</h1>
        </div>
        <div className="crm-head-actions">
          <button className="btn"><Icon name="export" size={14} /> Export CSV</button>
          <button className="btn btn-primary">Run weekly review</button>
        </div>
      </div>

      <div className="kpis">
        <Kpi k="Total loads YTD" v={totalLoads} delta="+34 wk" accent />
        <Kpi k="Total miles YTD" v={totalMiles.toLocaleString()} suffix="mi" />
        <Kpi k="Avg RPM (active)" v={avgRpm} suffix="$/mi" delta="+0.12" />
        <Kpi k="Avg on-time" v={avgOnTime} suffix="%" delta="+0.4" />
        <Kpi k="Settlements YTD" v={`$${(totalSettle/1000).toFixed(0)}k`} delta={top ? `Top · ${top.driver.split(' ')[0]}` : ""} />
      </div>

      <div className="table">
        <div className="table-head cells-perf">
          <div>Driver</div><div>Loads</div><div>Miles</div><div>RPM</div><div>On-time</div><div>Accidents</div><div>Detention</div><div>Settlements</div><div>Rating</div>
        </div>
        {data.sort((a,b) => b.settlementsYtd - a.settlementsYtd).map(d => (
          <div key={d.driverId} className={`table-row cells-perf ${rowClass(d)}`}>
            <div className="tcell-lane">
              <span className="ln1">{d.driver}</span>
              <span className="ln2">{d.driverId} · {d.lane}</span>
            </div>
            <div className="tcell-mono">{d.loadsYtd}</div>
            <div className="tcell-mono">{d.milesYtd.toLocaleString()}</div>
            <div className="tcell-rate">{d.avgRpm > 0 ? `$${d.avgRpm.toFixed(2)}` : "—"}</div>
            <div className="tcell-mono">{d.onTimePct > 0 ? `${d.onTimePct}%` : "—"}</div>
            <div className="tcell-mono">{d.accidents}</div>
            <div className="tcell-mono">{d.detentionClaims}</div>
            <div className="tcell-rate">${d.settlementsYtd.toLocaleString()}</div>
            <div className="tcell-mono">{d.rating !== null ? `★ ${d.rating}` : "—"}</div>
          </div>
        ))}
      </div>
    </React.Fragment>
  );
}

function SettlementsTab() {
  const data = window.SFL_DATA.settlements;
  const [statusKey, setStatusKey] = cuS("all");
  const [search, setSearch] = cuS("");
  const counts = { all: data.length, paid: data.filter(s => s.status === "paid").length, pending: data.filter(s => s.status === "pending").length };

  const filtered = data.filter(s => {
    if (statusKey !== "all" && s.status !== statusKey) return false;
    if (search) {
      const q = search.toLowerCase();
      if (!`${s.driver} ${s.driverId} ${s.weekEnding} ${s.id}`.toLowerCase().includes(q)) return false;
    }
    return true;
  });

  const totalGross = filtered.reduce((a,s) => a + s.gross, 0);
  const totalNet = filtered.reduce((a,s) => a + s.net, 0);
  const totalDispatch = filtered.reduce((a,s) => a + s.dispatchFee, 0);
  const totalFuel = filtered.reduce((a,s) => a + s.fuel, 0);
  const totalDetention = filtered.reduce((a,s) => a + s.detention, 0);
  const pendingNet = data.filter(s => s.status === "pending").reduce((a,s) => a + s.net, 0);

  return (
    <React.Fragment>
      <div className="crm-head">
        <div>
          <div className="sub"><span className="live-dot"></span>SETTLEMENTS · WEEKLY</div>
          <h1>Settlements.</h1>
        </div>
        <div className="crm-head-actions">
          <button className="btn"><Icon name="export" size={14} /> Export CSV</button>
          <button className="btn btn-primary">+ New settlement</button>
        </div>
      </div>

      <div className="kpis">
        <Kpi k="Gross (filtered)" v={`$${(totalGross/1000).toFixed(1)}k`} accent />
        <Kpi k="Net to drivers" v={`$${(totalNet/1000).toFixed(1)}k`} delta="85% to truck" />
        <Kpi k="Dispatch fees" v={`$${(totalDispatch/1000).toFixed(1)}k`} />
        <Kpi k="Fuel + factoring" v={`$${((totalFuel + filtered.reduce((a,s)=>a+s.factoring,0))/1000).toFixed(1)}k`} />
        <Kpi k="Pending payout" v={`$${(pendingNet/1000).toFixed(1)}k`} delta={`${counts.pending} weeks`} />
      </div>

      <div className="toolbar">
        <div className="search">
          <Icon name="search" size={15} />
          <input value={search} onChange={e => setSearch(e.target.value)} placeholder="Search driver, week, ID…" />
        </div>
        <button className={`chip ${statusKey === "all" ? "active" : ""}`} onClick={() => setStatusKey("all")}>All <span className="ct">{counts.all}</span></button>
        <button className={`chip ${statusKey === "paid" ? "active" : ""}`} onClick={() => setStatusKey("paid")}>Paid <span className="ct">{counts.paid}</span></button>
        <button className={`chip ${statusKey === "pending" ? "active" : ""}`} onClick={() => setStatusKey("pending")}>Pending <span className="ct">{counts.pending}</span></button>
      </div>

      <div className="table">
        <div className="table-head cells-settle">
          <div>ID</div><div>Driver</div><div>Wk Ending</div><div>Loads</div><div>Miles</div><div>Gross</div><div>Fees</div><div>Detention</div><div>Net</div><div>Status</div>
        </div>
        {filtered.map(s => (
          <div key={s.id} className="table-row cells-settle">
            <div className="tcell-id">{s.id.slice(0, 11)}…</div>
            <div className="tcell-lane">
              <span className="ln1">{s.driver}</span>
              <span className="ln2">{s.driverId}</span>
            </div>
            <div className="tcell-mono">{s.weekEnding}</div>
            <div className="tcell-mono">{s.loads}</div>
            <div className="tcell-mono">{s.miles.toLocaleString()}</div>
            <div className="tcell-rate">${s.gross.toLocaleString()}</div>
            <div className="tcell-mono">${(s.dispatchFee + s.fuel + s.factoring).toLocaleString()}</div>
            <div className="tcell-mono">{s.detention ? `$${s.detention}` : "—"}</div>
            <div className="tcell-rate">${s.net.toLocaleString()}</div>
            <div><span className={`status-pill ${s.status === "paid" ? "s-delivered" : "s-review"}`}>{s.status}</span></div>
          </div>
        ))}
      </div>
    </React.Fragment>
  );
}

function ComplianceTab() {
  const data = window.SFL_DATA.compliance;
  const [flagKey, setFlagKey] = cuS("all");

  const today = new Date("2026-05-09");
  const daysUntil = (d) => {
    if (!d || d === "—") return null;
    return Math.round((new Date(d) - today) / (1000 * 60 * 60 * 24));
  };

  const counts = {
    all: data.length,
    ok: data.filter(d => d.flag === "ok").length,
    warn: data.filter(d => d.flag === "warn").length,
    bad: data.filter(d => d.flag === "bad").length,
  };

  const cdlExpiringSoon = data.filter(d => { const x = daysUntil(d.cdlExpiry); return x !== null && x < 90 && x >= 0; }).length;
  const medExpiringSoon = data.filter(d => { const x = daysUntil(d.medExpiry); return x !== null && x < 60 && x >= 0; }).length;
  const totalHosViolations = data.reduce((a,d) => a + d.hosViolations, 0);
  const insurancePending = data.filter(d => d.insuranceCert === "pending" || d.insuranceCert === "expired").length;

  const filtered = flagKey === "all" ? data : data.filter(d => d.flag === flagKey);

  const dateCell = (d, daysWarn) => {
    if (!d || d === "—") return <span className="cell-na">—</span>;
    const days = daysUntil(d);
    let cls = "cell-ok";
    if (days < 0) cls = "cell-bad";
    else if (days < daysWarn) cls = "cell-warn";
    return (
      <div className={`cell-date ${cls}`}>
        <span className="d">{d}</span>
        <span className="r">{days < 0 ? `expired ${Math.abs(days)}d` : `${days}d`}</span>
      </div>
    );
  };

  return (
    <React.Fragment>
      <div className="crm-head">
        <div>
          <div className="sub"><span className="live-dot"></span>FMCSA + DOT COMPLIANCE</div>
          <h1>Compliance.</h1>
        </div>
        <div className="crm-head-actions">
          <button className="btn"><Icon name="export" size={14} /> Export CSV</button>
          <button className="btn btn-primary">+ Log inspection</button>
        </div>
      </div>

      <div className="kpis">
        <Kpi k="CDL expiring (90d)" v={cdlExpiringSoon} accent />
        <Kpi k="Med card expiring (60d)" v={medExpiringSoon} />
        <Kpi k="HOS violations YTD" v={totalHosViolations} delta={totalHosViolations === 0 ? "clean" : ""} />
        <Kpi k="Insurance issues" v={insurancePending} />
        <Kpi k="Compliance flag · clean" v={`${counts.ok}/${counts.all}`} delta={`${counts.bad} critical`} />
      </div>

      <div className="toolbar">
        <button className={`chip ${flagKey === "all" ? "active" : ""}`} onClick={() => setFlagKey("all")}>All <span className="ct">{counts.all}</span></button>
        <button className={`chip ${flagKey === "ok" ? "active" : ""}`} onClick={() => setFlagKey("ok")}>Clean <span className="ct">{counts.ok}</span></button>
        <button className={`chip ${flagKey === "warn" ? "active" : ""}`} onClick={() => setFlagKey("warn")}>Warning <span className="ct">{counts.warn}</span></button>
        <button className={`chip ${flagKey === "bad" ? "active" : ""}`} onClick={() => setFlagKey("bad")}>Critical <span className="ct">{counts.bad}</span></button>
      </div>

      <div className="table">
        <div className="table-head cells-comp">
          <div>Driver</div><div>CDL exp</div><div>Med card</div><div>Last inspection</div><div>HOS</div><div>Drug test</div><div>Insurance</div><div>Flag</div>
        </div>
        {filtered.map(d => (
          <div key={d.driverId} className="table-row cells-comp">
            <div className="tcell-lane">
              <span className="ln1">{d.driver}</span>
              <span className="ln2">{d.driverId}</span>
            </div>
            <div>{dateCell(d.cdlExpiry, 90)}</div>
            <div>{dateCell(d.medExpiry, 60)}</div>
            <div className="tcell-mono">
              {d.lastInspection !== "—" ? <><div>{d.lastInspection}</div><div className="ln2">{d.inspectionLevel}</div></> : "—"}
            </div>
            <div className="tcell-mono">{d.hosViolations === 0 ? "0" : <span className="cell-warn">{d.hosViolations}</span>}</div>
            <div className="tcell-mono">{d.drugTestDate !== "—" ? <><div>{d.drugTestDate}</div><div className={`ln2 ${d.drugTestResult === "negative" ? "cell-ok" : "cell-warn"}`}>{d.drugTestResult}</div></> : "—"}</div>
            <div className="tcell-mono"><span className={`comp-ins comp-${d.insuranceCert}`}>{d.insuranceCert}</span></div>
            <div><span className={`comp-flag flag-${d.flag}`}>{d.flag === "ok" ? "Clean" : d.flag === "warn" ? "Warning" : "Critical"}</span></div>
          </div>
        ))}
      </div>
    </React.Fragment>
  );
}

function fmtDuration(s) {
  if (!s || s === 0) return "0:00";
  const m = Math.floor(s / 60), sec = s % 60;
  return `${m}:${String(sec).padStart(2, "0")}`;
}

function CallSentiment({ s }) {
  if (!s) return <span className="cell-na">—</span>;
  const map = { positive: { c: "ok", t: "Positive" }, neutral: { c: "warn", t: "Neutral" }, negative: { c: "bad", t: "Negative" } };
  const m = map[s] || map.neutral;
  return <span className={`comp-flag flag-${m.c}`}>{m.t}</span>;
}

function CallOutcome({ o }) {
  const map = {
    "load-booked":          { tone: "ok",     label: "Load booked" },
    "callback-scheduled":   { tone: "active", label: "Callback set" },
    "rate-sent":            { tone: "ok",     label: "Rate sent" },
    "transferred-to-safety":{ tone: "warn",   label: "Routed → Safety" },
    "disqualified-followup":{ tone: "muted",  label: "Follow-up later" },
    "missed":               { tone: "bad",    label: "Missed" },
  };
  const m = map[o] || { tone: "muted", label: o || "—" };
  return <span className={`phase-pill phase-${m.tone}`}><span className="dot"></span><span className="lbl">{m.label}</span></span>;
}

function LiveCallCard({ call, onOpen }) {
  const [tick, setTick] = cuS(call.duration);
  cuE(() => {
    const t = setInterval(() => setTick(x => x + 1), 1000);
    return () => clearInterval(t);
  }, []);
  return (
    <div className="live-call-card" onClick={() => onOpen(call)}>
      <div className="lc-pulse"></div>
      <div className="lc-info">
        <div className="lc-head">
          <span className="lc-id">{call.id}</span>
          <span className="lc-live">● LIVE · {fmtDuration(tick)}</span>
        </div>
        <div className="lc-name">{call.callerName} <span className="lc-type">· {call.callerType}</span></div>
        <div className="lc-summary">{call.summary}</div>
      </div>
      <div className="lc-actions">
        <button type="button" className="btn">Listen ▶</button>
        <button type="button" className="btn">Whisper</button>
        <button type="button" className="btn btn-primary">Take over</button>
      </div>
    </div>
  );
}

function AIAgentCard() {
  const a = window.SFL_DATA.aiAgent;
  return (
    <aside className="ai-agent-card">
      <div className="aac-head">
        <div className="aac-avatar">{a.avatar}</div>
        <div className="aac-meta">
          <div className="aac-name">{a.name}</div>
          <div className="aac-role">{a.role}</div>
          <div className="aac-stat"><span className="dot"></span>ONLINE · ANSWERING NOW</div>
        </div>
      </div>
      <div className="aac-section">
        <h5>Voice + reach</h5>
        <ul>
          <li><span className="k">Voice</span><span className="v">{a.voice}</span></li>
          <li><span className="k">Languages</span><span className="v">{a.languages.join(" · ")}</span></li>
          <li><span className="k">Coverage</span><span className="v">{a.coverage}</span></li>
          <li><span className="k">Active since</span><span className="v">{a.activeSince}</span></li>
        </ul>
      </div>
      <div className="aac-section">
        <h5>Capabilities</h5>
        <ul className="aac-caps">
          {a.capabilities.map(c => (
            <li key={c.area}>
              <span className="cap-area">{c.area}</span>
              <span className="cap-detail">{c.detail}</span>
            </li>
          ))}
        </ul>
      </div>
      <div className="aac-section">
        <h5>Trained on SF Logistics</h5>
        <div className="aac-kb">
          {Object.entries(a.knowledge).map(([k, v]) => (
            <div className="kb-row" key={k}>
              <span className="kb-k">{k}</span>
              <span className="kb-v">{v}</span>
            </div>
          ))}
        </div>
      </div>
      {a.integrations && (
        <div className="aac-section">
          <h5>Integrations · Live</h5>
          <div className="aac-integrations">
            {a.integrations.map(i => (
              <div className={`int-row int-${i.status}`} key={i.name}>
                <span className="int-name">{i.name}</span>
                <span className="int-status">{i.status}</span>
                <span className="int-detail">{i.detail}</span>
              </div>
            ))}
          </div>
        </div>
      )}
      <div className="aac-section aac-platform">
        <h5>Platform · {a.platform || "SixBits AI"}</h5>
        <div className="aac-platform-grid">
          <div><span className="ppl-k">Cost</span><span className="ppl-v">{a.cost || "—"}</span></div>
          <div><span className="ppl-k">Setup</span><span className="ppl-v">{a.setup || "—"}</span></div>
          <div><span className="ppl-k">Coverage</span><span className="ppl-v">{a.coverage}</span></div>
          {a.guarantee && <div className="ppl-guarantee">{a.guarantee}</div>}
        </div>
      </div>
    </aside>
  );
}

function PlatformMetricsBanner() {
  const m = window.SFL_DATA.aiPlatformMetrics;
  if (!m) return null;
  return (
    <div className="ai-platform-banner">
      <div className="apb-head">
        <div className="apb-title">
          <span className="apb-eyebrow">SIXBITS AI · TRUCKING PLATFORM</span>
          <h3>The math behind Dani.</h3>
        </div>
        <a className="apb-link" href={m.sourceUrl} target="_blank" rel="noopener">View live demo →</a>
      </div>
      <div className="apb-grid">
        <div className="apb-stat">
          <span className="apb-v">{m.dormantLeadsInCrm.toLocaleString()}</span>
          <span className="apb-k">avg dormant leads<br/>in a 50-truck CRM</span>
        </div>
        <div className="apb-stat">
          <span className="apb-v">{m.coldConversionPct}%</span>
          <span className="apb-k">cold-lead<br/>conversion</span>
        </div>
        <div className="apb-stat">
          <span className="apb-v">${(m.costPerHireWasted/1000).toFixed(1)}k</span>
          <span className="apb-k">avg cost-per-hire<br/>wasted on dormant leads</span>
        </div>
        <div className="apb-stat">
          <span className="apb-v">{m.inboundNoCallback24hPct}%</span>
          <span className="apb-k">inbound calls without<br/>a 24h callback (industry)</span>
        </div>
        <div className="apb-stat apb-accent">
          <span className="apb-v">{m.outboundVsHumanRecruiter}</span>
          <span className="apb-k">outbound volume<br/>vs 1 part-time recruiter</span>
        </div>
        <div className="apb-stat apb-accent">
          <span className="apb-v">{m.annualGrossProfitOpp}</span>
          <span className="apb-k">annual gross-profit<br/>opportunity recovered</span>
        </div>
      </div>
    </div>
  );
}

function CampaignsTable() {
  const camps = window.SFL_DATA.aiCampaigns;
  if (!camps || !camps.length) return null;
  return (
    <div className="ai-campaigns">
      <div className="apb-head">
        <div className="apb-title">
          <span className="apb-eyebrow">OUTBOUND · DORMANT LEAD RECOVERY</span>
          <h3>Active campaigns.</h3>
        </div>
        <button type="button" className="btn btn-primary">+ New campaign</button>
      </div>
      <div className="table">
        <div className="table-head cells-camp">
          <div>Campaign</div><div>Source</div><div>Leads</div><div>Dialed</div><div>Contacted</div><div>Qualified</div><div>Booked</div><div>Declined</div><div>Voicemail</div><div>Status</div>
        </div>
        {camps.map(c => (
          <div key={c.id} className={`table-row cells-camp ${c.status === "running" ? "is-live" : ""}`}>
            <div className="tcell-lane">
              <span className="ln1">{c.name}</span>
              <span className="ln2">{c.id} · last run {c.lastRun}</span>
            </div>
            <div className="tcell-mono">{c.source}</div>
            <div className="tcell-mono">{c.leads}</div>
            <div className="tcell-mono">{c.dialed}</div>
            <div className="tcell-mono">{c.contacted}</div>
            <div className="tcell-mono"><span style={{color:"var(--signal-info)"}}>{c.qualified}</span></div>
            <div className="tcell-rate">{c.booked}</div>
            <div className="tcell-mono">{c.declined}</div>
            <div className="tcell-mono">{c.voicemail}</div>
            <div><span className={`status-pill ${c.status === "running" ? "s-transit" : "s-delivered"}`}>{c.status}</span></div>
          </div>
        ))}
      </div>
    </div>
  );
}

function AICallsTab({ openCall }) {
  const calls = window.SFL_DATA.aiCalls;
  const [search, setSearch] = cuS("");
  const [typeKey, setTypeKey] = cuS("all");
  const [outcomeKey, setOutcomeKey] = cuS("all");

  const live = calls.filter(c => c.status === "live");
  const completed = calls.filter(c => c.status === "completed");
  const missed = calls.filter(c => c.status === "missed");

  const totalToday = calls.length;
  const qualifiedCt = completed.filter(c => c.qualified === true).length;
  const conversionPct = completed.length ? Math.round((qualifiedCt / completed.length) * 100) : 0;
  const avgDur = completed.length ? Math.round(completed.reduce((a,c) => a + c.duration, 0) / completed.length) : 0;
  const callbacksScheduled = calls.filter(c => c.scheduledCallback).length;
  const loadsBooked = calls.filter(c => c.outcome === "load-booked").length;

  const counts = {
    all: calls.length,
    driver: calls.filter(c => c.callerType === "driver").length,
    broker: calls.filter(c => c.callerType === "broker").length,
    shipper: calls.filter(c => c.callerType === "shipper").length,
    missed: missed.length,
  };

  const filtered = calls.filter(c => {
    if (typeKey !== "all" && typeKey !== "missed" && c.callerType !== typeKey) return false;
    if (typeKey === "missed" && c.status !== "missed") return false;
    if (outcomeKey !== "all" && c.outcome !== outcomeKey) return false;
    if (search) {
      const q = search.toLowerCase();
      const hay = `${c.id} ${c.callerName} ${c.callerPhone} ${c.callerCompany || ""} ${c.summary}`.toLowerCase();
      if (!hay.includes(q)) return false;
    }
    return true;
  });

  return (
    <div className="ai-calls-shell">
      <AIAgentCard />

      <div className="ai-calls-main">
        <div className="crm-head">
          <div>
            <div className="sub"><span className="live-dot"></span>AI RECEPTIONIST · LIVE PIPELINE</div>
            <h1>Calls.</h1>
          </div>
          <div className="crm-head-actions">
            <button className="btn"><Icon name="export" size={14} /> Export transcripts</button>
            <button className="btn btn-primary">+ Train new objection</button>
          </div>
        </div>

        <div className="kpis">
          <Kpi k="Calls today" v={totalToday} delta={`+${live.length} live`} accent />
          <Kpi k="Conversion" v={`${conversionPct}%`} suffix="qualified" delta="+8 pts wk" />
          <Kpi k="Avg duration" v={fmtDuration(avgDur)} delta="−18s wk" />
          <Kpi k="Loads booked" v={loadsBooked} delta="from AI alone" />
          <Kpi k="Callbacks scheduled" v={callbacksScheduled} />
        </div>

        {live.length > 0 && (
          <div className="live-calls-row">
            <div className="lcr-head">
              <span className="dot"></span>
              <span>LIVE · {live.length} CALL{live.length !== 1 ? "S" : ""} IN PROGRESS</span>
            </div>
            {live.map(c => <LiveCallCard key={c.id} call={c} onOpen={openCall} />)}
          </div>
        )}

        <PlatformMetricsBanner />

        <CampaignsTable />

        <div className="toolbar">
          <div className="search">
            <Icon name="search" size={15} />
            <input value={search} onChange={e => setSearch(e.target.value)} placeholder="Search caller, ID, summary, phone…" />
          </div>
          <button className={`chip ${typeKey === "all" ? "active" : ""}`} onClick={() => setTypeKey("all")}>All <span className="ct">{counts.all}</span></button>
          <button className={`chip ${typeKey === "driver" ? "active" : ""}`} onClick={() => setTypeKey("driver")}>Drivers <span className="ct">{counts.driver}</span></button>
          <button className={`chip ${typeKey === "broker" ? "active" : ""}`} onClick={() => setTypeKey("broker")}>Brokers <span className="ct">{counts.broker}</span></button>
          <button className={`chip ${typeKey === "shipper" ? "active" : ""}`} onClick={() => setTypeKey("shipper")}>Shippers <span className="ct">{counts.shipper}</span></button>
          <button className={`chip ${typeKey === "missed" ? "active" : ""}`} onClick={() => setTypeKey("missed")}>Missed <span className="ct">{counts.missed}</span></button>
        </div>

        <div className="table">
          <div className="table-head cells-calls">
            <div>ID</div><div>Caller</div><div>Type</div><div>Started</div><div>Duration</div><div>Outcome</div><div>Sentiment</div>
          </div>
          {filtered.map(c => (
            <div key={c.id} className={`table-row cells-calls ${c.status === "live" ? "is-live" : ""}`} onClick={() => openCall(c)}>
              <div className="tcell-id">{c.id.slice(0, 13)}…</div>
              <div className="tcell-lane">
                <span className="ln1">{c.callerName}{c.status === "live" && <span className="lead-tag" style={{background:"var(--signal-ok)"}}>LIVE</span>}</span>
                <span className="ln2">{c.callerPhone}{c.callerCompany ? ` · ${c.callerCompany}` : ""}</span>
              </div>
              <div className="tcell-mono">{c.callerType.toUpperCase()}</div>
              <div className="tcell-mono">{c.startTime.slice(11)}</div>
              <div className="tcell-mono">{fmtDuration(c.duration)}</div>
              <div><CallOutcome o={c.outcome} /></div>
              <div><CallSentiment s={c.sentiment} /></div>
            </div>
          ))}
        </div>
      </div>
    </div>
  );
}

function CallDrawer({ call, onClose }) {
  const [tick, setTick] = cuS(call.duration);
  cuE(() => {
    if (call.status !== "live") return;
    const t = setInterval(() => setTick(x => x + 1), 1000);
    return () => clearInterval(t);
  }, [call.id]);

  return (
    <React.Fragment>
      <div className="drawer-backdrop" onClick={onClose}></div>
      <aside className="drawer drawer-wide">
        <div className="drawer-head">
          <div>
            <div className="id">{call.id} · {call.direction.toUpperCase()} · {call.callerType.toUpperCase()}</div>
            <h2>{call.callerName}</h2>
            <div style={{fontFamily:"var(--font-mono)", fontSize:11.5, letterSpacing:"0.06em", color:"var(--text-mute)", marginTop:4}}>{call.callerPhone}{call.callerCompany ? ` · ${call.callerCompany}` : ""}</div>
          </div>
          <button className="drawer-close" onClick={onClose}><Icon name="x" size={16} /></button>
        </div>
        <div className="drawer-body">
          <div className="drawer-section">
            <h4>Status</h4>
            <div style={{display:"flex", gap:10, alignItems:"center", flexWrap:"wrap"}}>
              {call.status === "live" ? (
                <span className="phase-pill phase-active"><span className="dot pulse"></span><span className="lbl">LIVE · {fmtDuration(tick)}</span></span>
              ) : call.status === "missed" ? (
                <span className="phase-pill phase-bad"><span className="dot"></span><span className="lbl">MISSED</span></span>
              ) : (
                <span className="phase-pill phase-ok"><span className="dot"></span><span className="lbl">COMPLETED · {fmtDuration(call.duration)}</span></span>
              )}
              <CallSentiment s={call.sentiment} />
              {call.outcome && <CallOutcome o={call.outcome} />}
            </div>
          </div>

          <div className="drawer-section">
            <h4>Summary</h4>
            <p className="call-summary">{call.summary || "—"}</p>
          </div>

          {call.transcript && call.transcript.length > 0 && (
            <div className="drawer-section">
              <h4>Transcript · {call.transcript.length} turns</h4>
              <div className="transcript">
                {call.transcript.map((m, i) => (
                  <div key={i} className={`tt-line tt-${m.speaker === "AI" ? "ai" : "caller"}`}>
                    <span className="tt-meta">{m.speaker === "AI" ? "Sasha · AI" : call.callerName}<span className="tt-t">{fmtDuration(m.t)}</span></span>
                    <div className="tt-bubble">{m.text}</div>
                  </div>
                ))}
                {call.status === "live" && (
                  <div className="tt-line tt-typing">
                    <span className="tt-meta">{call.callerName}</span>
                    <div className="tt-bubble"><span className="typing"><span></span><span></span><span></span></span></div>
                  </div>
                )}
              </div>
            </div>
          )}

          {call.objections && call.objections.length > 0 && (
            <div className="drawer-section">
              <h4>Objections handled · {call.objections.length}</h4>
              <div className="objections">
                {call.objections.map((o, i) => (
                  <div key={i} className="obj-row">
                    <div className="obj-raised">
                      <span className="obj-l">RAISED</span>
                      <span className="obj-t">"{o.raised}"</span>
                    </div>
                    <div className="obj-handled">
                      <span className="obj-l">AI RESPONSE</span>
                      <span className="obj-t">{o.handled}</span>
                    </div>
                    <div className={`obj-outcome obj-${o.outcome === "accepted" ? "ok" : o.outcome === "polite-decline" ? "warn" : "muted"}`}>
                      {o.outcome.toUpperCase()}
                    </div>
                  </div>
                ))}
              </div>
            </div>
          )}

          {(call.scheduledCallback || call.leadId) && (
            <div className="drawer-section">
              <h4>Outcome detail</h4>
              <div className="drawer-grid">
                {call.scheduledCallback && (
                  <div className="dg-item"><span className="k">Callback scheduled</span><span className="v">{call.scheduledCallback}</span></div>
                )}
                {call.leadId && (
                  <div className="dg-item"><span className="k">Linked lead</span><span className="v">{call.leadId}</span></div>
                )}
                <div className="dg-item"><span className="k">Intent</span><span className="v">{call.intent}</span></div>
                <div className="dg-item"><span className="k">Direction</span><span className="v">{call.direction}</span></div>
              </div>
            </div>
          )}
        </div>
        <div className="drawer-foot">
          {call.status === "live" ? (
            <React.Fragment>
              <button className="btn">Listen ▶</button>
              <button className="btn">Whisper</button>
              <button className="btn btn-primary">Take over →</button>
            </React.Fragment>
          ) : (
            <React.Fragment>
              <button className="btn">Download MP3</button>
              <button className="btn">Flag for training</button>
              <button className="btn btn-primary">Open lead →</button>
            </React.Fragment>
          )}
        </div>
      </aside>
    </React.Fragment>
  );
}

function readLeads(key) {
  try { return JSON.parse(localStorage.getItem(key) || "[]"); } catch (e) { return []; }
}

function CrmConsole() {
  const [tab, setTab] = cuS("loads");
  const [loads, setLoads] = cuS(() => [...readLeads("SFL_LEADS_LOADS"), ...window.SFL_DATA.loads]);
  const [drivers, setDrivers] = cuS(() => [...readLeads("SFL_LEADS_DRIVERS"), ...window.SFL_DATA.drivers]);
  const [openL, setOpenL] = cuS(null);
  const [openD, setOpenD] = cuS(null);
  const [openCall, setOpenCall] = cuS(null);
  const liveCallCount = (window.SFL_DATA.aiCalls || []).filter(c => c.status === "live").length;

  cuE(() => {
    const onStorage = (e) => {
      if (e.key === "SFL_LEADS_LOADS") setLoads([...readLeads("SFL_LEADS_LOADS"), ...window.SFL_DATA.loads]);
      if (e.key === "SFL_LEADS_DRIVERS") setDrivers([...readLeads("SFL_LEADS_DRIVERS"), ...window.SFL_DATA.drivers]);
    };
    window.addEventListener("storage", onStorage);
    return () => window.removeEventListener("storage", onStorage);
  }, []);

  const setLoadStatus = (id, status) => {
    setLoads(ls => ls.map(l => l.id === id ? { ...l, status } : l));
    setOpenL(o => o ? { ...o, status } : null);
  };
  const setDriverStatus = (id, status) => {
    setDrivers(ds => ds.map(d => d.id === id ? { ...d, status } : d));
    setOpenD(null);
  };
  const setDriverPhase = (id, phase) => {
    setDrivers(ds => ds.map(d => d.id === id ? { ...d, phase } : d));
    setOpenD(o => o && o.id === id ? { ...o, phase } : o);
  };

  const inPipeline = drivers.filter(d => !["terminated", "active", "off-duty"].includes(d.phase || "applied")).length;

  return (
    <div className="crm-shell">
      <aside className="crm-sidebar">
        <div className="crm-side-head">DISPATCH</div>
        <button className={`crm-side-link ${tab==="loads"?"active":""}`} onClick={() => setTab("loads")}>
          <Icon name="loads" size={15} /> Loads <span className="badge">{loads.filter(l=>l.status==="open").length}</span>
        </button>
        <button className={`crm-side-link ${tab==="drivers"?"active":""}`} onClick={() => setTab("drivers")}>
          <Icon name="users" size={15} /> Drivers <span className="badge">{drivers.filter(d=>d.status==="new").length}</span>
        </button>
        <button className={`crm-side-link ${tab==="pipeline"?"active":""}`} onClick={() => setTab("pipeline")}>
          <Icon name="chart" size={15} /> Pipeline <span className="badge">{inPipeline}</span>
        </button>
        <div className="crm-side-divider"></div>
        <div className="crm-side-head">AI</div>
        <button className={`crm-side-link ${tab==="ai-calls"?"active":""}`} onClick={() => setTab("ai-calls")}>
          <Icon name="users" size={15} /> Receptionist {liveCallCount > 0 && <span className="badge live-badge">{liveCallCount} LIVE</span>}
        </button>
        <div className="crm-side-divider"></div>
        <div className="crm-side-head">REPORTS</div>
        <button className={`crm-side-link ${tab==="performance"?"active":""}`} onClick={() => setTab("performance")}>
          <Icon name="chart" size={15} /> Performance
        </button>
        <button className={`crm-side-link ${tab==="settlements"?"active":""}`} onClick={() => setTab("settlements")}>
          <Icon name="export" size={15} /> Settlements
        </button>
        <button className={`crm-side-link ${tab==="compliance"?"active":""}`} onClick={() => setTab("compliance")}>
          <Icon name="doc" size={15} /> Compliance
        </button>

        <div className="crm-operator">
          <div className="av">SS</div>
          <div className="info">
            <div className="nm">Sanjar S.</div>
            <div className="role">OPS · ADMIN</div>
          </div>
        </div>
      </aside>
      <main className="crm-main">
        {tab === "loads" && <LoadsTab loads={loads} setLoads={setLoads} openLoad={setOpenL} />}
        {tab === "drivers" && <DriversTab drivers={drivers} setDrivers={setDrivers} openDriver={setOpenD} />}
        {tab === "pipeline" && <PipelineTab drivers={drivers} openDriver={setOpenD} />}
        {tab === "ai-calls" && <AICallsTab openCall={setOpenCall} />}
        {tab === "performance" && <PerformanceTab />}
        {tab === "settlements" && <SettlementsTab />}
        {tab === "compliance" && <ComplianceTab />}
      </main>

      {openL && <LoadDrawer load={openL} onClose={() => setOpenL(null)} onStatus={setLoadStatus} />}
      {openD && <DriverDrawer driver={openD} onClose={() => setOpenD(null)} onStatus={setDriverStatus} onPhase={setDriverPhase} />}
      {openCall && <CallDrawer call={openCall} onClose={() => setOpenCall(null)} />}
    </div>
  );
}

Object.assign(window, { CrmConsole });
