// Project Detail — full record view with sticky header, summary cards, tabs, AI panel
const ProjectDetail = ({ project, onBack }) => {
  const [tab, setTab] = React.useState("Overview");
  const [aiOpen, setAiOpen] = React.useState(true);
  const [aiPinned, setAiPinned] = React.useState(true);

  const p = project;
  const margin = ((p.contract - p.budgetActual - (p.contract - p.budgetActual) * 0.32) / p.contract * 100).toFixed(1);
  const billed = p.contract * (p.pct / 100) * 0.85;
  const remaining = p.contract - billed;
  const forecast = p.budgetPlan * 1.06;

  const tabs = ["Overview", "Scopes of Work", "WBS / Gantt", "Status Reports", "Tasks", "Budget", "Change Orders", "Billing", "Documents", "ERP Transactions"];
  const tabCounts = { "Tasks": 47, "Change Orders": p.changeOrders, "Documents": 28, "Billing": 6, "ERP Transactions": 142 };

  return (
    <div style={{ display: "grid", gridTemplateColumns: aiOpen ? "1fr 360px" : "1fr 0px", transition: "grid-template-columns 200ms cubic-bezier(.2,.6,.2,1)", minHeight: "calc(100vh - 100px)" }}>
      {/* Main column */}
      <div style={{ minWidth: 0 }}>
        {/* Header */}
        <div style={{ background: "#fff", borderBottom: "1px solid rgb(227,229,232)" }}>
          {/* Breadcrumb */}
          <div style={{ display: "flex", alignItems: "center", gap: 8, padding: "10px 24px 0", fontSize: 12, color: "rgb(106,115,131)" }}>
            <span style={{ display: "inline-flex", alignItems: "center", gap: 4, color: "rgb(83,74,255)", cursor: "pointer", fontWeight: 500 }} onClick={onBack}>
              <Icon name="chevronLeft" size={12} /> Projects
            </span>
            <span>/</span>
            <span>{p.id}</span>
            <span>/</span>
            <span style={{ color: "rgb(26,27,37)" }}>{p.name}</span>
          </div>
          {/* Title row */}
          <div style={{ display: "flex", alignItems: "flex-start", padding: "12px 24px 16px", gap: 16, justifyContent: "space-between" }}>
            <div style={{ display: "flex", gap: 14, alignItems: "center", minWidth: 0 }}>
              <div style={{ width: 48, height: 48, borderRadius: 10, background: p.customerType === "Construction" ? "rgb(255,243,210)" : "rgb(232,233,246)", display: "flex", alignItems: "center", justifyContent: "center" }}>
                <Icon name={p.customerType === "Construction" ? "hardhat" : "layers"} size={24} color={p.customerType === "Construction" ? "rgb(178,121,26)" : "rgb(83,74,255)"} />
              </div>
              <div style={{ minWidth: 0 }}>
                <div style={{ display: "flex", alignItems: "center", gap: 10, flexWrap: "wrap" }}>
                  <h1 style={{ fontSize: 22, fontWeight: 700, margin: 0, letterSpacing: "-.015em" }}>{p.name}</h1>
                  <Chip tone={STATUS_TONES[p.status]} dot>{p.status}</Chip>
                  {p.risk === "high" && <Chip tone="danger" dot>High risk</Chip>}
                </div>
                <div style={{ marginTop: 4, fontSize: 12, color: "rgb(106,115,131)", display: "flex", gap: 12, alignItems: "center" }}>
                  <span>{p.id}</span>
                  <span style={{ width: 3, height: 3, borderRadius: "50%", background: "rgb(163,172,186)" }} />
                  <span style={{ color: "rgb(83,74,255)", cursor: "pointer" }}>{p.customer}</span>
                  <span style={{ width: 3, height: 3, borderRadius: "50%", background: "rgb(163,172,186)" }} />
                  <span>Updated {p.updated}</span>
                </div>
              </div>
            </div>
            {/* Quick actions */}
            <div style={{ display: "flex", gap: 8, alignItems: "center", flexShrink: 0 }}>
              <Button kind="secondary" size="sm" icon="refresh">Add Change Order</Button>
              <Button kind="secondary" size="sm" icon="receipt">Create Invoice</Button>
              <Button kind="secondary" size="sm" icon="check">Add Task</Button>
              <Button kind="secondary" size="sm" icon="upload">Upload</Button>
              <span style={{ width: 1, height: 22, background: "rgb(227,229,232)", margin: "0 2px" }} />
              {!aiOpen && <Button kind="primary" size="sm" icon="sparkles" onClick={() => setAiOpen(true)}>Insights</Button>}
              <IconBtn icon="more" tone="outline" size={28} />
            </div>
          </div>

          {/* Header summary strip */}
          <div style={{ display: "grid", gridTemplateColumns: "repeat(6, 1fr)", padding: "4px 4px 14px", gap: 0 }}>
            <HeaderField label="Project Manager" value={<><Avatar size={20} initials={p.pm.initials} color={p.pm.color} /> {p.pm.name}</>} />
            <HeaderField label="Start Date" value="01/12/2026" />
            <HeaderField label="End Date" value="11/30/2026" />
            <HeaderField label="Contract Value" value={fmtMoneyFull(p.contract)} mono />
            <HeaderField label="Margin" value={`${margin}%`} mono tone={parseFloat(margin) < 15 ? "danger" : "success"} />
            <HeaderField label="Progress" value={
              <div style={{ display: "flex", alignItems: "center", gap: 8, width: "100%" }}>
                <ProgressBar value={p.pct} color={p.status === "At Risk" ? "rgb(192,47,50)" : "rgb(83,74,255)"} height={5} />
                <span style={{ fontSize: 13, fontWeight: 600, fontVariantNumeric: "tabular-nums" }}>{p.pct}%</span>
              </div>
            } stretch last />
          </div>

          {/* Tabs */}
          <div style={{ display: "flex", padding: "0 24px", gap: 2, overflowX: "auto" }}>
            {tabs.map(t => (
              <button key={t} onClick={() => setTab(t)} style={{
                padding: "10px 14px", border: 0, background: "transparent", cursor: "pointer", fontSize: 13, fontWeight: 500,
                color: t === tab ? "rgb(83,74,255)" : "rgb(65,69,82)",
                borderBottom: t === tab ? "2px solid rgb(83,74,255)" : "2px solid transparent", marginBottom: -1,
                whiteSpace: "nowrap", display: "inline-flex", alignItems: "center", gap: 6
              }}>
                {t}
                {tabCounts[t] != null && (
                  <span style={{ fontSize: 11, padding: "1px 6px", borderRadius: 9999, background: t === tab ? "rgb(232,233,246)" : "rgb(241,242,244)", color: t === tab ? "rgb(83,74,255)" : "rgb(106,115,131)", fontWeight: 500 }}>{tabCounts[t]}</span>
                )}
              </button>
            ))}
          </div>
        </div>

        {/* Tab content */}
        <div style={{ padding: 24 }}>
          {tab === "Overview" && <OverviewRouter p={p} margin={margin} billed={billed} remaining={remaining} forecast={forecast} />}
          {tab === "Scopes of Work" && <ScopesOfWorkTab p={p} />}
          {tab === "Budget" && <BudgetTab p={p} />}
          {tab === "Change Orders" && <ChangeOrdersTab p={p} />}
          {tab === "Billing" && <BillingTab p={p} />}
          {tab === "Status Reports" && <StatusReportsTab p={p} />}
          {tab === "Documents" && <DocumentsTab p={p} />}
          {tab === "ERP Transactions" && <ERPTransactionsTab p={p} />}
          {tab === "WBS / Gantt" && <WBSGanttTab p={p} />}
          {tab === "Tasks" && <TasksTab p={p} />}
          {!["Overview","Scopes of Work","Budget","Change Orders","Billing","Status Reports","Documents","ERP Transactions","WBS / Gantt","Tasks"].includes(tab) && <TabPlaceholder tab={tab} />}
        </div>
      </div>

      {/* AI Insights panel */}
      {aiOpen && <AIPanel p={p} onClose={() => setAiOpen(false)} />}
    </div>
  );
};

