// Status Reports tab — daily reporting compliance, calendar heatmap, AI insights

const REPORTS = [
  { date: "2026-04-30", weekday: "Thu", title: "Daily Report — Apr 30", by: { initials: "EC", name: "Emma Connor", color: "#22863A" }, time: "5:42 PM", expected: "5:00 PM", status: "Late",   ai: "Risk Identified",  summary: "East tracker delivery slipped 2 days. Field crew rotated to predrill; no labor idle." },
  { date: "2026-04-29", weekday: "Wed", title: "Daily Report — Apr 29", by: { initials: "EC", name: "Emma Connor", color: "#22863A" }, time: "4:18 PM", expected: "5:00 PM", status: "OnTime", ai: "Key Update",        summary: "Pile driving 78% complete. Predrill crew at full pace. SCADA gateway delivered to site." },
  { date: "2026-04-28", weekday: "Tue", title: "Daily Report — Apr 28", by: { initials: "RF", name: "Robert Fox",   color: "#76ADFF" }, time: "4:55 PM", expected: "5:00 PM", status: "OnTime", ai: null,                summary: "Routine progress on racking and electrical. No safety incidents." },
  { date: "2026-04-27", weekday: "Mon", title: "Daily Report — Apr 27", by: { initials: "RF", name: "Robert Fox",   color: "#76ADFF" }, time: null,       expected: "5:00 PM", status: "Missed", ai: null,                summary: null },
  { date: "2026-04-24", weekday: "Fri", title: "Daily Report — Apr 24", by: { initials: "EC", name: "Emma Connor", color: "#22863A" }, time: "5:08 PM", expected: "5:00 PM", status: "Late",   ai: "Delay Noted",       summary: "Owner walkthrough delayed pile-driving start by 90 min. Caught up by EOD." },
  { date: "2026-04-23", weekday: "Thu", title: "Daily Report — Apr 23", by: { initials: "JL", name: "Jordan Lin",   color: "#FF9143" }, time: "4:32 PM", expected: "5:00 PM", status: "OnTime", ai: "Key Update",        summary: "Racking complete on north section. Module deliveries arriving on schedule." },
  { date: "2026-04-22", weekday: "Wed", title: "Daily Report — Apr 22", by: { initials: "EC", name: "Emma Connor", color: "#22863A" }, time: "4:51 PM", expected: "5:00 PM", status: "OnTime", ai: null,                summary: "Standard progress. Crew of 28 on site. Weather clear." },
  { date: "2026-04-21", weekday: "Tue", title: "Daily Report — Apr 21", by: { initials: "EC", name: "Emma Connor", color: "#22863A" }, time: "5:34 PM", expected: "5:00 PM", status: "Late",   ai: null,                summary: "Pile-driving rig 2 down 3 hours for hydraulic repair. Repair completed." },
  { date: "2026-04-20", weekday: "Mon", title: "Daily Report — Apr 20", by: { initials: "RF", name: "Robert Fox",   color: "#76ADFF" }, time: "4:45 PM", expected: "5:00 PM", status: "OnTime", ai: null,                summary: "Week kickoff. Torque-tube delivery received and staged." },
  { date: "2026-04-17", weekday: "Fri", title: "Daily Report — Apr 17", by: { initials: "EC", name: "Emma Connor", color: "#22863A" }, time: "4:28 PM", expected: "5:00 PM", status: "OnTime", ai: "Risk Identified",   summary: "Geotech flagged refusal in north section. CO-013 drafted for predrill." },
  { date: "2026-04-16", weekday: "Thu", title: "Daily Report — Apr 16", by: { initials: "EC", name: "Emma Connor", color: "#22863A" }, time: null,       expected: "5:00 PM", status: "Missed", ai: null,                summary: null },
  { date: "2026-04-15", weekday: "Wed", title: "Daily Report — Apr 15", by: { initials: "JL", name: "Jordan Lin",   color: "#FF9143" }, time: "4:42 PM", expected: "5:00 PM", status: "OnTime", ai: null,                summary: "Pile driving in progress. 540 of 1,920 piles set." },
  { date: "2026-04-14", weekday: "Tue", title: "Daily Report — Apr 14", by: { initials: "EC", name: "Emma Connor", color: "#22863A" }, time: "5:11 PM", expected: "5:00 PM", status: "Late",   ai: null,                summary: "Crew swap day. Brief slowdown during hand-off; recovered by lunch." },
];

const STATUS_TONES_DR = {
  OnTime: { bg: "rgb(208,243,217)", fg: "rgb(34,134,58)",  label: "On Time", dot: "rgb(34,134,58)"  },
  Late:   { bg: "rgb(255,243,210)", fg: "rgb(178,121,26)", label: "Late",    dot: "rgb(228,182,68)" },
  Missed: { bg: "rgb(252,226,226)", fg: "rgb(192,47,50)",  label: "Missed",  dot: "rgb(192,47,50)"  },
};

const AI_BADGES = {
  "Key Update":      { tone: "info",    icon: "info" },
  "Risk Identified": { tone: "danger",  icon: "alert" },
  "Delay Noted":     { tone: "warning", icon: "clock" },
};

