/* ===================================================================
   KabelFlux v5 — BOM view + charts (L4 fix)
   - Donut: wires by gauge
   - Horizontal bars: cable-type distribution
   - KPI strip + line-item table
   =================================================================== */

/* — Reusable donut chart — */
const Donut = ({ data, size=180, thickness=22, label }) => {
  const total = data.reduce((a, b) => a + b.value, 0);
  const r = (size - thickness) / 2;
  const c = 2 * Math.PI * r;
  let acc = 0;
  return (
    <div className="kf-donut">
      <svg width={size} height={size} role="img" aria-label={label || 'Distribution chart'}>
        <g transform={`translate(${size/2} ${size/2}) rotate(-90)`}>
          <circle r={r} fill="none" stroke="var(--bg-3)" strokeWidth={thickness}/>
          {data.map((d, i) => {
            const len = (d.value / total) * c;
            const slice = (
              <circle key={i} r={r} fill="none"
                      stroke={d.color}
                      strokeWidth={thickness}
                      strokeDasharray={`${len} ${c}`}
                      strokeDashoffset={-acc}
                      strokeLinecap="butt"/>
            );
            acc += len;
            return slice;
          })}
        </g>
        <text x={size/2} y={size/2 - 2} textAnchor="middle" fontSize="22" fontWeight="700" fill="var(--t-1)" fontFamily="var(--f-display)" style={{fontVariantNumeric:'tabular-nums'}}>{total}</text>
        <text x={size/2} y={size/2 + 16} textAnchor="middle" fontSize="9" fill="var(--t-3)" letterSpacing="1" fontWeight="700">{(label || '').toUpperCase()}</text>
      </svg>
      <div className="kf-donut-legend">
        {data.map((d, i) => (
          <div key={i} className="kf-donut-legend-row">
            <span className="kf-donut-dot" style={{ background: d.color }}/>
            <span className="kf-donut-label">{d.name}</span>
            <span className="kf-donut-val num">{d.value}</span>
            <span className="kf-donut-pct num">{Math.round((d.value/total)*100)}%</span>
          </div>
        ))}
      </div>
    </div>
  );
};

/* — Horizontal bars — */
const BarRows = ({ data, max, format=(v=>v), unit='' }) => {
  const M = max || Math.max(...data.map(d => d.value));
  return (
    <div className="kf-bars">
      {data.map((d, i) => (
        <div key={i} className="kf-bar-row">
          <div className="kf-bar-name">{d.name}</div>
          <div className="kf-bar-track">
            <div className="kf-bar-fill" style={{ width: `${(d.value / M) * 100}%`, background: d.color || 'var(--info)' }}/>
          </div>
          <div className="kf-bar-val num">{format(d.value)}{unit}</div>
        </div>
      ))}
    </div>
  );
};