const HeaderField = ({ label, value, mono, tone, stretch, last }) => (
  <div style={{ display: "flex", flexDirection: "column", gap: 4, padding: "2px 20px", borderRight: last ? "none" : "1px solid rgb(239,240,242)", gridColumn: stretch ? "span 1" : undefined, minWidth: 0 }}>
    <span style={{ fontSize: 11, color: "rgb(106,115,131)", fontWeight: 500, textTransform: "uppercase", letterSpacing: ".04em" }}>{label}</span>
    <span style={{
      fontSize: 13, fontWeight: 500, color: tone ? TONES[tone].fg : "rgb(26,27,37)",
      display: "inline-flex", alignItems: "center", gap: 6,
      fontVariantNumeric: mono ? "tabular-nums" : "normal"
    }}>{value}</span>
  </div>
);

const OverviewRouter = (props) => {
  const { mode } = React.useContext(ViewModeContext);
  return (
    <ModeFader mode={mode}>
      {mode === "simplified" ? <OverviewSimplified {...props} /> : <OverviewTab {...props} />}
    </ModeFader>
  );
};

// Subtle cross-fade + tiny lift whenever the view mode toggles.
// Re-keys on `mode` so React swaps the subtree, and the wrapper's CSS
// animation plays each time.
const ModeFader = ({ mode, children }) => (
  <div key={mode} className="mode-fade">
    {children}
  </div>
);

