// Change Orders Tab — list + detail drawer with AI assist
// Status flow: Draft → Internal Review → Sent → Pending Approval → Approved | Rejected | Canceled

const CO_STATUS = {
  Draft:              { tone: "neutral",  next: "Submit for Review" },
  "Internal Review":  { tone: "info",     next: "Send to Customer" },
  Sent:               { tone: "purple",   next: "Mark Pending Approval" },
  "Pending Approval": { tone: "warning",  next: "Mark as Approved" },
  Approved:           { tone: "success",  next: "Apply to Project" },
  Rejected:           { tone: "danger",   next: null },
  Canceled:           { tone: "neutral",  next: null },
};

const CUSTOMER_APPROVAL = {
  "Not Sent":     { tone: "neutral",  icon: "circle" },
  "Awaiting":     { tone: "warning",  icon: "clock" },
  "Approved":     { tone: "success",  icon: "check" },
  "Rejected":     { tone: "danger",   icon: "cross" },
  "N/A":          { tone: "neutral",  icon: "circle" },
};

const REASONS = ["Owner Change", "Design Change", "Field Condition", "Schedule Acceleration", "Material Substitution", "Code/Permit", "Errors & Omissions"];

const CHANGE_ORDERS = [
  {
    id: "CO-014", title: "Add 240 modules — east tracker row extension", scope: "SOW-04 Module Installation",
    scopeId: "SOW-04",
    status: "Pending Approval", customerApproval: "Awaiting",
    revenue: 184_500, cost: 142_300, schedule: 6,
    owner: { initials: "EC", name: "Emma Connor", color: "#22863A" },
    updated: "2h ago", created: "04/24/2026", reason: "Owner Change",
    description: "Owner requested expansion of array on east edge to capture additional 96 kW. Includes 240 PV modules, additional racking, source-circuit harnesses, and DC combiner reconfiguration.",
    tasks: 6, docs: 4, billable: true,
    riskFlags: ["high-cost", "margin"],
  },
  {
    id: "CO-013", title: "Predrill 480 piles in north section refusal zone", scope: "SOW-02 Pile Driving",
    scopeId: "SOW-02",
    status: "Approved", customerApproval: "Approved",
    revenue: 92_800, cost: 78_400, schedule: 4,
    owner: { initials: "RF", name: "Robert Fox", color: "#76ADFF" },
    updated: "Yesterday", created: "04/02/2026", reason: "Field Condition",
    description: "Geotech encountered refusal in north section. Predrilling required for 480 piles with 6\" carbide bit. Includes equipment rental and crew time.",
    tasks: 3, docs: 6, billable: true,
    approvedDate: "04/15/2026", approvedBy: "Brad Sterling — Solis Energy",
  },
  {
    id: "CO-012", title: "Substitute galvanized racking — supply chain delay", scope: "SOW-03 Racking",
    scopeId: "SOW-03",
    status: "Sent", customerApproval: "Awaiting",
    revenue: 0, cost: 24_600, schedule: 0,
    owner: { initials: "JL", name: "Jordan Lin", color: "#FF9143" },
    updated: "3d ago", created: "04/18/2026", reason: "Material Substitution",
    description: "Original racking lead time slipped 14 weeks. Approved equivalent galvanized alternative from Unirac. Cost-only CO; revenue unchanged.",
    tasks: 2, docs: 3, billable: false,
    riskFlags: ["margin"],
  },
  {
    id: "CO-011", title: "Schedule acceleration — add second crew to torque tubes", scope: "SOW-03 Racking",
    scopeId: "SOW-03",
    status: "Internal Review", customerApproval: "Not Sent",
    revenue: 68_400, cost: 71_200, schedule: -10,
    owner: { initials: "EC", name: "Emma Connor", color: "#22863A" },
    updated: "Today", created: "04/28/2026", reason: "Schedule Acceleration",
    description: "Owner requested 10-day pull-in on substantial completion. Adding second torque-tube crew with overtime authorization through May 30.",
    tasks: 4, docs: 2, billable: true,
    riskFlags: ["margin"],
  },
  {
    id: "CO-010", title: "Add SCADA integration to Owner DAS", scope: "SOW-06 Commissioning",
    scopeId: "SOW-06",
    status: "Draft", customerApproval: "Not Sent",
    revenue: 38_200, cost: 26_900, schedule: 2,
    owner: { initials: "NM", name: "Nick Merley", color: "#B279FF" },
    updated: "5d ago", created: "04/22/2026", reason: "Design Change",
    description: "Owner data acquisition system requires Modbus integration with tracker controllers. Includes additional cabling, gateway, and commissioning support.",
    tasks: 2, docs: 1, billable: true,
  },
  {
    id: "CO-009", title: "Erosion control extension — 60 day SWPPP", scope: "SOW-01 Site Prep",
    scopeId: "SOW-01",
    status: "Approved", customerApproval: "Approved",
    revenue: 12_400, cost: 9_800, schedule: 0,
    owner: { initials: "RF", name: "Robert Fox", color: "#76ADFF" },
    updated: "1w ago", created: "03/18/2026", reason: "Code/Permit",
    description: "County requested SWPPP extension to cover full pile-driving phase. Includes additional silt fencing and weekly inspections.",
    tasks: 1, docs: 2, billable: true,
    approvedDate: "03/24/2026", approvedBy: "Brad Sterling — Solis Energy",
  },
  {
    id: "CO-008", title: "Replace damaged transformer pad — vandalism", scope: "SOW-05 Electrical",
    scopeId: "SOW-05",
    status: "Rejected", customerApproval: "Rejected",
    revenue: 14_800, cost: 14_800, schedule: 3,
    owner: { initials: "NM", name: "Nick Merley", color: "#B279FF" },
    updated: "2w ago", created: "03/02/2026", reason: "Field Condition",
    description: "Transformer pad damaged during off-hours. Owner directed insurance claim path; pursuing reimbursement through carrier instead.",
    tasks: 0, docs: 3, billable: false,
  },
  {
    id: "CO-007", title: "Permit fee adjustment — county rate change", scope: "SOW-01 Site Prep",
    scopeId: "SOW-01",
    status: "Canceled", customerApproval: "N/A",
    revenue: 0, cost: 4_200, schedule: 0,
    owner: { initials: "RF", name: "Robert Fox", color: "#76ADFF" },
    updated: "3w ago", created: "02/12/2026", reason: "Code/Permit",
    description: "County rolled back proposed fee increase before billing. CO no longer required.",
    tasks: 0, docs: 1, billable: false,
  },
];