// Production data: piles set per day. Target = 80/day. Green ≥95%, Yellow 75–94%, Red <75%.
const PRODUCTION = [
  { date: "2026-04-30", weekday: "Thu", expected: 80, achieved: 42, unit: "piles", crew: 28, hours: 9.5, weather: "Clear",   notes: "East tracker delivery slipped 2 days. Lost 38 piles to material wait.", flags: ["Material Delay", "Crew Idle"] },
  { date: "2026-04-29", weekday: "Wed", expected: 80, achieved: 86, unit: "piles", crew: 32, hours: 10.5, weather: "Clear",  notes: "Best day this week — full crew, all rigs operational.", flags: [] },
  { date: "2026-04-28", weekday: "Tue", expected: 80, achieved: 78, unit: "piles", crew: 30, hours: 10.0, weather: "Cloudy", notes: "Standard pace. One brief stand-down for survey check.", flags: [] },
  { date: "2026-04-27", weekday: "Mon", expected: 80, achieved: 0,  unit: "piles", crew: 0,  hours: 0,    weather: "Storm",  notes: "Site closed — high winds and lightning. No production.", flags: ["Weather Stand-down"] },
  { date: "2026-04-24", weekday: "Fri", expected: 80, achieved: 64, unit: "piles", crew: 26, hours: 9.0,  weather: "Clear",  notes: "Owner walkthrough delayed start by 90 min. Recovered partially.", flags: ["Owner Delay"] },
  { date: "2026-04-23", weekday: "Thu", expected: 80, achieved: 82, unit: "piles", crew: 30, hours: 10.0, weather: "Clear",  notes: "Strong day. Predrill rig back online after maintenance.", flags: [] },
  { date: "2026-04-22", weekday: "Wed", expected: 80, achieved: 76, unit: "piles", crew: 28, hours: 10.0, weather: "Clear",  notes: "Routine. Slight drag on south section due to caliche pockets.", flags: [] },
  { date: "2026-04-21", weekday: "Tue", expected: 80, achieved: 48, unit: "piles", crew: 28, hours: 9.5,  weather: "Clear",  notes: "Pile-driving rig 2 down 3 hours for hydraulic line repair.", flags: ["Equipment Down"] },
  { date: "2026-04-20", weekday: "Mon", expected: 80, achieved: 81, unit: "piles", crew: 30, hours: 10.5, weather: "Cloudy", notes: "Week kickoff. Torque-tube delivery staged — no impact to pile crew.", flags: [] },
  { date: "2026-04-17", weekday: "Fri", expected: 80, achieved: 38, unit: "piles", crew: 28, hours: 8.5,  weather: "Clear",  notes: "Geotech flagged refusal in north section. Predrill required for ~12% of remaining piles.", flags: ["Geotech Refusal", "Scope Change"] },
  { date: "2026-04-16", weekday: "Thu", expected: 80, achieved: 72, unit: "piles", crew: 28, hours: 10.0, weather: "Windy",  notes: "Wind gusts > 30mph paused crane work for 1 hour.", flags: ["Weather"] },
  { date: "2026-04-15", weekday: "Wed", expected: 80, achieved: 84, unit: "piles", crew: 30, hours: 10.0, weather: "Clear",  notes: "Crossed 540/1,920 milestone. Crew morale strong.", flags: [] },
  { date: "2026-04-14", weekday: "Tue", expected: 80, achieved: 56, unit: "piles", crew: 24, hours: 9.0,  weather: "Clear",  notes: "Crew swap day. Brief slowdown during hand-off; recovered by lunch.", flags: ["Crew Transition"] },
];

const prodStatus = (p) => {
  if (p.expected === 0) return "None";
  const pct = p.achieved / p.expected;
  if (pct >= 0.95) return "Green";
  if (pct >= 0.75) return "Yellow";
  return "Red";
};

const PROD_TONES = {
  Green:  { bg: "rgb(208,243,217)", fg: "rgb(34,134,58)",  dot: "rgb(34,134,58)",  label: "On Target" },
  Yellow: { bg: "rgb(255,243,210)", fg: "rgb(178,121,26)", dot: "rgb(228,182,68)", label: "At Risk" },
  Red:    { bg: "rgb(252,226,226)", fg: "rgb(192,47,50)",  dot: "rgb(192,47,50)",  label: "Behind" },
  None:   { bg: "rgb(241,242,244)", fg: "rgb(106,115,131)", dot: "rgb(163,172,186)", label: "No Production" },
};