// =================================================================
// SIMPLIFIED OVERVIEW
// Goal: answer "Is this project OK?" in one glance.
// Strip away dense compliance grids, multi-row stat tables, deep activity feeds.
// Lead with: status hero, the 4 numbers that matter, what's next, what needs you.
// =================================================================
const OverviewSimplified = ({ p, margin, billed, remaining, forecast }) => {
  const variance = p.budgetActual - p.budgetPlan;
  const onTrack = p.status !== "At Risk" && variance <= 0;
  const heroTone = p.status === "At Risk" ? "danger" : variance > 0 ? "warning" : "success";
  const HERO = {
    success: { bg: "linear-gradient(135deg, rgba(218,240,224,.7), rgba(218,240,224,.25))", border: "rgba(34,134,58,.25)", fg: "rgb(20,87,38)", label: "On track" },
    warning: { bg: "linear-gradient(135deg, rgba(255,243,210,.7), rgba(255,243,210,.25))", border: "rgba(178,121,26,.3)",  fg: "rgb(120,80,15)",  label: "Needs attention" },
    danger:  { bg: "linear-gradient(135deg, rgba(252,226,226,.65), rgba(252,226,226,.2))",  border: "rgba(192,47,50,.3)",  fg: "rgb(120,28,30)", label: "At risk" },
  }[heroTone];

  // Things that need the user — pulled from the same signals as the AI panel
  const callouts = [];
  if (variance > 0) callouts.push({ icon: "dollar", title: `Over budget by ${fmtMoney(Math.abs(variance))}`, body: "MEP scope is the largest contributor. Consider creating a CO.", action: "Create CO" });
  if (p.risk === "high") {
    callouts.push({ icon: "shield",  title: "2 lien waivers missing", body: "Apex MEP and Cornerstone Glazing — required before the next pay app.", action: "Request" });
    callouts.push({ icon: "calendar", title: "COI expires in 12 days", body: "Renewal not yet on file. Email renewal reminder?", action: "Send reminder" });
  }
  if (callouts.length === 0) {
    callouts.push({ icon: "check", title: "No outstanding items", body: "All compliance and finance signals are green this week.", action: null, tone: "success" });
  }

  const upcoming = [
    { name: p.nextMilestone, date: p.nextMilestoneDate, days: "in 4 days" },
    { name: "Install Laterals", date: "05/22/2026", days: "in 12 days" },
    { name: "Install Vertical Legs", date: "06/05/2026", days: "in 26 days" },
  ];

  return (
    <div style={{ display: "flex", flexDirection: "column", gap: 20 }}>
      {/* Hero status band */}
      <div style={{
        background: HERO.bg, border: `1px solid ${HERO.border}`, borderRadius: 14,
        padding: "20px 22px", display: "flex", alignItems: "center", gap: 24
      }}>
        <div style={{ flex: 1, minWidth: 0 }}>
          <div style={{ display: "flex", alignItems: "center", gap: 8, marginBottom: 6 }}>
            <span style={{ width: 8, height: 8, borderRadius: "50%", background: HERO.fg }} />
            <span style={{ fontSize: 11, fontWeight: 700, textTransform: "uppercase", letterSpacing: ".05em", color: HERO.fg }}>
              {HERO.label}
            </span>
          </div>
          <div style={{ fontSize: 22, fontWeight: 700, letterSpacing: "-.015em", lineHeight: 1.2, color: "rgb(26,27,37)" }}>
            {heroTone === "success" && `${p.name} is on schedule and within budget.`}
            {heroTone === "warning" && `${p.name} is ${Math.round(Math.abs(variance) / p.budgetPlan * 100)}% over plan but still recoverable.`}
            {heroTone === "danger"  && `${p.name} needs attention — schedule and budget are slipping.`}
          </div>
          <div style={{ fontSize: 13, color: "rgb(65,69,82)", marginTop: 6, lineHeight: 1.5 }}>
            {p.pct}% complete · {p.pm.name} is leading · last updated {p.updated}.
            {!onTrack && " Review the items below before the next billing cycle."}
          </div>
        </div>
        {/* Big circular progress */}
        <RingProgress pct={p.pct} accent={heroTone === "danger" ? "rgb(192,47,50)" : "rgb(83,74,255)"} />
      </div>

      {/* The 4 numbers that matter */}
      <div style={{ display: "grid", gridTemplateColumns: "repeat(4, 1fr)", gap: 12 }}>
        <BigStat label="Contract" value={fmtMoney(p.contract)} sub={`${p.changeOrders} change orders applied`} />
        <BigStat label="Spent" value={fmtMoney(p.budgetActual)} sub={`of ${fmtMoney(p.budgetPlan)} budget`}
          tone={variance > 0 ? "danger" : "neutral"}
          progress={Math.min(100, p.budgetActual / p.budgetPlan * 100)} />
        <BigStat label="Billed" value={fmtMoney(billed)} sub={`${fmtMoney(remaining)} left to bill`} />
        <BigStat label="Margin" value={`${margin}%`} sub={parseFloat(margin) >= 18 ? "Healthy" : parseFloat(margin) >= 12 ? "Watch" : "Below target"}
          tone={parseFloat(margin) >= 18 ? "success" : parseFloat(margin) >= 12 ? "warning" : "danger"} />
      </div>

      {/* Two columns: Needs attention + What's next */}
      <div style={{ display: "grid", gridTemplateColumns: "1.4fr 1fr", gap: 16 }}>
        {/* Needs your attention */}
        <Card title="Needs your attention" padding={0}>
          <div>
            {callouts.map((c, i) => (
              <div key={i} style={{
                display: "flex", gap: 14, padding: "16px",
                borderBottom: i < callouts.length - 1 ? "1px solid rgb(239,240,242)" : "none",
                alignItems: "flex-start"
              }}>
                <div style={{
                  width: 34, height: 34, borderRadius: 9, flexShrink: 0,
                  background: c.tone === "success" ? "rgb(218,240,224)" : "rgb(252,226,226)",
                  display: "flex", alignItems: "center", justifyContent: "center"
                }}>
                  <Icon name={c.icon} size={16} color={c.tone === "success" ? "rgb(34,134,58)" : "rgb(192,47,50)"} />
                </div>
                <div style={{ flex: 1, minWidth: 0 }}>
                  <div style={{ fontSize: 14, fontWeight: 600, color: "rgb(26,27,37)" }}>{c.title}</div>
                  <div style={{ fontSize: 13, color: "rgb(106,115,131)", marginTop: 3, lineHeight: 1.5 }}>{c.body}</div>
                </div>
                {c.action && <Button kind="secondary" size="sm">{c.action}</Button>}
              </div>
            ))}
          </div>
        </Card>

        {/* What's next */}
        <Card title="What's next" padding={0}>
          <div>
            {upcoming.map((m, i) => (
              <div key={i} style={{
                display: "flex", gap: 12, padding: "14px 16px", alignItems: "center",
                borderBottom: i < upcoming.length - 1 ? "1px solid rgb(239,240,242)" : "none"
              }}>
                <div style={{
                  width: 40, height: 44, borderRadius: 8, flexShrink: 0,
                  border: "1px solid rgb(239,240,242)", background: "rgb(252,252,253)",
                  display: "flex", flexDirection: "column", alignItems: "center", justifyContent: "center"
                }}>
                  <span style={{ fontSize: 9, fontWeight: 600, color: "rgb(106,115,131)", textTransform: "uppercase", letterSpacing: ".04em" }}>
                    {m.date.slice(0,2) === "01" ? "Jan" : m.date.slice(0,2) === "02" ? "Feb" : m.date.slice(0,2) === "03" ? "Mar" :
                     m.date.slice(0,2) === "04" ? "Apr" : m.date.slice(0,2) === "05" ? "May" : m.date.slice(0,2) === "06" ? "Jun" :
                     m.date.slice(0,2) === "07" ? "Jul" : m.date.slice(0,2) === "08" ? "Aug" : m.date.slice(0,2) === "09" ? "Sep" :
                     m.date.slice(0,2) === "10" ? "Oct" : m.date.slice(0,2) === "11" ? "Nov" : "Dec"}
                  </span>
                  <span style={{ fontSize: 16, fontWeight: 700, color: "rgb(26,27,37)", fontVariantNumeric: "tabular-nums", lineHeight: 1 }}>
                    {parseInt(m.date.slice(3,5), 10)}
                  </span>
                </div>
                <div style={{ flex: 1, minWidth: 0 }}>
                  <div style={{ fontSize: 14, fontWeight: 500, color: "rgb(26,27,37)" }}>{m.name}</div>
                  <div style={{ fontSize: 12, color: "rgb(106,115,131)", marginTop: 2 }}>{m.days}</div>
                </div>
              </div>
            ))}
          </div>
        </Card>
      </div>

      {/* Today on site — single condensed daily report */}
      <Card title="Latest from the field" action={<Button kind="ghost" size="sm" iconRight="chevronRight">All reports</Button>} padding={0}>
        <div style={{ padding: "16px" }}>
          <div style={{ display: "flex", alignItems: "center", gap: 10, marginBottom: 10 }}>
            <Avatar size={26} initials="RF" color="#76ADFF" />
            <div style={{ flex: 1 }}>
              <div style={{ fontSize: 13, fontWeight: 600 }}>Robert Fox · Site Lead</div>
              <div style={{ fontSize: 11, color: "rgb(106,115,131)" }}>Today · Clear, 68°F · Crew of 18</div>
            </div>
          </div>
          <div style={{ fontSize: 14, color: "rgb(26,27,37)", lineHeight: 1.6 }}>
            Steel erection on north tower 92% complete. Concrete pour for level 6 deck completed by 3pm — 240 cy placed. No safety incidents.
          </div>
        </div>
      </Card>

      {/* Tab cross-links — gentle nudge to deeper detail */}
      <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", padding: "12px 16px",
                    background: "#fff", border: "1px solid rgb(231,233,236)", borderRadius: 12 }}>
        <div style={{ display: "flex", alignItems: "center", gap: 10 }}>
          <Icon name="layers" size={14} color="rgb(106,115,131)" />
          <span style={{ fontSize: 13, color: "rgb(65,69,82)" }}>
            Need more detail? Switch to <strong style={{ color: "rgb(26,27,37)" }}>Detailed</strong> mode for compliance, full activity, and breakdowns.
          </span>
        </div>
      </div>
    </div>
  );
};