/* — BOM view — */
const BomView = ({ wires=[], connectors=[], nodes=[], bundles=[], realPid=null, onExport }) => {
  const gaugeData = useMemo(() => {
    const map = {};
    wires.forEach(w => { map[w.gauge] = (map[w.gauge] || 0) + 1; });
    const palette = ['#4a9eff','#00d4aa','#f5a623','#a78bfa','#ec4899','#ef4e4e'];
    return Object.entries(map).sort((a,b) => b[1]-a[1]).map(([name, value], i) => ({ name, value, color: palette[i % palette.length] }));
  }, [wires]);

  const cableData = useMemo(() => {
    const map = {};
    wires.forEach(w => { map[w.cable] = (map[w.cable] || 0) + 1; });
    return Object.entries(map).sort((a,b)=>b[1]-a[1]).map(([name, value]) => ({ name, value }));
  }, [wires]);

  const colorData = useMemo(() => {
    const map = {};
    wires.forEach(w => { map[w.color] = (map[w.color] || 0) + 1; });
    return Object.entries(map).sort((a,b)=>b[1]-a[1]).slice(0,8).map(([name,value]) => ({ name, value, color: COLOR_HEX[name] }));
  }, [wires]);

  const lengthTotal = wires.reduce((a, w) => a + w.length, 0);
  const totalShield = wires.filter(w => w.shield).length;

  return (
    <div className="kf-view kf-bom">
      <ViewHeader title="Bill of Materials" hint="Live — recomputed from project wires, connectors and nodes" actions={
        <>
          <Btn kind="ghost" icon="copy" size="sm">Copy summary</Btn>
          <Btn kind="outline" icon="download" onClick={() => onExport && onExport('bom')}>Export PDF</Btn>
          <Btn kind="primary" icon="download" onClick={() => onExport && onExport('bom-xlsx')}>Export XLSX</Btn>
        </>
      }/>

      <div className="kf-bom-scroll">
        {/* KPI strip */}
        <div className="kf-kpi-strip">
          <KPI label="Wires"        value={wires.length}        delta="+3 since v4.31" tone="info"/>
          <KPI label="Connectors"   value={connectors.length}   delta="6 types"        tone="default"/>
          <KPI label="Nodes"        value={nodes.length}        delta="1 fuse · 1 GND" tone="default"/>
          <KPI label="Total length" value={`${(lengthTotal/1000).toFixed(2)} m`} sub={`${lengthTotal.toLocaleString()} mm`} tone="default"/>
          <KPI label="Shielded"     value={totalShield} sub={`${Math.round(totalShield/wires.length*100)}% of wires`} tone="violet"/>
          <KPI label="Cost est."    value="$84.20" sub="Per harness, no labour" tone="success"/>
        </div>

        {/* Charts row */}
        <div className="kf-bom-grid">
          <div className="card">
            <div className="card-head">
              <h3>Wires by gauge</h3>
              <Chip size="sm">{wires.length} total</Chip>
            </div>
            <div className="card-body">
              <Donut data={gaugeData} label="WIRES"/>
            </div>
          </div>

          <div className="card">
            <div className="card-head">
              <h3>Cable type distribution</h3>
              <Chip size="sm">{cableData.length} types</Chip>
            </div>
            <div className="card-body">
              <BarRows data={cableData}/>
            </div>
          </div>

          <div className="card">
            <div className="card-head">
              <h3>Color coverage</h3>
              <Chip size="sm" tone="info">IEC 60757</Chip>
            </div>
            <div className="card-body">
              <BarRows data={colorData}/>
            </div>
          </div>

          <div className="card">
            <div className="card-head">
              <h3>Length by bundle</h3>
              <Chip size="sm" tone="info" icon="ruler">Active: L1</Chip>
            </div>
            <div className="card-body">
              <BarRows
                data={bundles.map(b => ({ name: `${b.label} · ${b.count}w`, value: b.length, color: 'var(--info)' }))}
                unit=" mm"/>
            </div>
          </div>
        </div>

        {/* Connector schedule + Node schedule */}
        <div className="kf-bom-grid two">
          <div className="card flush">
            <div className="card-head"><h3>Connector schedule</h3><Chip size="sm">{connectors.length}</Chip></div>
            <table className="kf-table">
              <thead>
                <tr><th>Ref</th><th>Type</th><th>Gender</th><th className="num">Pins</th><th className="num">Wired</th><th>Description</th></tr>
              </thead>
              <tbody>
                {connectors.map(c => {
                  const wired = wires.filter(w => w.fromConn === c.id || w.toConn === c.id).length;
                  return (
                    <tr key={c.id}>
                      <td className="mono"><b>{c.id}</b></td>
                      <td>{c.type}</td>
                      <td>{c.gender === 'M' ? 'Male' : 'Female'}</td>
                      <td className="num">{c.pins}</td>
                      <td className="num">{wired}/{c.pins}</td>
                      <td style={{ color:'var(--t-3)' }}>{c.label.split(' — ')[1]}</td>
                    </tr>
                  );
                })}
              </tbody>
            </table>
          </div>

          <div className="card flush">
            <div className="card-head"><h3>Node schedule</h3><Chip size="sm">{nodes.length}</Chip></div>
            <table className="kf-table">
              <thead>
                <tr><th>Ref</th><th>Type</th><th>Value</th><th>Coordinates</th></tr>
              </thead>
              <tbody>
                {nodes.map(n => (
                  <tr key={n.id}>
                    <td className="mono"><b>{n.label}</b></td>
                    <td>{n.type === 'splice' ? 'Splice' : n.type === 'fuse' ? 'Fuse' : 'Ground'}</td>
                    <td className="mono">{n.value || '—'}</td>
                    <td className="mono" style={{ color:'var(--t-3)' }}>{n.x}, {n.y}</td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        </div>
      </div>
    </div>
  );
};

const KPI = ({ label, value, sub, delta, tone='default' }) => (
  <div className={`kf-kpi kf-kpi-${tone}`}>
    <div className="kf-kpi-label">{label}</div>
    <div className="kf-kpi-value num">{value}</div>
    {sub && <div className="kf-kpi-sub">{sub}</div>}
    {delta && <div className="kf-kpi-delta">{delta}</div>}
  </div>
);

const STYLE = `
.kf-bom-scroll { flex: 1; overflow-y: auto; padding: 18px; }
.kf-kpi-strip {
  display: grid; grid-template-columns: repeat(6, 1fr); gap: 10px;
  margin-bottom: 18px;
}
@media (max-width: 1200px) { .kf-kpi-strip { grid-template-columns: repeat(3, 1fr); } }
.kf-kpi {
  background: var(--bg-2);
  border: 1px solid var(--line);
  border-radius: var(--r-3);
  padding: 14px 16px;
}
.kf-kpi-label { font-size: 10px; text-transform: uppercase; letter-spacing: 1px; color: var(--t-3); font-weight: 700; margin-bottom: 8px; }
.kf-kpi-value { font-family: var(--f-display); font-size: 28px; font-weight: 700; color: var(--t-1); line-height: 1; letter-spacing: -.5px; }
.kf-kpi-sub   { font-size: 11px; color: var(--t-3); margin-top: 6px; }
.kf-kpi-delta { font-size: 10.5px; color: var(--info); margin-top: 4px; font-family: var(--f-mono); }
.kf-kpi-info .kf-kpi-value    { color: var(--info); }
.kf-kpi-success .kf-kpi-value { color: var(--success); }
.kf-kpi-violet .kf-kpi-value  { color: var(--violet); }
.kf-kpi-warning .kf-kpi-value { color: var(--warning); }

.kf-bom-grid {
  display: grid; grid-template-columns: repeat(2, 1fr); gap: 12px;
  margin-bottom: 14px;
}
.kf-bom-grid.two { grid-template-columns: 1.4fr 1fr; }
@media (max-width: 1100px) { .kf-bom-grid, .kf-bom-grid.two { grid-template-columns: 1fr; } }

/* Donut */
.kf-donut { display: flex; gap: 24px; align-items: center; }
.kf-donut-legend { flex: 1; display: flex; flex-direction: column; gap: 6px; min-width: 0; }
.kf-donut-legend-row {
  display: grid;
  grid-template-columns: 14px 1fr auto 44px;
  align-items: center; gap: 10px;
  font-size: 12px;
  padding: 4px 0;
}
.kf-donut-dot   { width: 10px; height: 10px; border-radius: 2px; }
.kf-donut-label { color: var(--t-2); }
.kf-donut-val   { font-weight: 600; color: var(--t-1); }
.kf-donut-pct   { color: var(--t-3); text-align: right; }

/* Bars */
.kf-bars { display: flex; flex-direction: column; gap: 8px; }
.kf-bar-row {
  display: grid; grid-template-columns: 140px 1fr 60px;
  gap: 10px; align-items: center;
  font-size: 12px;
}
.kf-bar-name { color: var(--t-2); white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
.kf-bar-track {
  height: 14px;
  background: var(--bg-3);
  border-radius: 2px;
  overflow: hidden;
  position: relative;
}
.kf-bar-fill {
  height: 100%;
  border-radius: 2px;
  transition: width .35s var(--ease);
}
.kf-bar-val { color: var(--t-1); font-weight: 600; text-align: right; }
`;
document.head.appendChild(Object.assign(document.createElement('style'), { textContent: STYLE }));

window.BomView = BomView;
window.Donut = Donut;
window.BarRows = BarRows;
window.KPI = KPI;