const ACTIVITY = [
  { co: "CO-014", who: "EC", when: "2h ago",   action: "Submitted to customer for approval", icon: "send", tone: "info" },
  { co: "CO-014", who: "EC", when: "Yesterday", action: "Internal review completed", icon: "check", tone: "success" },
  { co: "CO-014", who: "AI", when: "Yesterday", action: "Generated draft from owner email thread", icon: "sparkles", tone: "purple" },
  { co: "CO-014", who: "EC", when: "04/24",     action: "Created draft", icon: "plus", tone: "neutral" },
];

const ChangeOrdersTab = ({ p }) => {
  const [search, setSearch] = React.useState("");
  const [statusFilter, setStatusFilter] = React.useState("All");
  const [scopeFilter, setScopeFilter] = React.useState("All");
  const [ownerFilter, setOwnerFilter] = React.useState("All");
  const [pendingOnly, setPendingOnly] = React.useState(false);
  const [selectedId, setSelectedId] = React.useState("CO-014");

  const filtered = CHANGE_ORDERS.filter(co => {
    if (statusFilter !== "All" && co.status !== statusFilter) return false;
    if (scopeFilter !== "All" && co.scopeId !== scopeFilter) return false;
    if (ownerFilter !== "All" && co.owner.name !== ownerFilter) return false;
    if (pendingOnly && !["Pending Approval", "Sent", "Internal Review"].includes(co.status)) return false;
    if (search && !(`${co.id} ${co.title}`.toLowerCase()).includes(search.toLowerCase())) return false;
    return true;
  });

  const selected = CHANGE_ORDERS.find(c => c.id === selectedId) || filtered[0];

  // KPIs
  const total = CHANGE_ORDERS.reduce((s, co) => s + co.revenue, 0);
  const approved = CHANGE_ORDERS.filter(c => c.status === "Approved");
  const approvedVal = approved.reduce((s, c) => s + c.revenue, 0);
  const pending = CHANGE_ORDERS.filter(c => ["Pending Approval", "Sent", "Internal Review"].includes(c.status));
  const pendingVal = pending.reduce((s, c) => s + c.revenue, 0);
  const rejected = CHANGE_ORDERS.filter(c => c.status === "Rejected" || c.status === "Canceled");
  const draftCount = CHANGE_ORDERS.filter(c => c.status === "Draft").length;
  const totalRev = CHANGE_ORDERS.reduce((s, c) => s + c.revenue, 0);
  const totalCost = CHANGE_ORDERS.reduce((s, c) => s + c.cost, 0);
  const marginImpact = totalRev - totalCost;

  const owners = ["All", ...Array.from(new Set(CHANGE_ORDERS.map(c => c.owner.name)))];
  const scopes = ["All", ...Array.from(new Set(CHANGE_ORDERS.map(c => c.scopeId)))];

  return (
    <div style={{ display: "flex", flexDirection: "column", gap: 16 }}>
      {/* KPI strip */}
      <div style={{ display: "grid", gridTemplateColumns: "repeat(5, 1fr)", gap: 12 }}>
        <COKPI label="Total CO Value" value={fmtMoney(total)} sub={`${CHANGE_ORDERS.length} total`} icon="refresh" />
        <COKPI
          label="Approved"
          value={fmtMoney(approvedVal)}
          sub={`${approved.length} approved`}
          accent="rgb(34,134,58)"
          accentBg="rgba(208,243,217,.5)"
        />
        <COKPI
          label="Pending Approval"
          value={fmtMoney(pendingVal)}
          sub={`${pending.length} awaiting action`}
          accent="rgb(178,121,26)"
          accentBg="rgba(255,243,210,.5)"
          urgent
        />
        <COKPI
          label="Rejected / Canceled"
          value={`${rejected.length}`}
          sub={`${draftCount} drafts`}
          accent="rgb(106,115,131)"
        />
        <COKPI
          label="Margin Impact"
          value={`${marginImpact >= 0 ? "+" : "−"}${fmtMoney(Math.abs(marginImpact))}`}
          sub={`${((marginImpact/totalRev)*100).toFixed(1)}% blended`}
          accent={marginImpact >= 0 ? "rgb(34,134,58)" : "rgb(192,47,50)"}
        />
      </div>

      {/* Toolbar */}
      <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", gap: 12, flexWrap: "wrap" }}>
        <div style={{ display: "flex", alignItems: "center", gap: 8, flexWrap: "wrap" }}>
          <div style={{ position: "relative", width: 260 }}>
            <span style={{ position: "absolute", left: 10, top: 8, opacity: 0.5 }}>
              <Icon name="search" size={14} color="rgb(106,115,131)" />
            </span>
            <input value={search} onChange={e => setSearch(e.target.value)} placeholder="Search CO #, title, scope…" style={{
              width: "100%", boxSizing: "border-box", paddingLeft: 30, paddingRight: 10, height: 30, borderRadius: 9999,
              border: "1px solid rgb(213,219,225)", fontSize: 13, fontFamily: "inherit", outline: "none", background: "#fff"
            }} />
          </div>
          <FilterPill2Click label="Status" value={statusFilter} options={["All", ...Object.keys(CO_STATUS)]} onChange={setStatusFilter} icon="flag" />
          <FilterPill2Click label="Scope" value={scopeFilter} options={scopes} onChange={setScopeFilter} icon="layers" />
          <FilterPill2Click label="Owner" value={ownerFilter} options={owners} onChange={setOwnerFilter} icon="user" />
          <button onClick={() => setPendingOnly(!pendingOnly)} style={{
            height: 28, padding: "0 12px", borderRadius: 9999,
            background: pendingOnly ? "rgb(255,243,210)" : "#fff",
            border: `1px solid ${pendingOnly ? "rgb(228,182,68)" : "rgb(213,219,225)"}`,
            color: pendingOnly ? "rgb(178,121,26)" : "rgb(65,69,82)",
            fontSize: 12, fontWeight: 500, fontFamily: "inherit", cursor: "pointer",
            display: "inline-flex", alignItems: "center", gap: 5, whiteSpace: "nowrap"
          }}>
            <Icon name="clock" size={12} />
            Pending Approval Only
            {pendingOnly && <Icon name="cross" size={10} />}
          </button>
        </div>
        <div style={{ display: "flex", gap: 6 }}>
          <Button kind="ghost" size="sm" icon="sparkles">AI Draft</Button>
          <Button kind="ghost" size="sm" icon="download">Export</Button>
          <Button kind="primary" size="sm" icon="plus">Create Change Order</Button>
        </div>
      </div>

      {/* Split: list + detail */}
      <div style={{ display: "grid", gridTemplateColumns: "minmax(0, 1fr) minmax(0, 1.2fr)", gap: 16, alignItems: "flex-start" }}>
        {/* List */}
        <Card padding={0}>
          <div style={{
            padding: "10px 14px", fontSize: 11, fontWeight: 600, color: "rgb(106,115,131)",
            background: "rgb(252,252,253)", borderBottom: "1px solid rgb(239,240,242)",
            textTransform: "uppercase", letterSpacing: ".04em",
            display: "flex", justifyContent: "space-between", alignItems: "center"
          }}>
            <span>{filtered.length} Change Order{filtered.length === 1 ? "" : "s"}</span>
            <span style={{ display: "flex", alignItems: "center", gap: 4, cursor: "pointer" }}>
              Sort: Recent <Icon name="expandDown" size={10} />
            </span>
          </div>
          {filtered.map((co, i) => {
            const isSel = co.id === selectedId;
            return (
              <div key={co.id} onClick={() => setSelectedId(co.id)} style={{
                padding: "12px 14px", cursor: "pointer",
                borderBottom: i < filtered.length - 1 ? "1px solid rgb(239,240,242)" : "none",
                background: isSel ? "rgba(232,233,246,.5)" : "#fff",
                borderLeft: isSel ? "3px solid rgb(83,74,255)" : "3px solid transparent",
                paddingLeft: isSel ? 11 : 14, fontSize: 13,
                transition: "background 120ms",
                display: "flex", flexDirection: "column", gap: 8,
              }}
              onMouseEnter={e => { if (!isSel) e.currentTarget.style.background = "rgb(248,248,251)"; }}
              onMouseLeave={e => { if (!isSel) e.currentTarget.style.background = "#fff"; }}>
                {/* Top: CO # + Status + meta */}
                <div style={{ display: "flex", alignItems: "center", gap: 8, justifyContent: "space-between" }}>
                  <div style={{ display: "flex", alignItems: "center", gap: 8, minWidth: 0, flex: 1 }}>
                    <span style={{ fontSize: 12, fontWeight: 600, color: isSel ? "rgb(83,74,255)" : "rgb(106,115,131)", fontVariantNumeric: "tabular-nums", flexShrink: 0 }}>{co.id}</span>
                    <Chip tone={CO_STATUS[co.status].tone} dot>{co.status}</Chip>
                  </div>
                  <div style={{ display: "flex", alignItems: "center", gap: 6, flexShrink: 0 }}>
                    <Avatar size={18} initials={co.owner.initials} color={co.owner.color} />
                    <span style={{ fontSize: 11, color: "rgb(106,115,131)", whiteSpace: "nowrap" }}>{co.updated}</span>
                  </div>
                </div>
                {/* Title */}
                <div style={{ fontWeight: 500, color: "rgb(26,27,37)", lineHeight: 1.35, fontSize: 13.5, overflow: "hidden", textOverflow: "ellipsis", display: "-webkit-box", WebkitLineClamp: 2, WebkitBoxOrient: "vertical" }}>{co.title}</div>
                {/* Bottom: scope + impact strip */}
                <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", gap: 8 }}>
                  <div style={{ display: "inline-flex", alignItems: "center", gap: 5, fontSize: 11, color: "rgb(106,115,131)", minWidth: 0, flex: 1 }}>
                    <Icon name="layers" size={11} />
                    <span style={{ whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis" }}>{co.scope}</span>
                  </div>
                  <div style={{ display: "inline-flex", alignItems: "center", gap: 8, fontSize: 12, fontVariantNumeric: "tabular-nums", flexShrink: 0 }}>
                    <span style={{ fontWeight: 600, color: co.revenue > 0 ? "rgb(34,134,58)" : co.revenue < 0 ? "rgb(192,47,50)" : "rgb(106,115,131)" }}>
                      {co.revenue > 0 ? "+" : co.revenue < 0 ? "−" : ""}{fmtMoney(Math.abs(co.revenue))}
                    </span>
                    <span style={{ width: 3, height: 3, borderRadius: "50%", background: "rgb(213,219,225)" }} />
                    <span style={{ color: "rgb(106,115,131)", fontWeight: 500 }}>−{fmtMoney(co.cost)}</span>
                    {co.schedule !== 0 && (
                      <>
                        <span style={{ width: 3, height: 3, borderRadius: "50%", background: "rgb(213,219,225)" }} />
                        <span style={{ display: "inline-flex", alignItems: "center", gap: 3, color: co.schedule > 0 ? "rgb(192,47,50)" : "rgb(34,134,58)", fontWeight: 500 }}>
                          <Icon name="clock" size={10} />
                          {co.schedule > 0 ? `+${co.schedule}d` : `${co.schedule}d`}
                        </span>
                      </>
                    )}
                  </div>
                </div>
                {/* Customer approval pill */}
                {co.customerApproval !== "N/A" && co.customerApproval !== "Not Sent" && (
                  <div style={{ marginTop: -2 }}>
                    <CustomerApprovalBadge status={co.customerApproval} />
                  </div>
                )}
              </div>
            );
          })}
          {filtered.length === 0 && (
            <div style={{ padding: "40px 16px", textAlign: "center", color: "rgb(106,115,131)", fontSize: 13 }}>
              <div style={{ marginBottom: 6 }}>No change orders match these filters.</div>
              <Button size="sm" kind="ghost" onClick={() => { setSearch(""); setStatusFilter("All"); setScopeFilter("All"); setOwnerFilter("All"); setPendingOnly(false); }}>Reset filters</Button>
            </div>
          )}
        </Card>

        {/* Detail drawer */}
        {selected && <COSideDrawer co={selected} />}
      </div>
    </div>
  );
};

const COKPI = ({ label, value, sub, accent, accentBg, urgent, icon }) => (
  <div style={{
    background: "#fff", border: `1px solid ${urgent ? "rgba(228,182,68,.6)" : "rgb(227,229,232)"}`,
    borderRadius: 12, padding: "14px 16px", position: "relative", overflow: "hidden"
  }}>
    {urgent && <div style={{ position: "absolute", top: 0, right: 0, width: 60, height: 60, background: "rgba(255,243,210,.6)", borderRadius: "50%", transform: "translate(20px,-20px)" }} />}
    <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", marginBottom: 6, position: "relative" }}>
      <span style={{ fontSize: 11, color: "rgb(106,115,131)", fontWeight: 500, textTransform: "uppercase", letterSpacing: ".04em" }}>{label}</span>
      {icon && <Icon name={icon} size={13} color={accent || "rgb(106,115,131)"} />}
    </div>
    <div style={{ fontSize: 22, fontWeight: 700, letterSpacing: "-.015em", fontVariantNumeric: "tabular-nums", color: accent || "rgb(26,27,37)", position: "relative" }}>{value}</div>
    <div style={{ fontSize: 12, color: "rgb(106,115,131)", marginTop: 4, position: "relative" }}>{sub}</div>
  </div>
);

const FilterPill2Click = ({ label, value, options, onChange, icon }) => {
  const [open, setOpen] = React.useState(false);
  const ref = React.useRef();
  React.useEffect(() => {
    const close = (e) => { if (ref.current && !ref.current.contains(e.target)) setOpen(false); };
    document.addEventListener("mousedown", close);
    return () => document.removeEventListener("mousedown", close);
  }, []);
  const active = value !== "All";
  return (
    <div ref={ref} style={{ position: "relative" }}>
      <button onClick={() => setOpen(!open)} style={{
        height: 28, padding: "0 10px", borderRadius: 9999,
        background: active ? "rgb(232,233,246)" : "#fff",
        border: `1px solid ${active ? "rgb(178,172,255)" : "rgb(213,219,225)"}`,
        color: active ? "rgb(83,74,255)" : "rgb(65,69,82)",
        fontSize: 12, fontWeight: 500, fontFamily: "inherit", cursor: "pointer",
        display: "inline-flex", alignItems: "center", gap: 5, whiteSpace: "nowrap"
      }}>
        {icon && <Icon name={icon} size={12} />}
        <span style={{ color: "rgb(106,115,131)" }}>{label}:</span>
        <span style={{ fontWeight: 600 }}>{value}</span>
        <Icon name="expandDown" size={11} />
      </button>
      {open && (
        <div style={{ position: "absolute", top: 32, left: 0, background: "#fff", border: "1px solid rgb(227,229,232)", borderRadius: 8, padding: 4, minWidth: 200, boxShadow: "0 4px 12px rgba(43,46,83,.08)", zIndex: 10, maxHeight: 280, overflowY: "auto" }}>
          {options.map(opt => (
            <div key={opt} onClick={() => { onChange(opt); setOpen(false); }} style={{
              padding: "7px 10px", borderRadius: 6, fontSize: 13, cursor: "pointer",
              color: opt === value ? "rgb(83,74,255)" : "rgb(26,27,37)",
              background: opt === value ? "rgb(232,233,246)" : "transparent",
              display: "flex", alignItems: "center", justifyContent: "space-between"
            }}
            onMouseEnter={e => { if (opt !== value) e.currentTarget.style.background = "rgb(248,248,251)"; }}
            onMouseLeave={e => { if (opt !== value) e.currentTarget.style.background = "transparent"; }}>
              {opt}
              {opt === value && <Icon name="check" size={13} color="rgb(83,74,255)" />}
            </div>
          ))}
        </div>
      )}
    </div>
  );
};

const CustomerApprovalBadge = ({ status }) => {
  const cfg = CUSTOMER_APPROVAL[status];
  if (!cfg) return null;
  const t = TONES[cfg.tone];
  return (
    <span style={{ display: "inline-flex", alignItems: "center", gap: 4, fontSize: 11, color: t.fg, fontWeight: 500 }}>
      <Icon name={cfg.icon} size={10} />
      Customer: {status}
    </span>
  );
};

const ImpactValue = ({ value, label, muted }) => {
  const positive = value > 0;
  const negative = value < 0;
  return (
    <span style={{
      fontSize: 12, fontVariantNumeric: "tabular-nums",
      color: muted ? "rgb(106,115,131)" : positive ? "rgb(34,134,58)" : negative ? "rgb(192,47,50)" : "rgb(26,27,37)",
      fontWeight: 600,
    }}>
      <span style={{ color: "rgb(106,115,131)", fontWeight: 400, marginRight: 4 }}>{label}</span>
      {value > 0 ? "+" : value < 0 ? "−" : ""}{fmtMoney(Math.abs(value))}
    </span>
  );
};

const COSideDrawer = ({ co }) => {
  const margin = co.revenue - co.cost;
  const marginPct = co.revenue > 0 ? (margin / co.revenue) * 100 : 0;
  const cfg = CO_STATUS[co.status];
  const isHighCost = co.cost > 100_000;
  const isMarginRisk = marginPct < 15 && co.revenue > 0;
  const isScheduleRisk = co.schedule >= 5;

  return (
    <div style={{ display: "flex", flexDirection: "column", gap: 12, position: "sticky", top: 200 }}>
      {/* Header card */}
      <Card padding={0}>
        <div style={{ padding: "16px 18px", borderBottom: "1px solid rgb(239,240,242)" }}>
          <div style={{ display: "flex", alignItems: "flex-start", justifyContent: "space-between", gap: 12, marginBottom: 8 }}>
            <div style={{ minWidth: 0, flex: 1 }}>
              <div style={{ display: "flex", alignItems: "center", gap: 8, marginBottom: 4 }}>
                <span style={{ fontSize: 12, color: "rgb(106,115,131)", fontWeight: 600, fontVariantNumeric: "tabular-nums" }}>{co.id}</span>
                <Chip tone={cfg.tone} dot>{co.status}</Chip>
                <CustomerApprovalBadge status={co.customerApproval} />
              </div>
              <h2 style={{ fontSize: 17, fontWeight: 700, margin: 0, letterSpacing: "-.01em", lineHeight: 1.3 }}>{co.title}</h2>
              <div style={{ display: "flex", alignItems: "center", gap: 12, marginTop: 8, fontSize: 12, color: "rgb(106,115,131)" }}>
                <span style={{ display: "inline-flex", alignItems: "center", gap: 5 }}>
                  <Avatar size={16} initials={co.owner.initials} color={co.owner.color} />
                  {co.owner.name}
                </span>
                <span style={{ width: 3, height: 3, borderRadius: "50%", background: "rgb(163,172,186)" }} />
                <span>Created {co.created}</span>
                <span style={{ width: 3, height: 3, borderRadius: "50%", background: "rgb(163,172,186)" }} />
                <span>Updated {co.updated}</span>
              </div>
            </div>
            <IconBtn icon="more" tone="outline" size={28} />
          </div>

          {/* Action bar — next-best-action highlighted */}
          <div style={{ display: "flex", gap: 6, flexWrap: "wrap", paddingTop: 12, borderTop: "1px solid rgb(239,240,242)" }}>
            {cfg.next && <Button kind="primary" size="sm" icon="check">{cfg.next}</Button>}
            {co.status === "Draft" && <Button kind="secondary" size="sm" icon="bookmark">Save Draft</Button>}
            {(co.status === "Approved") && <Button kind="secondary" size="sm" icon="receipt">Convert to Billing</Button>}
            {!["Approved", "Rejected", "Canceled"].includes(co.status) && <Button kind="ghost" size="sm" icon="cross">Reject / Cancel</Button>}
          </div>
        </div>
      </Card>

      {/* AI Insight Card */}
      {(isHighCost || isMarginRisk || isScheduleRisk) && (
        <div style={{
          background: "linear-gradient(180deg, rgba(232,233,246,.6) 0%, rgba(232,233,246,.3) 100%)",
          border: "1px solid rgba(178,172,255,.4)", borderRadius: 12, padding: 14
        }}>
          <div style={{ display: "flex", alignItems: "center", gap: 8, marginBottom: 10 }}>
            <div style={{ width: 24, height: 24, borderRadius: 6, background: "rgb(232,233,246)", display: "flex", alignItems: "center", justifyContent: "center" }}>
              <Icon name="sparkles" size={13} color="rgb(83,74,255)" />
            </div>
            <span style={{ fontSize: 12, fontWeight: 600, color: "rgb(83,74,255)", textTransform: "uppercase", letterSpacing: ".05em" }}>AI Summary</span>
          </div>
          <div style={{ fontSize: 13, color: "rgb(26,27,37)", lineHeight: 1.5, marginBottom: 10 }}>
            This change order adds <strong>{fmtMoney(co.revenue)}</strong> in revenue against <strong>{fmtMoney(co.cost)}</strong> in cost — a <strong style={{ color: marginPct < 15 ? "rgb(192,47,50)" : marginPct < 22 ? "rgb(178,121,26)" : "rgb(34,134,58)" }}>{marginPct.toFixed(1)}% margin</strong>{co.schedule !== 0 && <> with a <strong>{co.schedule > 0 ? `${co.schedule}-day` : `${Math.abs(co.schedule)}-day`} {co.schedule > 0 ? "schedule extension" : "acceleration"}</strong></>}.
          </div>
          <div style={{ display: "flex", flexDirection: "column", gap: 6 }}>
            {isHighCost && <AIAlert tone="warning" icon="dollar" text={`Cost above ${fmtMoney(100_000)} threshold — requires CFO sign-off per company policy`} />}
            {isMarginRisk && <AIAlert tone="danger" icon="trendingDown" text={`Margin ${marginPct.toFixed(1)}% falls below 15% project floor — consider negotiating revenue uplift`} />}
            {isScheduleRisk && <AIAlert tone="warning" icon="clock" text={`${co.schedule}-day schedule extension may push substantial completion past liquidated-damages date`} />}
          </div>
        </div>
      )}

      {/* Financial Impact */}
      <Card>
        <div style={{ display: "flex", alignItems: "center", gap: 8, marginBottom: 12 }}>
          <div style={{ width: 24, height: 24, borderRadius: 6, background: "rgb(232,233,246)", display: "flex", alignItems: "center", justifyContent: "center" }}>
            <Icon name="dollar" size={13} color="rgb(83,74,255)" />
          </div>
          <span style={{ fontSize: 13, fontWeight: 600 }}>Financial Impact</span>
        </div>
        <div style={{ display: "grid", gridTemplateColumns: "repeat(3, 1fr)", gap: 0, border: "1px solid rgb(239,240,242)", borderRadius: 10, overflow: "hidden" }}>
          <FinancialCell label="Revenue" value={co.revenue} sign positive={co.revenue > 0} />
          <FinancialCell label="Cost" value={co.cost} sign negative={co.cost > 0} divider />
          <FinancialCell label="Margin" value={margin} sign positive={margin > 0} negative={margin < 0} sub={`${marginPct.toFixed(1)}%`} divider />
        </div>
      </Card>

      {/* Description + Reason */}
      <Card>
        <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", marginBottom: 10 }}>
          <span style={{ fontSize: 13, fontWeight: 600 }}>Description</span>
          <span style={{ display: "inline-flex", alignItems: "center", gap: 5, fontSize: 11, padding: "3px 8px", borderRadius: 9999, background: "rgb(241,242,244)", color: "rgb(65,69,82)", fontWeight: 500 }}>
            <Icon name="tag" size={10} /> {co.reason}
          </span>
        </div>
        <div style={{ fontSize: 13, color: "rgb(65,69,82)", lineHeight: 1.55 }}>{co.description}</div>
      </Card>

      {/* Scope & Schedule */}
      <Card>
        <div style={{ fontSize: 13, fontWeight: 600, marginBottom: 12 }}>Scope & Schedule Impact</div>
        <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 12 }}>
          <div style={{ padding: 12, background: "rgb(248,248,251)", borderRadius: 8 }}>
            <div style={{ fontSize: 11, color: "rgb(106,115,131)", fontWeight: 500, textTransform: "uppercase", letterSpacing: ".04em", marginBottom: 6 }}>Linked Scope</div>
            <div style={{ display: "flex", alignItems: "center", gap: 6 }}>
              <Icon name="layers" size={13} color="rgb(83,74,255)" />
              <span style={{ fontSize: 13, fontWeight: 500 }}>{co.scope}</span>
            </div>
            <div style={{ marginTop: 8, fontSize: 11, color: "rgb(106,115,131)" }}>
              {co.tasks} task{co.tasks === 1 ? "" : "s"} affected
            </div>
          </div>
          <div style={{ padding: 12, background: co.schedule > 0 ? "rgba(252,226,226,.4)" : co.schedule < 0 ? "rgba(208,243,217,.4)" : "rgb(248,248,251)", borderRadius: 8 }}>
            <div style={{ fontSize: 11, color: "rgb(106,115,131)", fontWeight: 500, textTransform: "uppercase", letterSpacing: ".04em", marginBottom: 6 }}>Schedule Impact</div>
            <div style={{ display: "flex", alignItems: "center", gap: 6 }}>
              <Icon name="clock" size={13} color={co.schedule > 0 ? "rgb(192,47,50)" : co.schedule < 0 ? "rgb(34,134,58)" : "rgb(106,115,131)"} />
              <span style={{ fontSize: 13, fontWeight: 600, fontVariantNumeric: "tabular-nums", color: co.schedule > 0 ? "rgb(192,47,50)" : co.schedule < 0 ? "rgb(34,134,58)" : "rgb(26,27,37)" }}>
                {co.schedule === 0 ? "No schedule impact" : co.schedule > 0 ? `+${co.schedule} days` : `${co.schedule} days`}
              </span>
            </div>
            <div style={{ marginTop: 8, fontSize: 11, color: "rgb(106,115,131)" }}>
              {co.schedule > 0 ? "Pushes completion later" : co.schedule < 0 ? "Accelerates completion" : "On baseline schedule"}
            </div>
          </div>
        </div>
      </Card>

      {/* Approval */}
      <Card>
        <div style={{ fontSize: 13, fontWeight: 600, marginBottom: 12 }}>Approval</div>
        <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 14 }}>
          <ApprovalSlot
            label="Internal"
            status={["Internal Review", "Sent", "Pending Approval", "Approved"].includes(co.status) ? "Approved" : "Pending"}
            who={co.owner.name}
            when={co.status === "Draft" ? "—" : co.created}
          />
          <ApprovalSlot
            label="Customer"
            status={co.customerApproval}
            who={co.approvedBy || "—"}
            when={co.approvedDate || (co.customerApproval === "Awaiting" ? "Sent " + co.updated : "—")}
          />
        </div>
      </Card>

      {/* Related items */}
      <Card>
        <div style={{ fontSize: 13, fontWeight: 600, marginBottom: 10 }}>Related Items</div>
        <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr 1fr", gap: 8 }}>
          <RelatedTile icon="list" label="Tasks" count={co.tasks} />
          <RelatedTile icon="folder" label="Documents" count={co.docs} />
          <RelatedTile icon="receipt" label="Billing" count={co.billable ? 1 : 0} subtitle={co.billable ? "Eligible" : "Not billable"} />
        </div>
      </Card>

      {/* Activity */}
      <Card padding={0}>
        <div style={{ padding: "12px 16px", borderBottom: "1px solid rgb(239,240,242)", display: "flex", alignItems: "center", justifyContent: "space-between" }}>
          <span style={{ fontSize: 13, fontWeight: 600 }}>Activity</span>
          <Button size="xs" kind="ghost" icon="plus">Comment</Button>
        </div>
        <div style={{ padding: "8px 16px 14px" }}>
          {ACTIVITY.filter(a => a.co === co.id).map((a, i, arr) => (
            <div key={i} style={{ display: "flex", gap: 10, paddingTop: i === 0 ? 6 : 0 }}>
              <div style={{ display: "flex", flexDirection: "column", alignItems: "center", flexShrink: 0 }}>
                <div style={{
                  width: 26, height: 26, borderRadius: "50%", background: TONES[a.tone].bg,
                  display: "flex", alignItems: "center", justifyContent: "center", flexShrink: 0
                }}>
                  <Icon name={a.icon} size={13} color={TONES[a.tone].fg} />
                </div>
                {i < arr.length - 1 && <div style={{ width: 1, flex: 1, background: "rgb(239,240,242)", minHeight: 14 }} />}
              </div>
              <div style={{ paddingBottom: 14, flex: 1 }}>
                <div style={{ fontSize: 13, color: "rgb(26,27,37)" }}>{a.action}</div>
                <div style={{ fontSize: 11, color: "rgb(106,115,131)", marginTop: 2 }}>{a.who} · {a.when}</div>
              </div>
            </div>
          ))}
          {ACTIVITY.filter(a => a.co === co.id).length === 0 && (
            <div style={{ fontSize: 12, color: "rgb(106,115,131)", padding: "12px 0", textAlign: "center" }}>No activity yet.</div>
          )}
        </div>
      </Card>
    </div>
  );
};