const BigStat = ({ label, value, sub, tone, progress }) => {
  const toneColor = tone === "danger" ? "rgb(192,47,50)" : tone === "warning" ? "rgb(178,121,26)" : tone === "success" ? "rgb(34,134,58)" : "rgb(26,27,37)";
  return (
    <div style={{
      background: "#fff", border: "1px solid rgb(231,233,236)", borderRadius: 12,
      padding: "16px 18px", display: "flex", flexDirection: "column", gap: 4
    }}>
      <span style={{ fontSize: 11, color: "rgb(106,115,131)", fontWeight: 600, textTransform: "uppercase", letterSpacing: ".05em" }}>{label}</span>
      <span style={{ fontSize: 26, fontWeight: 700, letterSpacing: "-.02em", fontVariantNumeric: "tabular-nums", color: toneColor, lineHeight: 1.1, marginTop: 2 }}>{value}</span>
      <span style={{ fontSize: 12, color: "rgb(106,115,131)" }}>{sub}</span>
      {progress != null && (
        <div style={{ marginTop: 6 }}>
          <ProgressBar value={progress} max={100} color={toneColor} height={4} />
        </div>
      )}
    </div>
  );
};

const RingProgress = ({ pct, accent = "rgb(83,74,255)", size = 96 }) => {
  const r = (size - 10) / 2;
  const c = 2 * Math.PI * r;
  const offset = c - (pct / 100) * c;
  return (
    <div style={{ position: "relative", width: size, height: size, flexShrink: 0 }}>
      <svg width={size} height={size}>
        <circle cx={size/2} cy={size/2} r={r} fill="none" stroke="rgba(15,23,42,.08)" strokeWidth={6} />
        <circle cx={size/2} cy={size/2} r={r} fill="none" stroke={accent} strokeWidth={6}
          strokeDasharray={c} strokeDashoffset={offset} strokeLinecap="round"
          transform={`rotate(-90 ${size/2} ${size/2})`} style={{ transition: "stroke-dashoffset 400ms" }} />
      </svg>
      <div style={{ position: "absolute", inset: 0, display: "flex", flexDirection: "column", alignItems: "center", justifyContent: "center" }}>
        <span style={{ fontSize: 22, fontWeight: 700, letterSpacing: "-.02em", lineHeight: 1, fontVariantNumeric: "tabular-nums" }}>{pct}%</span>
        <span style={{ fontSize: 10, color: "rgb(106,115,131)", fontWeight: 500, marginTop: 2, textTransform: "uppercase", letterSpacing: ".05em" }}>Complete</span>
      </div>
    </div>
  );
};