const StatusReportsTab = ({ p }) => {
  const [search, setSearch] = React.useState("");
  const [statusFilter, setStatusFilter] = React.useState("All");
  const [employeeFilter, setEmployeeFilter] = React.useState("All");
  const [selectedDate, setSelectedDate] = React.useState("2026-04-30");
  const [month, setMonth] = React.useState(3); // April = 3 (0-indexed)
  const year = 2026;
  const [view, setView] = React.useState("compliance");
  const [selectedProdDate, setSelectedProdDate] = React.useState("2026-04-30");

  const employees = ["All", ...Array.from(new Set(REPORTS.map(r => r.by.name)))];

  const filtered = REPORTS.filter(r => {
    if (statusFilter !== "All" && r.status !== statusFilter) return false;
    if (employeeFilter !== "All" && r.by.name !== employeeFilter) return false;
    if (search && !(`${r.title} ${r.by.name} ${r.summary || ""}`.toLowerCase()).includes(search.toLowerCase())) return false;
    return true;
  });

  // Compliance metrics
  const total = REPORTS.length;
  const onTime = REPORTS.filter(r => r.status === "OnTime").length;
  const late = REPORTS.filter(r => r.status === "Late").length;
  const missed = REPORTS.filter(r => r.status === "Missed").length;
  const pctOnTime = Math.round(onTime / total * 100);
  const pctLate = Math.round(late / total * 100);
  const pctMissed = Math.round(missed / total * 100);

  return (
    <div style={{ display: "flex", flexDirection: "column", gap: 16 }}>
      {/* Sub-toggle */}
      <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", gap: 12 }}>
        <div style={{
          display: "inline-flex", padding: 3, borderRadius: 9999,
          background: "rgb(241,242,244)", border: "1px solid rgb(231,233,236)"
        }}>
          {[
            { id: "compliance", label: "Compliance", icon: "shield", count: null },
            { id: "production", label: "Production", icon: "trending", count: PRODUCTION.length },
            { id: "reports",    label: "Reports",    icon: "list",   count: REPORTS.length },
          ].map(opt => {
            const active = view === opt.id;
            return (
              <button key={opt.id} onClick={() => setView(opt.id)} style={{
                display: "inline-flex", alignItems: "center", gap: 6, padding: "6px 14px", borderRadius: 9999,
                border: "none", cursor: "pointer", fontFamily: "inherit", fontSize: 13, fontWeight: 500,
                background: active ? "#fff" : "transparent",
                color: active ? "rgb(26,27,37)" : "rgb(106,115,131)",
                boxShadow: active ? "0 1px 2px rgba(15,23,42,.08)" : "none",
                transition: "background 120ms, color 120ms"
              }}>
                <Icon name={opt.icon} size={13} color={active ? "rgb(83,74,255)" : "rgb(106,115,131)"} />
                {opt.label}
                {opt.count != null && (
                  <span style={{
                    fontSize: 11, fontWeight: 600, padding: "1px 6px", borderRadius: 9999,
                    background: active ? "rgb(241,242,244)" : "rgb(227,229,232)",
                    color: active ? "rgb(65,69,82)" : "rgb(106,115,131)",
                    fontVariantNumeric: "tabular-nums"
                  }}>{opt.count}</span>
                )}
              </button>
            );
          })}
        </div>
        <div style={{ display: "flex", gap: 6 }}>
          <Button kind="ghost" size="sm" icon="download">Export</Button>
          <Button kind="primary" size="sm" icon="plus">Submit Today's Report</Button>
        </div>
      </div>

      {view === "compliance" && <>
      {/* Compliance metrics + AI insights */}
      <div style={{ display: "grid", gridTemplateColumns: "minmax(0, 1.4fr) minmax(0, 1fr)", gap: 16 }}>
        {/* Compliance */}
        <Card padding={0}>
          <div style={{ padding: "14px 18px", borderBottom: "1px solid rgb(239,240,242)", display: "flex", alignItems: "center", justifyContent: "space-between" }}>
            <div style={{ display: "flex", alignItems: "center", gap: 8 }}>
              <span style={{ fontSize: 14, fontWeight: 600 }}>Reporting Compliance</span>
              <Chip tone="neutral">Last 30 days</Chip>
            </div>
            <span style={{ fontSize: 11, color: "rgb(34,134,58)", display: "inline-flex", alignItems: "center", gap: 4, fontWeight: 600 }}>
              <Icon name="trending" size={11} /> Improving 8% MoM
            </span>
          </div>
          <div style={{ padding: 18, display: "grid", gridTemplateColumns: "180px 1fr", gap: 24, alignItems: "center" }}>
            {/* Donut */}
            <ComplianceDonut onTime={onTime} late={late} missed={missed} total={total} />
            {/* Metrics */}
            <div style={{ display: "flex", flexDirection: "column", gap: 12 }}>
              <ComplianceMetricRow tone="OnTime" label="On Time"  count={onTime} pct={pctOnTime} primary />
              <ComplianceMetricRow tone="Late"   label="Late"     count={late}   pct={pctLate} />
              <ComplianceMetricRow tone="Missed" label="Missed"   count={missed} pct={pctMissed} />
              <div style={{ paddingTop: 10, borderTop: "1px solid rgb(239,240,242)", display: "flex", justifyContent: "space-between", fontSize: 12 }}>
                <span style={{ color: "rgb(106,115,131)" }}>Submitted vs Expected</span>
                <span style={{ fontWeight: 600, fontVariantNumeric: "tabular-nums" }}>{onTime + late} / {total}</span>
              </div>
            </div>
          </div>
        </Card>

        {/* AI Insights */}
        <div style={{
          background: "linear-gradient(180deg, rgba(232,233,246,.6) 0%, rgba(232,233,246,.2) 100%)",
          border: "1px solid rgba(178,172,255,.4)", borderRadius: 12, padding: 16
        }}>
          <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="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 Insights</span>
          </div>
          <div style={{ fontSize: 13, color: "rgb(26,27,37)", lineHeight: 1.5, marginBottom: 12 }}>
            {pctOnTime}% on-time submission rate trending up. <strong>2 risks</strong> and <strong>1 delay</strong> flagged in the last 14 days — pile-driving refusal in north section is the most actionable.
          </div>
          <div style={{ display: "flex", flexDirection: "column", gap: 6 }}>
            <InsightRow tone="warning" icon="user" text="Robert Fox missed Apr 27 — 2nd missed report this month" />
            <InsightRow tone="danger"  icon="alert" text="Geotech refusal flagged Apr 17 — converted to CO-013" />
            <InsightRow tone="info"    icon="clock" text="Late submissions cluster on Mondays (avg 28 min late)" />
          </div>
        </div>
      </div>

      {/* Calendar heatmap + selected day */}
      <Card padding={0}>
        <div style={{ padding: "14px 18px", borderBottom: "1px solid rgb(239,240,242)", display: "flex", alignItems: "center", justifyContent: "space-between" }}>
          <div style={{ display: "flex", alignItems: "center", gap: 10 }}>
            <span style={{ fontSize: 14, fontWeight: 600 }}>Compliance Calendar</span>
            <Chip tone="neutral">{["January","February","March","April","May","June","July","August","September","October","November","December"][month]} {year}</Chip>
          </div>
          <div style={{ display: "flex", alignItems: "center", gap: 12 }}>
            <Legend items={[
              { color: "rgb(34,134,58)",  label: "On Time" },
              { color: "rgb(228,182,68)", label: "Late" },
              { color: "rgb(192,47,50)",  label: "Missed" },
              { color: "rgb(227,229,232)", label: "No expected report" },
            ]} />
            <div style={{ display: "flex", gap: 4 }}>
              <IconBtn icon="chevronLeft" tone="outline" size={28} onClick={() => setMonth(Math.max(0, month - 1))} />
              <IconBtn icon="chevronRight" tone="outline" size={28} onClick={() => setMonth(Math.min(11, month + 1))} />
            </div>
          </div>
        </div>
        <div style={{ display: "grid", gridTemplateColumns: "minmax(0, 1.5fr) minmax(0, 1fr)", gap: 0 }}>
          <ComplianceCalendar reports={REPORTS} month={month} year={year} selectedDate={selectedDate} onSelect={setSelectedDate} />
          <DayDetail date={selectedDate} reports={REPORTS} />
        </div>
      </Card>
      </>}

      {view === "production" && <ProductionView selectedDate={selectedProdDate} setSelectedDate={setSelectedProdDate} />}

      {view === "reports" && <>
      {/* Toolbar */}
      <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 title, employee, summary…" 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", "OnTime", "Late", "Missed"]} onChange={setStatusFilter} icon="flag" />
        <FilterPill2Click label="Employee" value={employeeFilter} options={employees} onChange={setEmployeeFilter} icon="user" />
        <FilterPill2Click label="Range" value="Last 30 days" options={["Last 7 days", "Last 30 days", "Last 90 days", "All time"]} onChange={() => {}} icon="calendar" />
        <span style={{ marginLeft: "auto", fontSize: 12, color: "rgb(106,115,131)" }}>{filtered.length} of {REPORTS.length}</span>
      </div>

      {/* Reports table */}
      <Card padding={0}>
        <div style={{
          display: "grid",
          gridTemplateColumns: "100px minmax(0, 1.6fr) 160px 110px 130px 140px 60px",
          padding: "10px 16px", 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", gap: 12, alignItems: "center"
        }}>
          <span>Date</span>
          <span>Report</span>
          <span>Submitted By</span>
          <span>Time</span>
          <span>Status</span>
          <span>AI Highlight</span>
          <span></span>
        </div>
        {filtered.map((r, i) => {
          const tone = STATUS_TONES_DR[r.status];
          return (
            <div key={r.date} style={{
              display: "grid",
              gridTemplateColumns: "100px minmax(0, 1.6fr) 160px 110px 130px 140px 60px",
              padding: "12px 16px", gap: 12, alignItems: "center",
              borderBottom: i < filtered.length - 1 ? "1px solid rgb(239,240,242)" : "none",
              fontSize: 13, cursor: "pointer", transition: "background 120ms"
            }}
            onMouseEnter={e => e.currentTarget.style.background = "rgb(248,248,251)"}
            onMouseLeave={e => e.currentTarget.style.background = "#fff"}
            onClick={() => setSelectedDate(r.date)}>
              <div>
                <div style={{ fontWeight: 600, fontVariantNumeric: "tabular-nums" }}>{formatShortDate(r.date)}</div>
                <div style={{ fontSize: 11, color: "rgb(106,115,131)", marginTop: 2 }}>{r.weekday}</div>
              </div>
              <div style={{ minWidth: 0 }}>
                <div style={{ fontWeight: 500, color: "rgb(26,27,37)" }}>{r.title}</div>
                <div style={{ fontSize: 11, color: "rgb(106,115,131)", marginTop: 2, whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis" }}>
                  {r.summary || <span style={{ fontStyle: "italic" }}>No report submitted</span>}
                </div>
              </div>
              <div style={{ display: "flex", alignItems: "center", gap: 6, minWidth: 0 }}>
                <Avatar size={20} initials={r.by.initials} color={r.by.color} />
                <span style={{ fontSize: 12, color: "rgb(65,69,82)", whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis" }}>{r.by.name}</span>
              </div>
              <div style={{ fontSize: 12, fontVariantNumeric: "tabular-nums", color: r.time ? "rgb(26,27,37)" : "rgb(163,172,186)" }}>
                {r.time || "—"}
                {r.time && r.status === "Late" && <div style={{ fontSize: 10, color: "rgb(178,121,26)" }}>+{lateBy(r.expected, r.time)}</div>}
              </div>
              <div>
                <span style={{
                  display: "inline-flex", alignItems: "center", gap: 5, padding: "3px 8px", borderRadius: 9999,
                  background: tone.bg, color: tone.fg, fontSize: 11, fontWeight: 600
                }}>
                  <span style={{ width: 5, height: 5, borderRadius: "50%", background: tone.dot }} />
                  {tone.label}
                </span>
              </div>
              <div>
                {r.ai ? (
                  <span style={{
                    display: "inline-flex", alignItems: "center", gap: 4, padding: "3px 8px", borderRadius: 9999,
                    background: TONES[AI_BADGES[r.ai].tone].bg, color: TONES[AI_BADGES[r.ai].tone].fg,
                    fontSize: 11, fontWeight: 500
                  }}>
                    <Icon name="sparkles" size={10} />
                    {r.ai}
                  </span>
                ) : <span style={{ fontSize: 11, color: "rgb(163,172,186)" }}>—</span>}
              </div>
              <div style={{ textAlign: "right" }}>
                <Button size="xs" kind="ghost">View</Button>
              </div>
            </div>
          );
        })}
      </Card>
      </>}
    </div>
  );
};

const formatShortDate = (iso) => {
  const [y, m, d] = iso.split("-").map(Number);
  return `${["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"][m-1]} ${d}`;
};

const lateBy = (expected, actual) => {
  const parse = (t) => {
    const [hm, ap] = t.split(" ");
    let [h, m] = hm.split(":").map(Number);
    if (ap === "PM" && h !== 12) h += 12;
    if (ap === "AM" && h === 12) h = 0;
    return h * 60 + m;
  };
  const diff = parse(actual) - parse(expected);
  return diff < 60 ? `${diff}m` : `${Math.floor(diff/60)}h ${diff%60}m`;
};

const ComplianceDonut = ({ onTime, late, missed, total }) => {
  const r = 60, c = 2 * Math.PI * r;
  const segments = [
    { value: onTime, color: "rgb(34,134,58)" },
    { value: late,   color: "rgb(228,182,68)" },
    { value: missed, color: "rgb(192,47,50)" },
  ];
  let offset = 0;
  return (
    <div style={{ position: "relative", width: 160, height: 160, margin: "0 auto" }}>
      <svg width="160" height="160" viewBox="0 0 160 160" style={{ transform: "rotate(-90deg)" }}>
        <circle cx="80" cy="80" r={r} fill="none" stroke="rgb(241,242,244)" strokeWidth="14" />
        {segments.map((s, i) => {
          const len = (s.value / total) * c;
          const dasharray = `${len} ${c - len}`;
          const dashoffset = -offset;
          offset += len;
          return (
            <circle key={i} cx="80" cy="80" r={r} fill="none" stroke={s.color} strokeWidth="14"
              strokeDasharray={dasharray} strokeDashoffset={dashoffset} strokeLinecap="butt" />
          );
        })}
      </svg>
      <div style={{ position: "absolute", inset: 0, display: "flex", flexDirection: "column", alignItems: "center", justifyContent: "center" }}>
        <div style={{ fontSize: 28, fontWeight: 700, letterSpacing: "-.02em", fontVariantNumeric: "tabular-nums" }}>{Math.round(onTime/total*100)}%</div>
        <div style={{ fontSize: 11, color: "rgb(106,115,131)", fontWeight: 500 }}>On Time</div>
      </div>
    </div>
  );
};

const ComplianceMetricRow = ({ tone, label, count, pct, primary }) => {
  const t = STATUS_TONES_DR[tone];
  return (
    <div>
      <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", marginBottom: 4 }}>
        <span style={{ display: "inline-flex", alignItems: "center", gap: 6, fontSize: 12, fontWeight: 500 }}>
          <span style={{ width: 8, height: 8, borderRadius: 2, background: t.dot }} />
          {label}
        </span>
        <span style={{ fontSize: 12, fontVariantNumeric: "tabular-nums" }}>
          <span style={{ fontWeight: 600 }}>{count}</span>
          <span style={{ color: "rgb(106,115,131)", marginLeft: 6 }}>{pct}%</span>
        </span>
      </div>
      <ProgressBar value={pct} color={t.dot} height={primary ? 6 : 4} />
    </div>
  );
};

const InsightRow = ({ 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={13} 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 Legend = ({ items }) => (
  <div style={{ display: "inline-flex", gap: 12 }}>
    {items.map(i => (
      <span key={i.label} style={{ display: "inline-flex", alignItems: "center", gap: 5, fontSize: 11, color: "rgb(65,69,82)" }}>
        <span style={{ width: 8, height: 8, borderRadius: 2, background: i.color }} />
        {i.label}
      </span>
    ))}
  </div>
);

const ComplianceCalendar = ({ reports, month, year, selectedDate, onSelect }) => {
  const firstDay = new Date(year, month, 1).getDay();
  const daysInMonth = new Date(year, month + 1, 0).getDate();
  const today = new Date(2026, 3, 30); // anchor "today" on Apr 30, 2026 to match data
  const cells = [];
  for (let i = 0; i < firstDay; i++) cells.push(null);
  for (let d = 1; d <= daysInMonth; d++) cells.push(d);
  while (cells.length % 7 !== 0) cells.push(null);

  const reportFor = (d) => {
    const iso = `${year}-${String(month+1).padStart(2,"0")}-${String(d).padStart(2,"0")}`;
    return reports.find(r => r.date === iso);
  };
  const isWeekend = (idx) => idx % 7 === 0 || idx % 7 === 6;
  const isFuture = (d) => new Date(year, month, d) > today;

  return (
    <div style={{ padding: 16, borderRight: "1px solid rgb(239,240,242)" }}>
      <div style={{ display: "grid", gridTemplateColumns: "repeat(7, 1fr)", gap: 4, marginBottom: 6 }}>
        {["Sun","Mon","Tue","Wed","Thu","Fri","Sat"].map(d => (
          <div key={d} style={{ fontSize: 10, fontWeight: 600, color: "rgb(106,115,131)", textTransform: "uppercase", letterSpacing: ".05em", textAlign: "center", padding: "4px 0" }}>{d}</div>
        ))}
      </div>
      <div style={{ display: "grid", gridTemplateColumns: "repeat(7, 1fr)", gap: 4 }}>
        {cells.map((d, i) => {
          if (d === null) return <div key={i} />;
          const r = reportFor(d);
          const iso = `${year}-${String(month+1).padStart(2,"0")}-${String(d).padStart(2,"0")}`;
          const future = isFuture(d);
          const weekend = isWeekend(i);
          const isSel = iso === selectedDate;
          let bg = "#fff", fg = "rgb(26,27,37)", border = "1px solid rgb(239,240,242)", dot = null;
          if (future) { bg = "rgb(252,252,253)"; fg = "rgb(163,172,186)"; }
          else if (weekend && !r) { bg = "rgb(248,248,251)"; fg = "rgb(163,172,186)"; }
          else if (r) {
            const t = STATUS_TONES_DR[r.status];
            bg = t.bg; fg = t.fg; dot = t.dot;
            border = `1px solid ${t.dot}33`;
          }
          if (isSel) border = "2px solid rgb(83,74,255)";

          return (
            <button key={i} onClick={() => r && onSelect(iso)} disabled={!r} style={{
              aspectRatio: "1 / 1", borderRadius: 8, padding: 6, background: bg, border, cursor: r ? "pointer" : "default",
              display: "flex", flexDirection: "column", alignItems: "flex-start", justifyContent: "space-between",
              fontFamily: "inherit", color: fg, position: "relative", overflow: "hidden"
            }}
            title={r ? `${r.title} — ${STATUS_TONES_DR[r.status].label}` : ""}>
              <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", width: "100%" }}>
                <span style={{ fontSize: 12, fontWeight: 600, fontVariantNumeric: "tabular-nums" }}>{d}</span>
                {dot && <span style={{ width: 6, height: 6, borderRadius: "50%", background: dot }} />}
              </div>
              {r && (
                <div style={{ display: "flex", alignItems: "center", gap: 3, fontSize: 9, opacity: .9 }}>
                  <Avatar size={14} initials={r.by.initials} color={r.by.color} />
                  {r.ai && <Icon name="sparkles" size={9} />}
                </div>
              )}
            </button>
          );
        })}
      </div>
    </div>
  );
};

const DayDetail = ({ date, reports }) => {
  const r = reports.find(x => x.date === date);
  if (!r) {
    return (
      <div style={{ padding: 24, color: "rgb(106,115,131)", fontSize: 13, textAlign: "center" }}>
        Select a day to view its report.
      </div>
    );
  }
  const tone = STATUS_TONES_DR[r.status];
  return (
    <div style={{ padding: 18 }}>
      <div style={{ display: "flex", alignItems: "center", gap: 8, marginBottom: 10 }}>
        <span style={{ fontSize: 11, color: "rgb(106,115,131)", fontWeight: 600, textTransform: "uppercase", letterSpacing: ".05em" }}>
          {r.weekday}, {formatShortDate(r.date)}
        </span>
        <span style={{ display: "inline-flex", alignItems: "center", gap: 5, padding: "2px 8px", borderRadius: 9999, background: tone.bg, color: tone.fg, fontSize: 11, fontWeight: 600 }}>
          <span style={{ width: 5, height: 5, borderRadius: "50%", background: tone.dot }} />
          {tone.label}
        </span>
      </div>
      <h3 style={{ fontSize: 15, fontWeight: 600, margin: "0 0 8px", letterSpacing: "-.005em" }}>{r.title}</h3>
      {r.status === "Missed" ? (
        <div style={{ padding: 14, background: "rgb(252,226,226)", border: "1px solid rgba(192,47,50,.2)", borderRadius: 8, fontSize: 12, color: "rgb(192,47,50)", display: "flex", gap: 8 }}>
          <Icon name="alert" size={14} color="rgb(192,47,50)" style={{ flexShrink: 0, marginTop: 1 }} />
          <span>No report was submitted for this day. Reminder sent to {r.by.name}.</span>
        </div>
      ) : (
        <>
          <div style={{ display: "flex", alignItems: "center", gap: 14, fontSize: 12, color: "rgb(106,115,131)", marginBottom: 12 }}>
            <span style={{ display: "inline-flex", alignItems: "center", gap: 5 }}>
              <Avatar size={16} initials={r.by.initials} color={r.by.color} />
              {r.by.name}
            </span>
            <span style={{ width: 3, height: 3, borderRadius: "50%", background: "rgb(163,172,186)" }} />
            <span>Submitted {r.time}</span>
            {r.status === "Late" && <span style={{ color: "rgb(178,121,26)", fontWeight: 600 }}>+{lateBy(r.expected, r.time)} late</span>}
          </div>
          {r.ai && (
            <div style={{
              display: "inline-flex", alignItems: "center", gap: 5, padding: "3px 8px", borderRadius: 9999,
              background: TONES[AI_BADGES[r.ai].tone].bg, color: TONES[AI_BADGES[r.ai].tone].fg,
              fontSize: 11, fontWeight: 500, marginBottom: 10
            }}>
              <Icon name="sparkles" size={10} />
              {r.ai}
            </div>
          )}
          <div style={{ fontSize: 13, color: "rgb(26,27,37)", lineHeight: 1.55, padding: 12, background: "rgb(252,252,253)", border: "1px solid rgb(239,240,242)", borderRadius: 8 }}>
            {r.summary}
          </div>
          <div style={{ display: "flex", gap: 6, marginTop: 12 }}>
            <Button size="sm" kind="primary" icon="eye">View Full Report</Button>
            <Button size="sm" kind="ghost" icon="link">Open in Drive</Button>
          </div>
        </>
      )}
    </div>
  );
};

// =================================================================
// PRODUCTION VIEW
// =================================================================

const PROD_AI_FLAGS = {
  "Material Delay":     { tone: "warning", icon: "archive", text: "Material wait — supplier slipped delivery; crew rotated to predrill" },
  "Crew Idle":          { tone: "warning", icon: "user",    text: "Idle hours logged — labor cost without pile output" },
  "Weather Stand-down": { tone: "info",    icon: "alert",   text: "Site closed for safety — high winds and lightning" },
  "Owner Delay":        { tone: "warning", icon: "user",    text: "Owner walkthrough cut into rig start time" },
  "Equipment Down":     { tone: "danger",  icon: "alert",   text: "Pile-driving rig 2 hydraulic line failure — 3hr downtime" },
  "Geotech Refusal":    { tone: "danger",  icon: "alert",   text: "Subsurface refusal flagged — predrill required for ~12% of remaining piles" },
  "Scope Change":       { tone: "info",    icon: "file",    text: "Drove CO-013 (predrill scope) — 2 weeks added to plan" },
  "Weather":            { tone: "info",    icon: "alertCircle", text: "Wind gusts paused crane work for 1 hour" },
  "Crew Transition":    { tone: "info",    icon: "user",    text: "Shift-change overlap caused brief slowdown" },
};

const ProductionView = ({ selectedDate, setSelectedDate }) => {
  const totalExp = PRODUCTION.reduce((s, p) => s + p.expected, 0);
  const totalAch = PRODUCTION.reduce((s, p) => s + p.achieved, 0);
  const greenDays = PRODUCTION.filter(p => prodStatus(p) === "Green").length;
  const yellowDays = PRODUCTION.filter(p => prodStatus(p) === "Yellow").length;
  const redDays = PRODUCTION.filter(p => prodStatus(p) === "Red").length;
  const noneDays = PRODUCTION.filter(p => prodStatus(p) === "None").length;
  const overall = Math.round(totalAch / totalExp * 100);

  // 7-day rolling avg for trendline (most recent 7)
  const recent7 = PRODUCTION.slice(0, 7);
  const recent7Avg = Math.round(recent7.reduce((s, p) => s + p.achieved, 0) / recent7.length);

  const sel = PRODUCTION.find(p => p.date === selectedDate) || PRODUCTION[0];

  // Sorted oldest → newest for the bar chart
  const chartData = [...PRODUCTION].sort((a, b) => a.date.localeCompare(b.date));
  const maxBar = Math.max(...chartData.map(d => Math.max(d.expected, d.achieved))) * 1.1;

  return (
    <div style={{ display: "flex", flexDirection: "column", gap: 16 }}>
      {/* KPI strip + AI summary */}
      <div style={{ display: "grid", gridTemplateColumns: "minmax(0, 1.6fr) minmax(0, 1fr)", gap: 16 }}>
        <Card padding={0}>
          <div style={{ padding: "14px 18px", borderBottom: "1px solid rgb(239,240,242)", display: "flex", alignItems: "center", justifyContent: "space-between" }}>
            <div style={{ display: "flex", alignItems: "center", gap: 8 }}>
              <span style={{ fontSize: 14, fontWeight: 600 }}>Production Performance</span>
              <Chip tone="neutral">Last 13 working days</Chip>
              <Chip tone="neutral">Target 80 piles/day</Chip>
            </div>
            <span style={{ fontSize: 11, color: overall >= 90 ? "rgb(34,134,58)" : "rgb(178,121,26)", display: "inline-flex", alignItems: "center", gap: 4, fontWeight: 600 }}>
              <Icon name="trending" size={11} /> {overall}% of plan
            </span>
          </div>
          <div style={{ padding: 18, display: "grid", gridTemplateColumns: "repeat(4, 1fr)", gap: 16 }}>
            <ProdKPI label="Achieved" value={totalAch.toLocaleString()} unit="piles" sub={`of ${totalExp.toLocaleString()} planned`} />
            <ProdKPI label="On Target" value={greenDays} unit="days" tone="Green" />
            <ProdKPI label="At Risk" value={yellowDays} unit="days" tone="Yellow" />
            <ProdKPI label="Behind" value={redDays + noneDays} unit="days" tone="Red" sub={noneDays ? `${noneDays} no production` : null} />
          </div>
        </Card>

        <div style={{
          background: "linear-gradient(180deg, rgba(232,233,246,.6) 0%, rgba(232,233,246,.2) 100%)",
          border: "1px solid rgba(178,172,255,.4)", borderRadius: 12, padding: 16
        }}>
          <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="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 Production Insights</span>
          </div>
          <div style={{ fontSize: 13, color: "rgb(26,27,37)", lineHeight: 1.5, marginBottom: 12 }}>
            Tracking <strong>{overall}% of plan</strong>. 7-day avg <strong>{recent7Avg} piles/day</strong> vs 80 target. Geotech refusal (Apr 17) and material delay (Apr 30) are the top two recoverable issues.
          </div>
          <div style={{ display: "flex", flexDirection: "column", gap: 6 }}>
            <InsightRow tone="danger"  icon="alert"   text="Apr 30 only 53% of target — east tracker delivery slipped 2 days" />
            <InsightRow tone="danger"  icon="alert"   text="Apr 17 only 48% — geotech refusal converted to CO-013" />
            <InsightRow tone="warning" icon="trending" text="3 of last 7 days < 75% target — schedule recovery plan recommended" />
          </div>
        </div>
      </div>

      {/* Daily bar chart */}
      <Card padding={0}>
        <div style={{ padding: "14px 18px", borderBottom: "1px solid rgb(239,240,242)", display: "flex", alignItems: "center", justifyContent: "space-between" }}>
          <div style={{ display: "flex", alignItems: "center", gap: 10 }}>
            <span style={{ fontSize: 14, fontWeight: 600 }}>Expected vs. Achieved — Daily</span>
            <Chip tone="neutral">Click any bar for detail</Chip>
          </div>
          <Legend items={[
            { color: "rgb(34,134,58)",  label: "On Target (≥95%)" },
            { color: "rgb(228,182,68)", label: "At Risk (75–94%)" },
            { color: "rgb(192,47,50)",  label: "Behind (<75%)" },
            { color: "rgb(213,219,225)", label: "Expected" },
          ]} />
        </div>
        <div style={{ padding: "20px 18px 14px" }}>
          <ProductionBars data={chartData} max={maxBar} selectedDate={selectedDate} onSelect={setSelectedDate} />
        </div>
      </Card>

      {/* Day-list + Day detail */}
      <div style={{ display: "grid", gridTemplateColumns: "minmax(0, 1.3fr) minmax(0, 1fr)", gap: 16 }}>
        <Card padding={0}>
          <div style={{ padding: "14px 18px", borderBottom: "1px solid rgb(239,240,242)", display: "flex", alignItems: "center", justifyContent: "space-between" }}>
            <span style={{ fontSize: 14, fontWeight: 600 }}>Daily Production Log</span>
            <span style={{ fontSize: 11, color: "rgb(106,115,131)" }}>{PRODUCTION.length} days</span>
          </div>
          <div>
            {PRODUCTION.map((d, i) => {
              const status = prodStatus(d);
              const tone = PROD_TONES[status];
              const pct = d.expected ? Math.round(d.achieved / d.expected * 100) : 0;
              const isSel = d.date === selectedDate;
              return (
                <button key={d.date} onClick={() => setSelectedDate(d.date)} style={{
                  width: "100%", textAlign: "left", padding: "12px 18px", border: "none",
                  borderBottom: i < PRODUCTION.length - 1 ? "1px solid rgb(239,240,242)" : "none",
                  background: isSel ? "rgb(248,248,251)" : "#fff",
                  borderLeft: isSel ? "3px solid rgb(83,74,255)" : "3px solid transparent",
                  cursor: "pointer", fontFamily: "inherit",
                  display: "grid", gridTemplateColumns: "100px 1fr 90px 100px", gap: 12, alignItems: "center"
                }}>
                  <div>
                    <div style={{ fontWeight: 600, fontSize: 13, fontVariantNumeric: "tabular-nums" }}>{formatShortDate(d.date)}</div>
                    <div style={{ fontSize: 11, color: "rgb(106,115,131)", marginTop: 2 }}>{d.weekday}</div>
                  </div>
                  <div style={{ minWidth: 0 }}>
                    <div style={{ display: "flex", alignItems: "center", gap: 8, marginBottom: 6 }}>
                      <span style={{ fontSize: 13, fontWeight: 500, fontVariantNumeric: "tabular-nums" }}>
                        {d.achieved} <span style={{ color: "rgb(163,172,186)", fontWeight: 400 }}>/ {d.expected} {d.unit}</span>
                      </span>
                      {d.flags.length > 0 && (
                        <span style={{ fontSize: 10, color: "rgb(106,115,131)", display: "inline-flex", alignItems: "center", gap: 3 }}>
                          <Icon name="alert" size={10} color="rgb(178,121,26)" />
                          {d.flags.length} flag{d.flags.length > 1 ? "s" : ""}
                        </span>
                      )}
                    </div>
                    <ProdMiniBar pct={pct} color={tone.dot} />
                  </div>
                  <div style={{ fontSize: 13, fontWeight: 600, fontVariantNumeric: "tabular-nums", color: tone.fg, textAlign: "right" }}>
                    {pct}%
                  </div>
                  <div style={{ textAlign: "right" }}>
                    <span style={{
                      display: "inline-flex", alignItems: "center", gap: 5, padding: "3px 8px", borderRadius: 9999,
                      background: tone.bg, color: tone.fg, fontSize: 11, fontWeight: 600
                    }}>
                      <span style={{ width: 5, height: 5, borderRadius: "50%", background: tone.dot }} />
                      {tone.label}
                    </span>
                  </div>
                </button>
              );
            })}
          </div>
        </Card>

        <ProdDayDetail day={sel} />
      </div>
    </div>
  );
};

const ProdKPI = ({ label, value, unit, sub, tone }) => (
  <div>
    <div style={{ display: "flex", alignItems: "center", gap: 6, fontSize: 11, color: "rgb(106,115,131)", textTransform: "uppercase", letterSpacing: ".04em", fontWeight: 600, marginBottom: 6 }}>
      {tone && <span style={{ width: 8, height: 8, borderRadius: 2, background: PROD_TONES[tone].dot }} />}
      {label}
    </div>
    <div style={{ display: "flex", alignItems: "baseline", gap: 4 }}>
      <span style={{ fontSize: 24, fontWeight: 700, letterSpacing: "-.02em", fontVariantNumeric: "tabular-nums" }}>{value}</span>
      <span style={{ fontSize: 12, color: "rgb(106,115,131)" }}>{unit}</span>
    </div>
    {sub && <div style={{ fontSize: 11, color: "rgb(106,115,131)", marginTop: 2 }}>{sub}</div>}
  </div>
);

const ProdMiniBar = ({ pct, color }) => (
  <div style={{ position: "relative", height: 4, background: "rgb(241,242,244)", borderRadius: 2, overflow: "hidden" }}>
    <div style={{ position: "absolute", left: 0, top: 0, bottom: 0, width: `${Math.min(100, pct)}%`, background: color, borderRadius: 2 }} />
    {/* 100% target marker */}
    <div style={{ position: "absolute", left: "100%", top: -2, bottom: -2, width: 1, background: "rgb(106,115,131)", opacity: 0.4 }} />
  </div>
);

const ProductionBars = ({ data, max, selectedDate, onSelect }) => {
  const H = 180; // chart height
  return (
    <div style={{ position: "relative" }}>
      {/* Y axis label */}
      <div style={{
        position: "absolute", left: 0, top: 0, bottom: 24, width: 36, display: "flex", flexDirection: "column",
        justifyContent: "space-between", fontSize: 10, color: "rgb(106,115,131)", textAlign: "right", paddingRight: 6
      }}>
        <span>{Math.round(max)}</span>
        <span>{Math.round(max * 0.5)}</span>
        <span>0</span>
      </div>
      {/* Bars */}
      <div style={{
        marginLeft: 36, height: H, display: "flex", alignItems: "flex-end", gap: 6,
        borderBottom: "1px solid rgb(231,233,236)", position: "relative"
      }}>
        {/* Target line */}
        <div style={{
          position: "absolute", left: 0, right: 0, bottom: `${80 / max * 100}%`,
          borderTop: "1px dashed rgb(83,74,255)", opacity: 0.4
        }}>
          <span style={{ position: "absolute", right: 4, top: -16, fontSize: 10, color: "rgb(83,74,255)", fontWeight: 600, background: "#fff", padding: "0 4px" }}>Target 80</span>
        </div>
        {data.map(d => {
          const status = prodStatus(d);
          const tone = PROD_TONES[status];
          const expH = (d.expected / max) * 100;
          const achH = (d.achieved / max) * 100;
          const isSel = d.date === selectedDate;
          return (
            <div key={d.date} onClick={() => onSelect(d.date)} style={{
              flex: 1, height: "100%", display: "flex", flexDirection: "column", justifyContent: "flex-end",
              cursor: "pointer", position: "relative", minWidth: 0
            }}
            title={`${formatShortDate(d.date)}: ${d.achieved}/${d.expected} ${d.unit}`}>
              <div style={{
                position: "relative", height: `${expH}%`, display: "flex", alignItems: "flex-end",
                borderRadius: "4px 4px 0 0", overflow: "hidden",
                background: isSel ? "rgba(83,74,255,.08)" : "transparent",
                outline: isSel ? "2px solid rgb(83,74,255)" : "none", outlineOffset: 1,
                transition: "background 120ms"
              }}>
                {/* Expected outline */}
                <div style={{
                  position: "absolute", inset: 0,
                  border: `1px dashed ${isSel ? "rgb(83,74,255)" : "rgb(213,219,225)"}`,
                  borderRadius: "4px 4px 0 0", borderBottom: "none"
                }} />
                {/* Achieved fill */}
                <div style={{
                  width: "100%", height: `${(achH / expH) * 100}%`,
                  background: tone.dot, borderRadius: "4px 4px 0 0"
                }} />
              </div>
            </div>
          );
        })}
      </div>
      {/* X labels */}
      <div style={{ marginLeft: 36, display: "flex", gap: 6, paddingTop: 6 }}>
        {data.map(d => (
          <div key={d.date} style={{ flex: 1, textAlign: "center", fontSize: 10, color: "rgb(106,115,131)", fontVariantNumeric: "tabular-nums", minWidth: 0 }}>
            {d.date.slice(5).replace("-", "/")}
          </div>
        ))}
      </div>
    </div>
  );
};

const ProdDayDetail = ({ day }) => {
  const status = prodStatus(day);
  const tone = PROD_TONES[status];
  const pct = day.expected ? Math.round(day.achieved / day.expected * 100) : 0;
  const gap = day.expected - day.achieved;
  return (
    <Card padding={0}>
      <div style={{ padding: "14px 18px", borderBottom: "1px solid rgb(239,240,242)", display: "flex", alignItems: "center", justifyContent: "space-between" }}>
        <div style={{ display: "flex", alignItems: "center", gap: 8 }}>
          <span style={{ fontSize: 14, fontWeight: 600 }}>{day.weekday}, {formatShortDate(day.date)}</span>
          <span style={{
            display: "inline-flex", alignItems: "center", gap: 5, padding: "2px 8px", borderRadius: 9999,
            background: tone.bg, color: tone.fg, fontSize: 11, fontWeight: 600
          }}>
            <span style={{ width: 5, height: 5, borderRadius: "50%", background: tone.dot }} />
            {tone.label}
          </span>
        </div>
        <span style={{ fontSize: 22, fontWeight: 700, color: tone.fg, fontVariantNumeric: "tabular-nums", letterSpacing: "-.02em" }}>{pct}%</span>
      </div>
      <div style={{ padding: 18, display: "flex", flexDirection: "column", gap: 14 }}>
        {/* Expected vs Achieved bars */}
        <div style={{ display: "flex", flexDirection: "column", gap: 8 }}>
          <ProdDetailBar label="Expected" value={day.expected} max={Math.max(day.expected, day.achieved, 1)} unit={day.unit} color="rgb(213,219,225)" />
          <ProdDetailBar label="Achieved" value={day.achieved} max={Math.max(day.expected, day.achieved, 1)} unit={day.unit} color={tone.dot} bold />
          {gap > 0 && day.expected > 0 && (
            <div style={{ fontSize: 11, color: tone.fg, fontWeight: 600, marginTop: 2 }}>
              Gap: {gap} {day.unit} short of plan
            </div>
          )}
        </div>

        {/* Conditions row */}
        <div style={{ display: "grid", gridTemplateColumns: "repeat(3, 1fr)", gap: 8, padding: 12, background: "rgb(252,252,253)", border: "1px solid rgb(239,240,242)", borderRadius: 8 }}>
          <ProdConditionStat icon="user" label="Crew" value={`${day.crew}`} />
          <ProdConditionStat icon="clock" label="Hours" value={`${day.hours}h`} />
          <ProdConditionStat icon="alertCircle" label="Weather" value={day.weather} />
        </div>

        {/* Notes */}
        <div>
          <div style={{ fontSize: 11, color: "rgb(106,115,131)", textTransform: "uppercase", letterSpacing: ".04em", fontWeight: 600, marginBottom: 6 }}>Field Notes</div>
          <div style={{ fontSize: 13, color: "rgb(26,27,37)", lineHeight: 1.5, padding: 12, background: "rgb(252,252,253)", border: "1px solid rgb(239,240,242)", borderRadius: 8 }}>
            {day.notes}
          </div>
        </div>

        {/* AI flags */}
        {(status === "Yellow" || status === "Red" || status === "None") && day.flags.length > 0 && (
          <div>
            <div style={{ display: "flex", alignItems: "center", gap: 6, marginBottom: 8 }}>
              <Icon name="sparkles" size={12} color="rgb(83,74,255)" />
              <span style={{ fontSize: 11, color: "rgb(83,74,255)", textTransform: "uppercase", letterSpacing: ".04em", fontWeight: 600 }}>
                AI flagged this day {status === "Red" || status === "None" ? "Red" : "Yellow"}
              </span>
            </div>
            <div style={{ display: "flex", flexDirection: "column", gap: 6 }}>
              {day.flags.map(f => {
                const flag = PROD_AI_FLAGS[f];
                if (!flag) return null;
                return <InsightRow key={f} tone={flag.tone} icon={flag.icon} text={<><strong>{f}.</strong> {flag.text}</>} />;
              })}
            </div>
          </div>
        )}

        {status === "Green" && (
          <div style={{ display: "flex", gap: 8, padding: 10, background: "rgb(208,243,217)", border: "1px solid rgba(34,134,58,.2)", borderRadius: 8 }}>
            <Icon name="check" size={14} color="rgb(34,134,58)" style={{ flexShrink: 0, marginTop: 1 }} />
            <span style={{ fontSize: 12, color: "rgb(26,27,37)" }}>Met or exceeded daily target. No production risks flagged.</span>
          </div>
        )}

        <div style={{ display: "flex", gap: 6 }}>
          <Button size="sm" kind="primary" icon="eye">Open Daily Report</Button>
          <Button size="sm" kind="ghost" icon="chart">Trend</Button>
        </div>
      </div>
    </Card>
  );
};

const ProdDetailBar = ({ label, value, max, unit, color, bold }) => (
  <div>
    <div style={{ display: "flex", justifyContent: "space-between", fontSize: 11, marginBottom: 4 }}>
      <span style={{ color: "rgb(106,115,131)", fontWeight: bold ? 600 : 400 }}>{label}</span>
      <span style={{ fontVariantNumeric: "tabular-nums", fontWeight: bold ? 600 : 400 }}>{value} {unit}</span>
    </div>
    <div style={{ height: bold ? 8 : 6, background: "rgb(241,242,244)", borderRadius: 4, overflow: "hidden" }}>
      <div style={{ width: `${(value / max) * 100}%`, height: "100%", background: color, borderRadius: 4 }} />
    </div>
  </div>
);

const ProdConditionStat = ({ icon, label, value }) => (
  <div style={{ display: "flex", flexDirection: "column", gap: 4 }}>
    <span style={{ display: "inline-flex", alignItems: "center", gap: 5, fontSize: 10, color: "rgb(106,115,131)", textTransform: "uppercase", letterSpacing: ".04em", fontWeight: 600 }}>
      <Icon name={icon} size={10} />
      {label}
    </span>
    <span style={{ fontSize: 13, fontWeight: 600 }}>{value}</span>
  </div>
);

window.StatusReportsTab = StatusReportsTab;