const FinancialCell = ({ label, value, sign, positive, negative, sub, divider }) => (
  <div style={{
    padding: "12px 14px",
    borderLeft: divider ? "1px solid rgb(239,240,242)" : "none",
    background: positive ? "rgba(208,243,217,.25)" : negative ? "rgba(252,226,226,.25)" : "#fff",
  }}>
    <div style={{ fontSize: 11, color: "rgb(106,115,131)", fontWeight: 500, textTransform: "uppercase", letterSpacing: ".04em" }}>{label}</div>
    <div style={{ fontSize: 18, fontWeight: 700, fontVariantNumeric: "tabular-nums", marginTop: 4, color: positive ? "rgb(34,134,58)" : negative ? "rgb(192,47,50)" : "rgb(26,27,37)" }}>
      {sign && (positive ? "+" : negative ? "−" : "")}{fmtMoney(Math.abs(value))}
    </div>
    {sub && <div style={{ fontSize: 12, color: "rgb(106,115,131)", marginTop: 2, fontVariantNumeric: "tabular-nums" }}>{sub}</div>}
  </div>
);

const AIAlert = ({ tone, icon, text }) => (
  <div style={{
    display: "flex", gap: 8, padding: "8px 10px", borderRadius: 8,
    background: TONES[tone].bg, border: `1px solid ${TONES[tone].fg}22`
  }}>
    <Icon name={icon} size={14} color={TONES[tone].fg} style={{ marginTop: 1, flexShrink: 0 }} />
    <span style={{ fontSize: 12, color: "rgb(26,27,37)", lineHeight: 1.45 }}>{text}</span>
  </div>
);