const OverviewTab = ({ p, margin, billed, remaining, forecast }) => {
  const variance = p.budgetActual - p.budgetPlan;
  return (
    <div style={{ display: "flex", flexDirection: "column", gap: 20 }}>
      {/* Summary cards row */}
      <div style={{ display: "grid", gridTemplateColumns: "1.4fr 1fr 1fr 1fr 0.8fr", gap: 12 }}>
        {/* Financial Health */}
        <Card>
          <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", marginBottom: 12 }}>
            <div style={{ display: "flex", alignItems: "center", gap: 8 }}>
              <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 Health</span>
            </div>
            <Chip tone={parseFloat(margin) < 15 ? "danger" : parseFloat(margin) < 22 ? "warning" : "success"} dot>{margin}% margin</Chip>
          </div>
          <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 10 }}>
            <Stat label="Original Budget" value={fmtMoney(p.budgetPlan || p.contract * 0.78)} />
            <Stat label="Revised Budget" value={fmtMoney((p.budgetPlan || p.contract * 0.78) * 1.04)} />
            <Stat label="Forecast" value={fmtMoney(forecast)} tone={forecast > p.budgetPlan ? "warning" : "neutral"} />
            <Stat label="Actual Cost" value={fmtMoney(p.budgetActual)} />
            <Stat label="Remaining" value={fmtMoney(Math.max(0, p.budgetPlan - p.budgetActual))} />
            <Stat label="Variance" value={`${variance >= 0 ? "+" : "−"}${fmtMoney(Math.abs(variance))}`} tone={variance > 0 ? "danger" : "success"} />
          </div>
          <div style={{ marginTop: 12, paddingTop: 12, borderTop: "1px solid rgb(239,240,242)" }}>
            <div style={{ display: "flex", justifyContent: "space-between", fontSize: 11, color: "rgb(106,115,131)", marginBottom: 4 }}>
              <span>Spent {fmtMoney(p.budgetActual)}</span>
              <span>Budget {fmtMoney(p.budgetPlan)}</span>
            </div>
            <ProgressBar value={p.budgetActual} max={Math.max(p.budgetPlan, p.budgetActual) * 1.1} color={TONES[p.budgetTone].fg} height={6} />
          </div>
        </Card>

        {/* Progress */}
        <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="activity" size={13} color="rgb(83,74,255)" />
            </div>
            <span style={{ fontSize: 13, fontWeight: 600 }}>Progress</span>
          </div>
          <div style={{ fontSize: 28, fontWeight: 700, letterSpacing: "-.02em", lineHeight: 1, fontVariantNumeric: "tabular-nums" }}>{p.pct}%</div>
          <div style={{ fontSize: 12, color: "rgb(106,115,131)", marginTop: 2, marginBottom: 12 }}>Project complete</div>
          <ProgressBar value={p.pct} color={p.status === "At Risk" ? "rgb(192,47,50)" : "rgb(83,74,255)"} height={5} />
          <div style={{ marginTop: 14, display: "grid", gridTemplateColumns: "1fr 1fr", gap: 10 }}>
            <Stat label="Tasks" value="32 / 47" />
            <Stat label="Milestones" value="5 / 9" />
          </div>
        </Card>

        {/* Billing */}
        <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="receipt" size={13} color="rgb(83,74,255)" />
            </div>
            <span style={{ fontSize: 13, fontWeight: 600 }}>Billing</span>
          </div>
          <div style={{ display: "flex", flexDirection: "column", gap: 10 }}>
            <Stat label="Billed to Date" value={fmtMoney(billed)} />
            <Stat label="Remaining to Bill" value={fmtMoney(remaining)} />
            <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center" }}>
              <span style={{ fontSize: 11, color: "rgb(106,115,131)", fontWeight: 500 }}>Status</span>
              <Chip tone={BILLING_TONES[p.billing]}>{p.billing}</Chip>
            </div>
            <div style={{ borderTop: "1px solid rgb(239,240,242)", paddingTop: 8 }}>
              <div style={{ fontSize: 11, color: "rgb(106,115,131)", fontWeight: 500, marginBottom: 4 }}>Next Billing</div>
              <div style={{ fontSize: 13, fontWeight: 500 }}>Progress draw 4</div>
              <div style={{ fontSize: 11, color: "rgb(106,115,131)", marginTop: 2 }}>Est. {fmtMoney(p.contract * 0.12)} on 05/15</div>
            </div>
          </div>
        </Card>

        {/* Change Orders */}
        <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="refresh" size={13} color="rgb(83,74,255)" />
            </div>
            <span style={{ fontSize: 13, fontWeight: 600 }}>Change Orders</span>
          </div>
          <div style={{ display: "flex", flexDirection: "column", gap: 10 }}>
            <div style={{ padding: 10, background: "rgb(218,240,224)", borderRadius: 8 }}>
              <div style={{ fontSize: 11, color: "rgb(34,134,58)", fontWeight: 500 }}>Approved</div>
              <div style={{ fontSize: 18, fontWeight: 700, letterSpacing: "-.01em", color: "rgb(34,134,58)", fontVariantNumeric: "tabular-nums" }}>{fmtMoney(p.coValue * 0.65)}</div>
              <div style={{ fontSize: 11, color: "rgb(34,134,58)", opacity: 0.8 }}>{Math.max(1, Math.floor(p.changeOrders * 0.6))} orders</div>
            </div>
            <div style={{ padding: 10, background: "rgb(255,243,210)", borderRadius: 8 }}>
              <div style={{ fontSize: 11, color: "rgb(178,121,26)", fontWeight: 500 }}>Pending</div>
              <div style={{ fontSize: 18, fontWeight: 700, letterSpacing: "-.01em", color: "rgb(178,121,26)", fontVariantNumeric: "tabular-nums" }}>{fmtMoney(p.coValue * 0.35)}</div>
              <div style={{ fontSize: 11, color: "rgb(178,121,26)", opacity: 0.8 }}>{Math.max(0, p.changeOrders - Math.floor(p.changeOrders * 0.6))} orders</div>
            </div>
          </div>
        </Card>

        {/* Compliance */}
        <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="shield" size={13} color="rgb(83,74,255)" />
            </div>
            <span style={{ fontSize: 13, fontWeight: 600 }}>Compliance</span>
          </div>
          <div style={{ display: "flex", flexDirection: "column", gap: 8 }}>
            <ComplianceRow label="COI" status={p.risk === "high" ? "warning" : "ok"} text={p.risk === "high" ? "Expires in 12d" : "Compliant"} />
            <ComplianceRow label="W-9" status="ok" text="On file" />
            <ComplianceRow label="Lien Waivers" status={p.risk === "high" ? "danger" : "ok"} text={p.risk === "high" ? "2 missing" : "Current"} />
            <ComplianceRow label="Safety Plan" status="ok" text="Approved" />
            <ComplianceRow label="FEOC" status={p.risk === "high" ? "warning" : "ok"} text={p.risk === "high" ? "Attestation pending" : "Compliant"} />
            <ComplianceRow label="Certified Payroll" status={p.risk === "high" ? "danger" : "ok"} text={p.risk === "high" ? "3 reports overdue" : "Up to date"} />
          </div>
        </Card>
      </div>

      {/* Activity + Milestones row */}
      <div style={{ display: "grid", gridTemplateColumns: "1.5fr 1fr", gap: 16 }}>
        <ActivityFeed p={p} />
        <UpcomingMilestones p={p} />
      </div>

      {/* Daily summaries */}
      <DailySummaries p={p} />
    </div>
  );
};

