/* JobsPipeline — read-only CRM pipeline over the Engine-31 mirror (window.CRM).
   Board (kanban by silo) + sortable table, KPI strip, search & filters.
   Reuses the Quote Board's KPI-hero + status-pill language. */

const { Card: PipeCard, Eyebrow: PipeEyebrow, Select: PipeSelect } = window.Ds1Threshold_e046d3;

const SILO_DOT = {
  new_lead: "var(--color-primary)", appointment: "var(--status-info-solid)",
  quoted: "var(--status-pending-solid)", sold: "var(--status-sold-solid)",
  measure: "var(--color-primary)", production: "var(--status-info-solid)",
  install: "var(--status-pending-solid)", complete: "var(--status-sold-solid)",
};

function SyncIndicator() {
  const mins = Math.max(1, Math.round((Date.now() - window.CRM.lastSyncMs) / 60000));
  return (
    <div title="Read-only mirror of Engine 31 — refreshes about every 5 minutes" style={{ display: "inline-flex", alignItems: "center", gap: 7, padding: "6px 12px", borderRadius: "var(--radius-full)", background: "var(--surface-sunken)", border: "1px solid var(--border-subtle)" }}>
      <span style={{ width: 7, height: 7, borderRadius: "50%", background: "var(--status-sold-solid)", boxShadow: "0 0 0 3px rgba(16,185,129,0.15)" }} />
      <span style={{ fontSize: "var(--text-2xs)", fontWeight: 600, color: "var(--text-muted)", textTransform: "uppercase", letterSpacing: "0.08em" }}>Synced {mins} min ago</span>
    </div>
  );
}

function StatusPill({ silo, status }) {
  return (
    <span style={{ display: "inline-flex", alignItems: "center", gap: 6, padding: "3px 10px", borderRadius: "var(--radius-full)", background: "var(--surface-sunken)", border: "1px solid var(--border-subtle)", fontSize: "var(--text-2xs)", fontWeight: 600, color: "var(--text-secondary)", whiteSpace: "nowrap" }}>
      <span style={{ width: 6, height: 6, borderRadius: "50%", background: SILO_DOT[silo] || "var(--text-faint)" }} />
      {status}
    </span>
  );
}

function SiloChip({ silo }) {
  const s = window.CRM.SILO[silo] || {};
  return (
    <span style={{ display: "inline-flex", alignItems: "center", gap: 6, padding: "4px 11px", borderRadius: "var(--radius-full)", background: s.tone, fontSize: "var(--text-2xs)", fontWeight: 700, color: "var(--text-primary)", whiteSpace: "nowrap" }}>
      <Icon name={s.icon} size={12} />{s.label}
    </span>
  );
}

function PipelineStat({ silo, count, active, onClick }) {
  const s = window.CRM.SILO[silo];
  return (
    <button onClick={onClick} style={{ flex: "1 1 0", minWidth: 116, textAlign: "left", cursor: "pointer", background: "var(--surface-card)", border: `1px solid ${active ? "var(--color-primary)" : "var(--border-subtle)"}`, borderRadius: "var(--radius-lg)", boxShadow: active ? "var(--shadow-sm)" : "none", padding: "12px 14px", transition: "all var(--duration-fast) var(--ease-standard)" }}>
      <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", marginBottom: 8 }}>
        <span style={{ width: 26, height: 26, borderRadius: "var(--radius-md)", background: s.tone, display: "flex", alignItems: "center", justifyContent: "center", color: "var(--color-primary-deep)" }}><Icon name={s.icon} size={14} /></span>
        <span style={{ fontSize: "var(--text-2xl)", fontWeight: 700, letterSpacing: "-0.02em", fontVariantNumeric: "tabular-nums", color: "var(--text-primary)", lineHeight: 1 }}>{count}</span>
      </div>
      <div style={{ fontSize: "var(--text-2xs)", fontWeight: 600, textTransform: "uppercase", letterSpacing: "0.08em", color: "var(--text-muted)" }}>{s.label}</div>
    </button>
  );
}

function JobCard({ job, onOpen }) {
  return (
    <div onClick={() => onOpen(job)} style={{ background: "var(--surface-card)", border: "1px solid var(--border-subtle)", borderRadius: "var(--radius-lg)", padding: "13px 14px", cursor: "pointer", boxShadow: "var(--shadow-xs)", transition: "all var(--duration-fast) var(--ease-standard)" }}
      onMouseEnter={(e) => { e.currentTarget.style.boxShadow = "var(--shadow-md)"; e.currentTarget.style.transform = "translateY(-2px)"; }}
      onMouseLeave={(e) => { e.currentTarget.style.boxShadow = "var(--shadow-xs)"; e.currentTarget.style.transform = "none"; }}>
      <div style={{ display: "flex", alignItems: "flex-start", justifyContent: "space-between", gap: 8, marginBottom: 8 }}>
        <div style={{ fontSize: "var(--text-sm)", fontWeight: 700, color: "var(--text-primary)", lineHeight: 1.25 }}>{job.full_name}</div>
        <StatusPill silo={job.silo} status={job.status} />
      </div>
      <div style={{ display: "flex", alignItems: "center", gap: 6, fontSize: "var(--text-xs)", color: "var(--text-muted)", marginBottom: 4 }}>
        <Icon name="MapPin" size={13} color="var(--text-faint)" /><span style={{ overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }}>{job.full_address}</span>
      </div>
      <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", marginTop: 10, paddingTop: 9, borderTop: "1px solid var(--border-subtle)" }}>
        <span style={{ display: "inline-flex", alignItems: "center", gap: 5, fontSize: "var(--text-2xs)", color: "var(--text-muted)", fontWeight: 600 }}><Icon name="CalendarDays" size={12} />{window.CRM.fmtDay(job.action_date)}</span>
        <span style={{ fontSize: "var(--text-2xs)", color: "var(--text-faint)", fontVariantNumeric: "tabular-nums" }}>{job.id}</span>
      </div>
    </div>
  );
}