const ApprovalSlot = ({ label, status, who, when }) => {
  const cfg = CUSTOMER_APPROVAL[status] || { tone: "neutral", icon: "circle" };
  const tone = status === "Approved" ? "success" : status === "Rejected" ? "danger" : status === "Awaiting" || status === "Pending" ? "warning" : "neutral";
  const t = TONES[tone];
  return (
    <div style={{ padding: 12, border: "1px solid rgb(239,240,242)", borderRadius: 8 }}>
      <div style={{ fontSize: 11, color: "rgb(106,115,131)", fontWeight: 500, textTransform: "uppercase", letterSpacing: ".04em", marginBottom: 8 }}>{label}</div>
      <div style={{ display: "flex", alignItems: "center", gap: 6, marginBottom: 8 }}>
        <div style={{ width: 22, height: 22, borderRadius: "50%", background: t.bg, display: "flex", alignItems: "center", justifyContent: "center" }}>
          <Icon name={cfg.icon} size={12} color={t.fg} />
        </div>
        <span style={{ fontSize: 13, fontWeight: 600, color: t.fg }}>{status}</span>
      </div>
      <div style={{ fontSize: 12, color: "rgb(65,69,82)" }}>{who}</div>
      <div style={{ fontSize: 11, color: "rgb(106,115,131)", marginTop: 2 }}>{when}</div>
    </div>
  );
};