const Stat = ({ label, value, tone }) => (
  <div style={{ display: "flex", flexDirection: "column", gap: 2 }}>
    <span style={{ fontSize: 11, color: "rgb(106,115,131)", fontWeight: 500 }}>{label}</span>
    <span style={{ fontSize: 14, fontWeight: 600, color: tone ? TONES[tone].fg : "rgb(26,27,37)", fontVariantNumeric: "tabular-nums", letterSpacing: "-.005em" }}>{value}</span>
  </div>
);

const ComplianceRow = ({ label, status, text }) => {
  const tones = { ok: "success", warning: "warning", danger: "danger" };
  return (
    <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", padding: "4px 0" }}>
      <span style={{ fontSize: 12, color: "rgb(65,69,82)", fontWeight: 500 }}>{label}</span>
      <span style={{ display: "inline-flex", alignItems: "center", gap: 5, fontSize: 12, color: TONES[tones[status]].fg }}>
        <span style={{ width: 6, height: 6, borderRadius: "50%", background: TONES[tones[status]].fg }} />
        {text}
      </span>
    </div>
  );
};

const ActivityFeed = ({ p }) => {
  const items = [
    { who: p.pm, when: "2h ago", title: "Submitted", target: "Daily Progress Report", icon: "check", tone: "success" },
    { who: { initials: "EC", name: "Emma Connor", color: "#22863A" }, when: "4h ago", title: "Submitted", target: `Change Order #${p.changeOrders + 1} for $42,800`, icon: "refresh", tone: "warning" },
    { who: { initials: "JL", name: "Jordan Lin", color: "#FF9143" }, when: "Yesterday", title: "Uploaded", target: "Inspection Report — 04/29", icon: "upload", tone: "info" },
    { who: { initials: "RF", name: "Robert Fox", color: "#76ADFF" }, when: "Yesterday", title: "Completed", target: "Task: Steel beam delivery sign-off", icon: "check", tone: "success" },
    { who: { initials: "NM", name: "Nick Merley", color: "#B279FF" }, when: "2d ago", title: "Invoiced", target: `Progress Draw #3 — ${fmtMoney(p.contract * 0.18)}`, icon: "receipt", tone: "purple" },
  ];
  return (
    <Card title="Recent Activity" action={<Button kind="ghost" size="sm" iconRight="chevronRight">View all</Button>} padding={0}>
      <div style={{ padding: "8px 0" }}>
        {items.map((it, i) => (
          <div key={i} style={{ display: "flex", gap: 12, padding: "10px 16px", alignItems: "flex-start", borderBottom: i < items.length - 1 ? "1px solid rgb(239,240,242)" : "none" }}>
            <Avatar size={26} initials={it.who.initials} color={it.who.color} />
            <div style={{ flex: 1, minWidth: 0 }}>
              <div style={{ fontSize: 13 }}>
                <span style={{ fontWeight: 500 }}>{it.who.name}</span>
                <span style={{ color: "rgb(106,115,131)" }}> {it.title.toLowerCase()} </span>
                <span style={{ color: "rgb(26,27,37)" }}>{it.target}</span>
              </div>
              <div style={{ fontSize: 11, color: "rgb(106,115,131)", marginTop: 2, display: "flex", alignItems: "center", gap: 6 }}>
                <Icon name={it.icon} size={11} color={TONES[it.tone].fg} />
                <span>{it.when}</span>
              </div>
            </div>
          </div>
        ))}
      </div>
    </Card>
  );
};

const UpcomingMilestones = ({ p }) => {
  const ms = [
    { name: p.nextMilestone, date: p.nextMilestoneDate, status: "upcoming", days: "in 4 days" },
    { name: "Install Laterals", date: "05/22/2026", status: "upcoming", days: "in 12 days" },
    { name: "Install Vertical Legs", date: "06/05/2026", status: "upcoming", days: "in 26 days" },
    { name: "Screws Installed", date: "04/18/2026", status: "done", days: "Completed" },
    { name: "Permits issued", date: "03/02/2026", status: "done", days: "Completed" },
  ];
  return (
    <Card title="Milestones" action={<Button kind="ghost" size="sm" icon="plus">Add</Button>} padding={0}>
      <div style={{ padding: "8px 0" }}>
        {ms.map((m, i) => (
          <div key={i} style={{ display: "flex", gap: 12, padding: "10px 16px", alignItems: "center", borderBottom: i < ms.length - 1 ? "1px solid rgb(239,240,242)" : "none" }}>
            <div style={{
              width: 22, height: 22, borderRadius: "50%",
              background: m.status === "done" ? "rgb(34,134,58)" : "#fff",
              border: m.status === "done" ? "0" : "1.5px solid rgb(213,219,225)",
              display: "flex", alignItems: "center", justifyContent: "center", flexShrink: 0
            }}>
              {m.status === "done" && <Icon name="check" size={12} color="#fff" />}
            </div>
            <div style={{ flex: 1, minWidth: 0 }}>
              <div style={{ fontSize: 13, fontWeight: 500, color: m.status === "done" ? "rgb(106,115,131)" : "rgb(26,27,37)", textDecoration: m.status === "done" ? "line-through" : "none" }}>{m.name}</div>
              <div style={{ fontSize: 11, color: "rgb(106,115,131)", marginTop: 2, fontVariantNumeric: "tabular-nums" }}>{m.date} · {m.days}</div>
            </div>
          </div>
        ))}
      </div>
    </Card>
  );
};