function JobsPipeline({ onOpenJob }) {
  const CRM = window.CRM;
  const [view, setView] = React.useState("board");
  const [q, setQ] = React.useState("");
  const [silo, setSilo] = React.useState("all");
  const [status, setStatus] = React.useState("all");
  const [sort, setSort] = React.useState({ key: "action_date", dir: "asc" });

  const statuses = ["all", ...[...new Set(CRM.jobs.map((j) => j.status))]];
  const match = (j) => {
    const t = q.trim().toLowerCase();
    const hitQ = !t || [j.full_name, j.phone, j.full_address].some((v) => (v || "").toLowerCase().includes(t));
    return hitQ && (silo === "all" || j.silo === silo) && (status === "all" || j.status === status);
  };
  const filtered = CRM.jobs.filter(match);
  const visibleSilos = silo === "all" ? CRM.SILOS : CRM.SILOS.filter((s) => s.key === silo);

  const getters = { full_name: (j) => j.full_name, silo: (j) => (CRM.SILO[j.silo] || {}).label, status: (j) => j.status, action_date: (j) => j.action_date };
  const rows = sortList(filtered, sort.key, sort.dir, getters[sort.key]);

  return (
    <div style={{ maxWidth: "var(--content-max)", margin: "0 auto" }}>
      <div style={{ display: "flex", alignItems: "flex-end", justifyContent: "space-between", gap: 16, marginBottom: 22 }}>
        <div>
          <h1 style={{ margin: 0, fontSize: "var(--text-2xl)", fontWeight: 700, letterSpacing: "-0.02em", color: "var(--text-primary)" }}>Jobs Pipeline</h1>
          <p style={{ margin: "4px 0 0", fontSize: "var(--text-sm)", color: "var(--text-muted)" }}>Read-only mirror of Engine 31 · {CRM.mirrorTotal.toLocaleString()} jobs across the pipeline</p>
        </div>
        <SyncIndicator />
      </div>

      {/* KPI strip — counts per stage (click to filter) */}
      <div style={{ display: "flex", gap: 10, marginBottom: 20, flexWrap: "wrap" }}>
        {CRM.SILOS.map((s) => (
          <PipelineStat key={s.key} silo={s.key} count={CRM.counts[s.key]} active={silo === s.key} onClick={() => setSilo(silo === s.key ? "all" : s.key)} />
        ))}
      </div>

      {/* Controls */}
      <div style={{ display: "flex", alignItems: "center", gap: 10, marginBottom: 16, flexWrap: "wrap" }}>
        <div style={{ display: "flex", alignItems: "center", gap: 9, background: "var(--input-bg)", border: "1px solid var(--border-subtle)", borderRadius: "var(--radius-lg)", padding: "9px 13px", flex: "1 1 280px", minWidth: 220 }}>
          <Icon name="Search" size={16} color="var(--text-muted)" />
          <input value={q} onChange={(e) => setQ(e.target.value)} placeholder="Search name, phone, or address…" style={{ border: "none", outline: "none", background: "transparent", fontFamily: "var(--font-sans)", fontSize: "var(--text-sm)", color: "var(--text-primary)", width: "100%" }} />
          {q && <button onClick={() => setQ("")} style={{ border: "none", background: "transparent", cursor: "pointer", color: "var(--text-faint)", display: "flex", padding: 0 }}><Icon name="X" size={15} /></button>}
        </div>
        <div style={{ width: 184 }}>
          <PipeSelect value={silo} onChange={(e) => setSilo(e.target.value)} options={[{ value: "all", label: "All Stages" }, ...CRM.SILOS.map((s) => ({ value: s.key, label: s.label }))]} />
        </div>
        <div style={{ width: 168 }}>
          <PipeSelect value={status} onChange={(e) => setStatus(e.target.value)} options={statuses.map((s) => ({ value: s, label: s === "all" ? "All Statuses" : s }))} />
        </div>
        <div style={{ display: "flex", background: "var(--surface-sunken)", border: "1px solid var(--border-subtle)", borderRadius: "var(--radius-lg)", padding: 3, gap: 2 }}>
          {[["board", "Kanban", "KanbanSquare"], ["table", "Table", "Table2"]].map(([v, label, ic]) => (
            <button key={v} onClick={() => setView(v)} title={label} style={{ display: "inline-flex", alignItems: "center", gap: 6, padding: "6px 12px", borderRadius: "var(--radius-md)", border: "none", cursor: "pointer", fontFamily: "var(--font-sans)", fontSize: "var(--text-xs)", fontWeight: 600, background: view === v ? "var(--surface-card)" : "transparent", color: view === v ? "var(--text-primary)" : "var(--text-muted)", boxShadow: view === v ? "var(--shadow-xs)" : "none" }}>
              <Icon name={ic} size={15} />{label}
            </button>
          ))}
        </div>
      </div>

      {/* Board */}
      {view === "board" && (
        <div style={{ display: "flex", gap: 14, overflowX: "auto", paddingBottom: 12, alignItems: "flex-start" }}>
          {visibleSilos.map((s) => {
            const list = filtered.filter((j) => j.silo === s.key);
            return (
              <div key={s.key} style={{ flex: "0 0 268px", width: 268, display: "flex", flexDirection: "column", gap: 10 }}>
                <div style={{ display: "flex", alignItems: "center", gap: 8, padding: "2px 4px" }}>
                  <span style={{ width: 24, height: 24, borderRadius: "var(--radius-sm)", background: s.tone, display: "flex", alignItems: "center", justifyContent: "center", color: "var(--color-primary-deep)" }}><Icon name={s.icon} size={13} /></span>
                  <span style={{ fontSize: "var(--text-2xs)", fontWeight: 700, textTransform: "uppercase", letterSpacing: "0.08em", color: "var(--text-secondary)" }}>{s.label}</span>
                  <span style={{ marginLeft: "auto", fontSize: "var(--text-2xs)", fontWeight: 700, color: "var(--text-faint)", fontVariantNumeric: "tabular-nums", background: "var(--surface-sunken)", borderRadius: "var(--radius-full)", padding: "1px 8px" }}>{list.length}</span>
                </div>
                <div style={{ display: "flex", flexDirection: "column", gap: 10 }}>
                  {list.map((j) => <JobCard key={j.id} job={j} onOpen={onOpenJob} />)}
                  {list.length === 0 && <div style={{ border: "1px dashed var(--border-default)", borderRadius: "var(--radius-lg)", padding: "16px 12px", textAlign: "center", fontSize: "var(--text-2xs)", color: "var(--text-faint)" }}>No jobs</div>}
                </div>
              </div>
            );
          })}
        </div>
      )}

      {/* Table */}
      {view === "table" && (
        <PipeCard padding="none" style={{ overflow: "hidden" }}>
          <div style={{ display: "grid", gridTemplateColumns: "1.8fr 1.1fr 1fr 1fr 0.9fr", gap: 16, padding: "11px 22px", background: "var(--surface-sunken)", borderBottom: "1px solid var(--border-subtle)" }}>
            <SortHeader label="Customer" k="full_name" sort={sort} setSort={setSort} />
            <SortHeader label="Stage" k="silo" sort={sort} setSort={setSort} />
            <SortHeader label="Status" k="status" sort={sort} setSort={setSort} />
            <PipeEyebrow size="2xs">Phone</PipeEyebrow>
            <SortHeader label="Action Date" k="action_date" sort={sort} setSort={setSort} />
          </div>
          {rows.length === 0 && <div style={{ padding: 32, textAlign: "center", fontSize: "var(--text-sm)", color: "var(--text-muted)" }}>No jobs match your search.</div>}
          {rows.map((j) => (
            <div key={j.id} onClick={() => onOpenJob(j)} style={{ display: "grid", gridTemplateColumns: "1.8fr 1.1fr 1fr 1fr 0.9fr", gap: 16, padding: "13px 22px", alignItems: "center", borderBottom: "1px solid var(--border-subtle)", cursor: "pointer" }}
              onMouseEnter={(e) => { e.currentTarget.style.background = "var(--surface-sunken)"; }}
              onMouseLeave={(e) => { e.currentTarget.style.background = "transparent"; }}>
              <div style={{ minWidth: 0 }}>
                <div style={{ fontSize: "var(--text-sm)", fontWeight: 600, color: "var(--text-primary)" }}>{j.full_name}</div>
                <div style={{ fontSize: "var(--text-xs)", color: "var(--text-muted)", marginTop: 2, overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }}>{j.id} · {j.full_address}</div>
              </div>
              <div><SiloChip silo={j.silo} /></div>
              <div><StatusPill silo={j.silo} status={j.status} /></div>
              <div style={{ fontSize: "var(--text-sm)", color: "var(--text-secondary)", fontVariantNumeric: "tabular-nums" }}>{j.phone}</div>
              <div style={{ fontSize: "var(--text-sm)", color: "var(--text-muted)", fontVariantNumeric: "tabular-nums" }}>{window.CRM.fmtDay(j.action_date)}</div>
            </div>
          ))}
        </PipeCard>
      )}
    </div>
  );
}

window.JobsPipeline = JobsPipeline;
window.CRMStatusPill = StatusPill;
window.CRMSiloChip = SiloChip;
window.CRMSyncIndicator = SyncIndicator;