const RelatedTile = ({ icon, label, count, subtitle }) => (
  <button style={{
    padding: "10px 12px", border: "1px solid rgb(239,240,242)", borderRadius: 8, background: "#fff",
    display: "flex", alignItems: "center", gap: 10, cursor: "pointer", fontFamily: "inherit", textAlign: "left",
    transition: "all 120ms"
  }}
  onMouseEnter={e => { e.currentTarget.style.background = "rgb(248,248,251)"; e.currentTarget.style.borderColor = "rgb(213,219,225)"; }}
  onMouseLeave={e => { e.currentTarget.style.background = "#fff"; e.currentTarget.style.borderColor = "rgb(239,240,242)"; }}>
    <div style={{ width: 26, height: 26, borderRadius: 6, background: "rgb(248,248,251)", display: "flex", alignItems: "center", justifyContent: "center", flexShrink: 0 }}>
      <Icon name={icon} size={13} color="rgb(83,74,255)" />
    </div>
    <div style={{ flex: 1, minWidth: 0 }}>
      <div style={{ fontSize: 12, fontWeight: 500, color: "rgb(26,27,37)" }}>{label}</div>
      {subtitle ? (
        <div style={{ fontSize: 11, color: "rgb(106,115,131)" }}>{subtitle}</div>
      ) : (
        <div style={{ fontSize: 11, color: "rgb(106,115,131)" }}>{count} item{count === 1 ? "" : "s"}</div>
      )}
    </div>
    {!subtitle && <span style={{ fontSize: 13, fontWeight: 600, color: "rgb(65,69,82)" }}>{count}</span>}
  </button>
);

window.ChangeOrdersTab = ChangeOrdersTab;
window.FilterPill2Click = FilterPill2Click;