const DailySummaries = ({ p }) => {
  const summaries = [
    { date: "04/29/2026", weather: "Clear, 68°F", crew: 18, text: "Steel erection on north tower 92% complete. Concrete pour for level 6 deck completed by 3pm — 240 cy placed. No safety incidents.", author: "RF" },
    { date: "04/28/2026", weather: "Light rain, 61°F", crew: 14, text: "Rain delayed exterior work 2 hours. MEP roughs-ins continued on levels 3-4. Inspection scheduled for Thursday confirmed.", author: "RF" },
    { date: "04/27/2026", weather: "Clear, 72°F", crew: 22, text: "Full crew on site. Drywall hangers completed level 2 common areas. Window install starting Tuesday pending shipment.", author: "RF" },
  ];
  return (
    <Card title="Daily Status Summaries" action={<Button kind="ghost" size="sm" iconRight="chevronRight">All reports</Button>} padding={0}>
      <div>
        {summaries.map((s, i) => (
          <div key={i} style={{ padding: "12px 16px", borderBottom: i < summaries.length - 1 ? "1px solid rgb(239,240,242)" : "none" }}>
            <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", marginBottom: 6 }}>
              <div style={{ display: "flex", alignItems: "center", gap: 10 }}>
                <span style={{ fontSize: 13, fontWeight: 600, fontVariantNumeric: "tabular-nums" }}>{s.date}</span>
                <Chip tone="neutral">{s.weather}</Chip>
                <Chip tone="info">Crew: {s.crew}</Chip>
              </div>
              <Avatar size={22} initials={s.author} color="#76ADFF" />
            </div>
            <div style={{ fontSize: 13, color: "rgb(65,69,82)", lineHeight: 1.5 }}>{s.text}</div>
          </div>
        ))}
      </div>
    </Card>
  );
};

const TabPlaceholder = ({ tab }) => (
  <div style={{ background: "#fff", border: "1px solid rgb(227,229,232)", borderRadius: 12, padding: "60px 24px", display: "flex", flexDirection: "column", alignItems: "center", gap: 12 }}>
    <div style={{ width: 64, height: 64, borderRadius: "50%", background: "rgba(178,172,255,.4)", display: "flex", alignItems: "center", justifyContent: "center" }}>
      <Icon name="layers" size={28} color="rgb(83,74,255)" />
    </div>
    <div style={{ fontSize: 18, fontWeight: 600 }}>{tab}</div>
    <div style={{ fontSize: 13, color: "rgb(106,115,131)", textAlign: "center", maxWidth: 360 }}>This tab is part of the central project workspace. Switch back to Overview to see the full dashboard layout.</div>
    <Button kind="primary" icon="plus" size="sm">New {tab.split(" ")[0]} item</Button>
  </div>
);

