// Manufacturing Operations page — OEE, throughput, downtime, yield

const { useState: useStateMfg } = React;

function ManufacturingPage({ data }) {
  const [line, setLine] = useStateMfg("all");

  // Mock production data
  const oee = 78.4;
  const availability = 92.1;
  const performance = 88.4;
  const quality = 96.2;

  const lines = [
    { id: "L-01", name: "Line 1 — Aurelius", oee: 82.4, avail: 94, perf: 89, qual: 98, throughput: 412, target: 480, status: "ok" },
    { id: "L-02", name: "Line 2 — Orion",    oee: 71.2, avail: 86, perf: 84, qual: 98, throughput: 318, target: 420, status: "warn" },
    { id: "L-03", name: "Line 3 — Vela",     oee: 84.1, avail: 96, perf: 91, qual: 96, throughput: 1240, target: 1320, status: "ok" },
    { id: "L-04", name: "Line 4 — Polaris",  oee: 75.8, avail: 91, perf: 88, qual: 95, throughput: 184, target: 240, status: "warn" },
  ];

  const downtimeEvents = [
    { date: "May 12", line: "L-02", machine: "Press #4",   reason: "Bearing failure",         min: 840, severity: "critical" },
    { date: "May 11", line: "L-02", machine: "Conveyor B",  reason: "Belt alignment",          min: 120, severity: "high" },
    { date: "May 10", line: "L-04", machine: "Welder #2",   reason: "Scheduled maintenance",   min: 240, severity: "low" },
    { date: "May 09", line: "L-01", machine: "Robot arm 3", reason: "Sensor recalibration",    min: 90,  severity: "medium" },
    { date: "May 08", line: "L-03", machine: "Packer #1",   reason: "Material jam",            min: 45,  severity: "medium" },
    { date: "May 07", line: "L-02", machine: "Press #4",    reason: "Bearing replacement scheduled", min: 180, severity: "low" },
  ];

  const yieldData = [
    { sku: "AUR-100", planned: 320, produced: 312, scrap: 8,  yield: 97.5, target: 98, },
    { sku: "AUR-101", planned: 180, produced: 178, scrap: 2,  yield: 98.9, target: 98, },
    { sku: "ORI-220", planned: 140, produced: 124, scrap: 16, yield: 88.6, target: 96, },
    { sku: "ORI-221", planned: 240, produced: 231, scrap: 9,  yield: 96.3, target: 96, },
    { sku: "POL-550", planned: 60,  produced: 58,  scrap: 2,  yield: 96.7, target: 95, },
    { sku: "VEL-310", planned: 1200, produced: 1184, scrap: 16, yield: 98.7, target: 98 },
  ];

  return (
    <div className="pc-page">
      {/* OEE composite KPIs */}
      <div className="pc-kpi-grid pc-kpi-grid-4">
        <KPICard label="OEE — overall"     value={oee.toFixed(1) + "%"}        delta={-2.4} sub="vs. last week" accent="var(--warning)" spark={[80.2, 81.4, 79.8, 78.1, 76.4, 78.4]} />
        <KPICard label="Availability"      value={availability.toFixed(1)+"%"} delta={-1.8} sub="Uptime vs. planned" accent="var(--positive)" />
        <KPICard label="Performance"       value={performance.toFixed(1)+"%"}  delta={-0.6} sub="Actual vs. ideal cycle" accent="var(--accent-2)" />
        <KPICard label="Quality"           value={quality.toFixed(1)+"%"}      delta={0.4}  sub="First-pass yield" accent="var(--positive)" />
      </div>

      <div className="pc-ai-banner">
        <div style={{ display: "flex", alignItems: "flex-start", gap: 14, flex: 1, minWidth: 0 }}>
          <div style={{ width: 36, height: 36, borderRadius: 10, background: "radial-gradient(circle at 30% 30%, var(--accent), var(--accent-2))", display: "flex", alignItems: "center", justifyContent: "center", flexShrink: 0 }}>
            <Icon d={icons.ai} size={18} stroke="var(--on-accent)" strokeWidth={2.4} />
          </div>
          <div>
            <div style={{ fontSize: 11, color: "var(--text-3)", textTransform: "uppercase", letterSpacing: 0.6, marginBottom: 3 }}>Throughput diagnosis</div>
            <div style={{ fontSize: 14, color: "var(--text)", lineHeight: 1.5 }}>
              OEE dropped <b style={{ color: "var(--danger)" }}>2.4 pts</b> this week, all driven by <b>Line 2</b>: 14 hours of unplanned downtime on Press #4 (bearing failure) cost ~<b>380 units</b> of output. Spare bearings are now on a 28-day lead time — recommended action: dual-source the bearing and carry a 2-unit safety stock (~$840 of inventory for ~$28K of avoided shortfall).
            </div>
          </div>
        </div>
        <button className="pc-btn-mini">Open work order</button>
      </div>

      {/* Lines table */}
      <Card title="Production lines" subtitle="Real-time OEE, throughput, and health"
            action={
              <div style={{ display: "flex", gap: 8 }}>
                <ExportButton rows={lines} filename="production_lines" />
                <SegSmall opts={["This shift", "Today", "Week"]} active="Today" />
              </div>
            } padding={0}>
        <table className="pc-table">
          <thead>
            <tr>
              <th>Line</th>
              <th style={{textAlign:"right"}}>OEE</th>
              <th>Availability</th>
              <th>Performance</th>
              <th>Quality</th>
              <th style={{textAlign:"right"}}>Throughput</th>
              <th>vs Target</th>
              <th>Status</th>
            </tr>
          </thead>
          <tbody>
            {lines.map((l, i) => {
              const pctOfTarget = l.throughput / l.target;
              return (
                <tr key={i} className={l.status === "warn" ? "pc-row-danger" : ""}>
                  <td style={{paddingLeft:14}}>
                    <div style={{ fontSize: 12.5, fontWeight: 500 }}>{l.name}</div>
                    <div style={{ fontFamily: "ui-monospace, monospace", fontSize: 10.5, color: "var(--text-3)" }}>{l.id}</div>
                  </td>
                  <td style={{textAlign: "right", fontFamily: "ui-monospace, monospace", fontWeight: 600, color: l.oee >= 85 ? "var(--positive)" : l.oee >= 75 ? "var(--warning)" : "var(--danger)"}}>{l.oee.toFixed(1)}%</td>
                  <td><Bullet value={l.avail} target={92} max={100} accent={l.avail >= 92 ? "var(--positive)" : "var(--warning)"} /></td>
                  <td><Bullet value={l.perf}  target={88} max={100} accent={l.perf  >= 88 ? "var(--positive)" : "var(--warning)"} /></td>
                  <td><Bullet value={l.qual}  target={95} max={100} accent={l.qual  >= 95 ? "var(--positive)" : "var(--warning)"} /></td>
                  <td style={{textAlign: "right", fontFamily: "ui-monospace, monospace"}}>{l.throughput} / {l.target}</td>
                  <td><Bullet value={pctOfTarget * 100} target={100} max={120} accent={pctOfTarget >= 1 ? "var(--positive)" : "var(--warning)"} /></td>
                  <td><SevPill sev={l.status === "warn" ? "high" : "low"} /></td>
                </tr>
              );
            })}
          </tbody>
        </table>
      </Card>

      <div className="pc-grid-2">
        <Card title="Downtime — last 7 days" subtitle="Unplanned events by line"
              action={<ExportButton rows={downtimeEvents} filename="downtime_log" />} padding={0}>
          <table className="pc-table compact">
            <thead><tr><th>Date</th><th>Line</th><th>Machine</th><th>Reason</th><th style={{textAlign:"right"}}>Min</th><th></th></tr></thead>
            <tbody>
              {downtimeEvents.map((d, i) => (
                <tr key={i}>
                  <td style={{paddingLeft:14, fontSize: 11.5, color: "var(--text-2)"}}>{d.date}</td>
                  <td style={{fontFamily: "ui-monospace, monospace", fontSize: 11}}>{d.line}</td>
                  <td style={{fontSize: 12}}>{d.machine}</td>
                  <td style={{fontSize: 11.5, color: "var(--text-2)"}}>{d.reason}</td>
                  <td style={{fontFamily: "ui-monospace, monospace", textAlign: "right", color: d.min > 300 ? "var(--danger)" : "var(--text-2)"}}>{d.min}</td>
                  <td><SevPill sev={d.severity} /></td>
                </tr>
              ))}
            </tbody>
          </table>
        </Card>

        <Card title="Downtime breakdown" subtitle="By reason category · last 30 days">
          <div style={{ padding: "8px 0" }}>
            {[
              { c: "Mechanical failure",      h: 22.4, color: "var(--danger)" },
              { c: "Material/changeover",     h: 14.2, color: "var(--warning)" },
              { c: "Scheduled maintenance",   h: 11.8, color: "var(--accent-2)" },
              { c: "Quality holds",           h: 7.4,  color: "var(--accent)" },
              { c: "Operator unavailable",    h: 5.1,  color: "var(--text-3)" },
            ].map((b, i) => (
              <div key={i} style={{ marginBottom: 12 }}>
                <div style={{ display: "flex", justifyContent: "space-between", fontSize: 12, marginBottom: 6 }}>
                  <span>{b.c}</span>
                  <span style={{ fontFamily: "ui-monospace, monospace", fontWeight: 500 }}>{b.h.toFixed(1)} hrs</span>
                </div>
                <div style={{ height: 6, background: "var(--bg-elev-2)", borderRadius: 1 }}>
                  <div style={{ width: (b.h / 22.4 * 100) + "%", height: "100%", background: b.color, borderRadius: 1 }} />
                </div>
              </div>
            ))}
          </div>
          <AIInsight>
            <b>Mechanical failure</b> dominates downtime — and 64% of those hours trace to <b>Press #4</b>. A preventive bearing replacement schedule would have caught the May 12 event. Recommend adding to PM calendar.
          </AIInsight>
        </Card>
      </div>

      <Card title="Material yield & scrap" subtitle="Production runs · last 7 days"
            action={<ExportButton rows={yieldData} filename="material_yield" />} padding={0}>
        <table className="pc-table">
          <thead>
            <tr>
              <th>SKU</th>
              <th style={{textAlign:"right"}}>Planned qty</th>
              <th style={{textAlign:"right"}}>Produced</th>
              <th style={{textAlign:"right"}}>Scrap</th>
              <th style={{textAlign:"right"}}>Yield %</th>
              <th>vs Target</th>
              <th>Cost of scrap</th>
            </tr>
          </thead>
          <tbody>
            {yieldData.map((y, i) => {
              const variance = y.yield - y.target;
              const scrapCost = y.scrap * 240; // mock unit cost
              return (
                <tr key={i} className={variance < -3 ? "pc-row-danger" : ""}>
                  <td style={{paddingLeft:14, fontFamily: "ui-monospace, monospace", fontWeight: 500}}>{y.sku}</td>
                  <td style={{textAlign:"right", fontFamily: "ui-monospace, monospace"}}>{y.planned}</td>
                  <td style={{textAlign:"right", fontFamily: "ui-monospace, monospace"}}>{y.produced}</td>
                  <td style={{textAlign:"right", fontFamily: "ui-monospace, monospace", color: "var(--danger)"}}>{y.scrap}</td>
                  <td style={{textAlign:"right", fontFamily: "ui-monospace, monospace", fontWeight: 600, color: variance >= 0 ? "var(--positive)" : variance < -3 ? "var(--danger)" : "var(--warning)"}}>{y.yield.toFixed(1)}%</td>
                  <td><Bullet value={y.yield} target={y.target} max={100} accent={variance >= 0 ? "var(--positive)" : "var(--warning)"} /></td>
                  <td style={{fontFamily: "ui-monospace, monospace", color: "var(--text-2)"}}>{fmtUSD(scrapCost)}</td>
                </tr>
              );
            })}
          </tbody>
        </table>
      </Card>

      <div className="pc-grid-2">
        <Card title="On-time delivery" subtitle="Customer ship commitments">
          <div style={{ display: "flex", alignItems: "center", justifyContent: "center", margin: "12px 0 20px" }}>
            <Donut size={140} stroke={18}
              segments={[
                { value: 92, color: "var(--positive)" },
                { value: 6,  color: "var(--warning)" },
                { value: 2,  color: "var(--danger)" },
              ]}
              center={
                <>
                  <div style={{ fontSize: 28, fontWeight: 600, fontFamily: "ui-monospace, monospace" }}>92%</div>
                  <div style={{ fontSize: 10.5, color: "var(--text-3)", textTransform: "uppercase", letterSpacing: 0.5 }}>OTD</div>
                </>
              } />
          </div>
          <table className="pc-table compact">
            <tbody>
              <tr><td style={{paddingLeft: 14}}><span style={{color: "var(--positive)"}}>●</span> On time</td><td style={{fontFamily: "ui-monospace, monospace", textAlign: "right"}}>184 shipments</td></tr>
              <tr><td style={{paddingLeft: 14}}><span style={{color: "var(--warning)"}}>●</span> 1–3 days late</td><td style={{fontFamily: "ui-monospace, monospace", textAlign: "right"}}>12 shipments</td></tr>
              <tr><td style={{paddingLeft: 14}}><span style={{color: "var(--danger)"}}>●</span> 4+ days late</td><td style={{fontFamily: "ui-monospace, monospace", textAlign: "right"}}>4 shipments</td></tr>
            </tbody>
          </table>
        </Card>

        <Card title="Cycle time trend" subtitle="Avg. seconds per unit · 12 weeks">
          <AreaChart
            height={220}
            labels={["W14","W15","W16","W17","W18","W19","W20","W21","W22","W23","W24","W25"]}
            yFmt={(v) => v.toFixed(0) + "s"}
            series={[
              { name: "Actual",  values: [48, 47, 48, 49, 48, 47, 49, 51, 53, 54, 52, 52], color: "var(--accent)" },
              { name: "Standard",  values: Array(12).fill(48), color: "var(--positive)", fill: false, dashed: true },
            ]}
          />
          <AIInsight>
            Cycle time has drifted from standard by ~4s/unit over the past 4 weeks — that's <b>~8.3% throughput loss</b> when running at capacity. Investigation suggests scheduled tool changeover frequency is too high; relaxing changeover from every 240 units to every 320 should recover ~3 seconds.
          </AIInsight>
        </Card>
      </div>
    </div>
  );
}

Object.assign(window, { ManufacturingPage });