const AIPanel = ({ p, onClose }) => (
  <div style={{
    background: "#fff",
    borderLeft: "1px solid rgb(227,229,232)",
    display: "flex", flexDirection: "column",
    height: "calc(100vh - 100px)",
    position: "sticky", top: 0,
    overflowY: "auto"
  }}>
    {/* Panel header */}
    <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", padding: "14px 16px", borderBottom: "1px solid rgb(239,240,242)", position: "sticky", top: 0, background: "#fff", zIndex: 1 }}>
      <div style={{ display: "flex", alignItems: "center", gap: 8 }}>
        <div style={{ width: 26, height: 26, borderRadius: 6, background: "linear-gradient(135deg, rgba(123,200,255,.25), rgba(83,74,255,.18))", display: "flex", alignItems: "center", justifyContent: "center" }}>
          <Icon name="sparkles" size={14} color="rgb(83,74,255)" />
        </div>
        <div>
          <div style={{ fontSize: 13, fontWeight: 600 }}>AI Insights</div>
          <div style={{ fontSize: 11, color: "rgb(106,115,131)" }}>Updated 4 min ago</div>
        </div>
      </div>
      <IconBtn icon="cross" size={28} onClick={onClose} />
    </div>

    {/* Health summary */}
    <div style={{ padding: "16px", borderBottom: "1px solid rgb(239,240,242)" }}>
      <div style={{ fontSize: 11, color: "rgb(106,115,131)", fontWeight: 500, textTransform: "uppercase", letterSpacing: ".04em", marginBottom: 8 }}>Project Health</div>
      <div style={{ padding: 12, borderRadius: 10, background: p.risk === "high" ? "rgba(252,226,226,.5)" : "rgb(248,248,251)", border: `1px solid ${p.risk === "high" ? "rgba(192,47,50,.2)" : "rgb(239,240,242)"}` }}>
        <div style={{ display: "flex", alignItems: "center", gap: 6, marginBottom: 6 }}>
          <Chip tone={p.risk === "high" ? "danger" : "warning"} dot>{p.risk === "high" ? "At Risk" : "Watch"}</Chip>
          <span style={{ fontSize: 12, color: "rgb(106,115,131)", fontVariantNumeric: "tabular-nums" }}>Score: {p.risk === "high" ? "62" : "78"}/100</span>
        </div>
        <div style={{ fontSize: 13, lineHeight: 1.5, color: "rgb(26,27,37)" }}>
          {p.risk === "high"
            ? `Cost variance at +12% vs plan, driven by scope expansion in MEP and 5 pending change orders worth ${fmtMoney(p.coValue)}. Schedule slip of 6 days projected unless steel topping out lands by 05/14.`
            : `Tracking on schedule. ${fmtMoney(p.coValue)} in change orders pending review — a quick approval will unlock ${fmtMoney(p.contract * 0.12)} in next billing draw.`}
        </div>
      </div>
    </div>

    {/* Risk alerts */}
    {p.risk === "high" && (
      <div style={{ padding: "16px", borderBottom: "1px solid rgb(239,240,242)" }}>
        <div style={{ fontSize: 11, color: "rgb(106,115,131)", fontWeight: 500, textTransform: "uppercase", letterSpacing: ".04em", marginBottom: 8 }}>Active Alerts</div>
        <div style={{ display: "flex", flexDirection: "column", gap: 8 }}>
          <AlertCard tone="danger" icon="dollar" title="Budget over by 12%" body={`Actuals exceed plan by ${fmtMoney(Math.abs(p.budgetActual - p.budgetPlan))}. MEP scope is the largest contributor.`} />
          <AlertCard tone="warning" icon="calendar" title="Schedule risk: 6-day slip" body="Steel delivery delayed; topping-out milestone at risk for 05/14." />
        </div>
      </div>
    )}

    {/* Suggested actions */}
    <div style={{ padding: "16px", borderBottom: "1px solid rgb(239,240,242)" }}>
      <div style={{ fontSize: 11, color: "rgb(106,115,131)", fontWeight: 500, textTransform: "uppercase", letterSpacing: ".04em", marginBottom: 8 }}>Suggested Actions</div>
      <div style={{ display: "flex", flexDirection: "column", gap: 6 }}>
        <SuggestionRow icon="refresh" title="Create Change Order" body={`Cover ${fmtMoney(Math.abs(p.budgetActual - p.budgetPlan))} of unbilled MEP scope`} />
        <SuggestionRow icon="receipt" title="Invoice Ready Work" body={`${fmtMoney(p.contract * 0.12)} in completed milestones eligible to bill`} />
        <SuggestionRow icon="alert" title="Review Over-Budget Scope" body="3 line items running >15% over plan" />
      </div>
    </div>

    {/* Daily report */}
    <div style={{ padding: "16px", borderBottom: "1px solid rgb(239,240,242)" }}>
      <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", marginBottom: 8 }}>
        <div style={{ fontSize: 11, color: "rgb(106,115,131)", fontWeight: 500, textTransform: "uppercase", letterSpacing: ".04em" }}>Daily Report Summary</div>
        <span style={{ fontSize: 11, color: "rgb(106,115,131)" }}>04/29</span>
      </div>
      <div style={{ fontSize: 13, lineHeight: 1.5, color: "rgb(65,69,82)" }}>
        Steel erection on north tower at 92%. Concrete pour completed for level 6. Crew of 18 on site, no safety incidents. Window shipment confirmed for Tuesday 5/5.
      </div>
    </div>

    {/* Documents alert */}
    <div style={{ padding: "16px" }}>
      <div style={{ fontSize: 11, color: "rgb(106,115,131)", fontWeight: 500, textTransform: "uppercase", letterSpacing: ".04em", marginBottom: 8 }}>Document Alerts</div>
      <div style={{ display: "flex", flexDirection: "column", gap: 8 }}>
        <DocAlert tone="danger" title="2 lien waivers missing" body="Subs: Apex MEP, Cornerstone Glazing" />
        <DocAlert tone="warning" title="COI expires in 12 days" body="Cedar Heights Holdings — renewal needed" />
      </div>
    </div>
  </div>
);

const AlertCard = ({ tone, icon, title, body }) => (
  <div style={{ padding: 10, borderRadius: 8, background: TONES[tone].bg, border: `1px solid ${TONES[tone].fg}22` }}>
    <div style={{ display: "flex", alignItems: "center", gap: 6, marginBottom: 4 }}>
      <Icon name={icon} size={13} color={TONES[tone].fg} />
      <span style={{ fontSize: 12, fontWeight: 600, color: TONES[tone].fg }}>{title}</span>
    </div>
    <div style={{ fontSize: 12, color: "rgb(65,69,82)", lineHeight: 1.4 }}>{body}</div>
  </div>
);

const SuggestionRow = ({ icon, title, body }) => (
  <button style={{
    display: "flex", gap: 10, padding: "10px 12px", border: "1px solid rgb(239,240,242)", borderRadius: 8,
    background: "#fff", cursor: "pointer", textAlign: "left", fontFamily: "inherit", alignItems: "flex-start",
    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: 28, height: 28, borderRadius: 6, background: "rgb(232,233,246)", display: "flex", alignItems: "center", justifyContent: "center", flexShrink: 0 }}>
      <Icon name={icon} size={14} color="rgb(83,74,255)" />
    </div>
    <div style={{ flex: 1, minWidth: 0 }}>
      <div style={{ fontSize: 13, fontWeight: 500, color: "rgb(26,27,37)" }}>{title}</div>
      <div style={{ fontSize: 12, color: "rgb(106,115,131)", marginTop: 2, lineHeight: 1.4 }}>{body}</div>
    </div>
    <Icon name="chevronRight" size={14} color="rgb(163,172,186)" style={{ marginTop: 6 }} />
  </button>
);

const DocAlert = ({ tone, title, body }) => (
  <div style={{ display: "flex", gap: 8, padding: "8px 10px", borderRadius: 8, background: TONES[tone].bg }}>
    <Icon name="alertCircle" size={14} color={TONES[tone].fg} style={{ marginTop: 2, flexShrink: 0 }} />
    <div style={{ flex: 1 }}>
      <div style={{ fontSize: 12, fontWeight: 600, color: TONES[tone].fg }}>{title}</div>
      <div style={{ fontSize: 11, color: "rgb(65,69,82)", marginTop: 1 }}>{body}</div>
    </div>
  </div>
);

window.ProjectDetail = ProjectDetail;
