/* ===== Compliance / KPI right-side panel ===== */
const Bar = ({ value, max, color = 'var(--mojro-red)', warnAt = 0.85, badAt = 1.0, label, sub, mono = false }) => {
  const pct = Math.min(1, value / max);
  const cls = pct >= badAt ? 'bad' : pct >= warnAt ? 'warn' : 'ok';
  const tint = cls === 'bad' ? 'var(--bad)' : cls === 'warn' ? 'var(--warn)' : color;
  return (
    <div>
      <div style={{ display:'flex', justifyContent:'space-between', alignItems:'baseline', marginBottom:4 }}>
        <span style={{ fontSize:12, color:'var(--ink-2)' }}>{label}</span>
        <span className="mono" style={{ fontSize:12, color:'var(--ink-1)', fontWeight:600 }}>{sub}</span>
      </div>
      <div style={{ height:8, background:'#efe8df', borderRadius:4, overflow:'hidden', position:'relative' }}>
        <div style={{ width: (pct*100)+'%', height:'100%', background: tint, transition:'width 240ms' }} />
        {warnAt && (<div style={{ position:'absolute', left: (warnAt*100)+'%', top:0, bottom:0, width:1, background:'rgba(0,0,0,0.15)' }} />)}
      </div>
    </div>
  );
};

const AxleChart = ({ axles }) => {
  const max = Math.max(...axles.map(a => a.limit));
  return (
    <div>
      <div style={{ display:'flex', alignItems:'flex-end', gap:8, height:78, padding:'0 4px', borderBottom:'1px dashed var(--line-strong)' }}>
        {axles.map(a => {
          const h = (a.load / max) * 70;
          const cls = a.load > a.limit ? 'var(--bad)' : a.load > a.limit*0.9 ? 'var(--warn)' : 'var(--ok)';
          return (
            <div key={a.name} style={{ flex:1, display:'flex', flexDirection:'column', alignItems:'center', gap:4 }}>
              <div style={{ height: h+'px', width: '100%', background: cls, borderRadius:'4px 4px 0 0', position:'relative' }} title={`${a.name}: ${a.load}t / ${a.limit}t`}>
                {a.load > a.limit*0.9 && (
                  <div style={{ position:'absolute', top:-14, left:'50%', transform:'translateX(-50%)', fontSize:10, fontFamily:'var(--font-mono)', color:cls, fontWeight:600 }}>
                    {a.load}t
                  </div>
                )}
              </div>
            </div>
          );
        })}
      </div>
      <div style={{ display:'flex', gap:8, marginTop:4 }}>
        {axles.map(a => (
          <div key={a.name} style={{ flex:1, textAlign:'center' }}>
            <div style={{ fontSize:10, color:'var(--ink-3)' }}>{a.name}</div>
            <div className="mono" style={{ fontSize:11 }}>{a.load}<span style={{ color:'var(--ink-4)' }}>/{a.limit}t</span></div>
          </div>
        ))}
      </div>
    </div>
  );
};

const CogIndicator = ({ x = 0.42, y = 0.5, safeXMin=0.35, safeXMax=0.60, safeYMin=0.30, safeYMax=0.70 }) => {
  const inSafe = x >= safeXMin && x <= safeXMax && y >= safeYMin && y <= safeYMax;
  return (
    <div style={{ position:'relative', aspectRatio: '2.4 / 1', background:'#efe8df', borderRadius:6, overflow:'hidden', border:'1px solid var(--line)' }}>
      {/* safe zone */}
      <div style={{
        position:'absolute',
        left: (safeXMin*100)+'%', right: (100-safeXMax*100)+'%',
        top: (safeYMin*100)+'%', bottom: (100-safeYMax*100)+'%',
        background: 'rgba(31,138,91,0.18)',
        border: '1px dashed rgba(31,138,91,0.6)',
        borderRadius: 4,
      }}/>
      {/* center crosshair */}
      <div style={{ position:'absolute', left:'50%', top:0, bottom:0, width:1, background:'rgba(0,0,0,0.1)' }}/>
      <div style={{ position:'absolute', top:'50%', left:0, right:0, height:1, background:'rgba(0,0,0,0.1)' }}/>
      {/* CoG dot */}
      <div style={{
        position:'absolute',
        left: (x*100)+'%', top:(y*100)+'%',
        width: 14, height: 14, marginLeft:-7, marginTop:-7,
        borderRadius: '50%',
        background: inSafe ? 'var(--ok)' : 'var(--bad)',
        boxShadow: '0 0 0 4px ' + (inSafe ? 'rgba(31,138,91,0.25)' : 'rgba(193,51,51,0.25)'),
        transition: 'left 240ms, top 240ms, background 240ms',
      }}/>
      {/* front label */}
      <div style={{ position:'absolute', left:6, top:4, fontSize:10, color:'var(--ink-3)', letterSpacing:'0.08em' }}>FRONT</div>
      <div style={{ position:'absolute', right:6, top:4, fontSize:10, color:'var(--ink-3)', letterSpacing:'0.08em' }}>REAR</div>
    </div>
  );
};

const ViolationList = ({ items, onSelect }) => {
  if (!items.length) {
    return (
      <div style={{ padding:'10px', background:'var(--ok-bg)', border:'1px solid rgba(31,138,91,0.25)', borderRadius:6, color:'var(--ok)', fontSize:12, display:'flex', alignItems:'center', gap:6 }}>
        <Icon name="check" size={14}/> All rules satisfied
      </div>
    );
  }
  return (
    <div style={{ display:'flex', flexDirection:'column', gap:6 }}>
      {items.map(v => (
        <div key={v.id}
          onClick={() => onSelect && onSelect(v.item)}
          style={{
            padding:'8px 10px',
            background: v.severity === 'bad' ? 'var(--bad-bg)' : 'var(--warn-bg)',
            border: '1px solid ' + (v.severity === 'bad' ? 'rgba(193,51,51,0.25)' : 'rgba(201,138,27,0.25)'),
            borderRadius: 6, cursor:'pointer'
          }}>
          <div style={{ display:'flex', justifyContent:'space-between', alignItems:'center', marginBottom:2 }}>
            <span style={{ fontSize:11.5, fontWeight:600, color: v.severity === 'bad' ? 'var(--bad)' : 'var(--warn)' }}>
              <Icon name="warning" size={11} style={{ marginRight:4, verticalAlign:'-2px' }}/>
              {v.rule}
            </span>
            <span className="mono" style={{ fontSize:10, color:'var(--ink-3)' }}>#{v.item}</span>
          </div>
          <div style={{ fontSize:11.5, color:'var(--ink-2)', lineHeight:1.4 }}>{v.detail}</div>
        </div>
      ))}
    </div>
  );
};

const CompliancePanel = ({ kpis, axles, violations, onSelectItem }) => {
  return (
    <div className="card" style={{ display:'flex', flexDirection:'column', height:'100%', borderRadius:0, borderTop:0, borderRight:0, borderBottom:0, background:'var(--bg-elev)' }}>
      <div style={{ padding:'12px 14px', borderBottom:'1px solid var(--line)', display:'flex', alignItems:'center', justifyContent:'space-between' }}>
        <div>
          <div className="h-eyebrow">Compliance</div>
          <div style={{ fontWeight:700, fontSize:14, marginTop:2 }}>Live load summary</div>
        </div>
        <span className={"chip " + (violations.filter(v=>v.severity==='bad').length ? 'chip--bad' : violations.length ? 'chip--warn' : 'chip--ok')}>
          {violations.length === 0 ? <Icon name="check" size={11}/> : <Icon name="warning" size={11}/>}
          {violations.length || 'OK'} {violations.length === 1 ? 'issue' : violations.length ? 'issues' : ''}
        </span>
      </div>

      <div style={{ padding:'12px 14px', display:'flex', flexDirection:'column', gap:14, overflowY:'auto', flex:1, minHeight:0 }}>
        {/* metric cards */}
        <div style={{ display:'grid', gridTemplateColumns:'1fr 1fr', gap:8 }}>
          <KpiTile label="Volume used" value={`${kpis.volumePct}%`} sub="of 73.5 m³" tone={kpis.volumePct >= 95 ? 'bad' : kpis.volumePct >= 70 ? 'ok' : 'warn'} />
          <KpiTile label="Payload" value={`${kpis.weight}t`} sub={`of ${kpis.weightMax}t`} tone={(kpis.weight/kpis.weightMax) > 0.95 ? 'bad' : 'ok'}/>
          <KpiTile label="Containers" value={kpis.containerCount} sub="40ft HC" tone="info"/>
          <KpiTile label="Items" value={kpis.items} sub={`${kpis.skus} SKUs`} />
        </div>

        <section>
          <h6 className="h-eyebrow" style={{ marginBottom:8 }}>Volume utilisation</h6>
          <Bar label="Cube" sub={`${kpis.volumePct}% · ${kpis.deadAir}% dead air`} value={kpis.volumePct} max={100} warnAt={0.7} badAt={0.99}/>
        </section>

        <section>
          <h6 className="h-eyebrow" style={{ marginBottom:8 }}>Axle loads</h6>
          <AxleChart axles={axles}/>
        </section>

        <section>
          <h6 className="h-eyebrow" style={{ marginBottom:8 }}>Centre of gravity</h6>
          <CogIndicator x={kpis.cogX} y={kpis.cogY}/>
          <div style={{ marginTop:6, display:'flex', justifyContent:'space-between', fontSize:11.5, color:'var(--ink-3)' }}>
            <span>From front: <span className="mono" style={{ color:'var(--ink-1)' }}>{Math.round(kpis.cogX*100)}%</span></span>
            <span>Lateral offset: <span className="mono" style={{ color:'var(--ink-1)' }}>{Math.round((kpis.cogY-0.5)*100)}%</span></span>
          </div>
        </section>

        <section>
          <div style={{ display:'flex', alignItems:'center', justifyContent:'space-between', marginBottom:8 }}>
            <h6 className="h-eyebrow" style={{ margin:0 }}>Active violations</h6>
            <button className="btn btn--sm btn--ghost"><Icon name="wand" size={11}/> Auto-rebalance</button>
          </div>
          <ViolationList items={violations} onSelect={onSelectItem}/>
        </section>

        <section>
          <h6 className="h-eyebrow" style={{ marginBottom:8 }}>Decision log</h6>
          <div style={{ display:'flex', flexDirection:'column', gap:6, fontSize:12 }}>
            <DecisionRow tone="ok"   text='Placed PLT-EUR-A x8 at floor level — heaviest first rule.'/>
            <DecisionRow tone="info" text='Rotated GD-1029 by 90° to fit row width.'/>
            <DecisionRow tone="warn" text='Held PLT-EUR-C in rear quarter — hazmat separation from food.'/>
            <DecisionRow tone="info" text='Pipes loaded end-first against right wall — saved 0.62 m³.'/>
          </div>
        </section>
      </div>
    </div>
  );
};

const KpiTile = ({ label, value, sub, tone = 'ok' }) => {
  const palette = { ok:'var(--ok)', warn:'var(--warn)', bad:'var(--bad)', info:'var(--info)' };
  return (
    <div style={{ padding:'10px 12px', background:'var(--bg-card)', border:'1px solid var(--line)', borderRadius:8 }}>
      <div style={{ fontSize:10.5, color:'var(--ink-3)', textTransform:'uppercase', letterSpacing:'0.08em', fontWeight:600 }}>{label}</div>
      <div style={{ display:'flex', alignItems:'baseline', gap:4, marginTop:2 }}>
        <div style={{ fontSize:20, fontWeight:700, color: palette[tone] }} className="mono">{value}</div>
        <div style={{ fontSize:11, color:'var(--ink-3)' }} className="mono">{sub}</div>
      </div>
    </div>
  );
};

const DecisionRow = ({ tone='info', text }) => {
  const c = tone === 'ok' ? 'var(--ok)' : tone === 'warn' ? 'var(--warn)' : 'var(--info)';
  return (
    <div style={{ display:'flex', gap:8, alignItems:'flex-start' }}>
      <span style={{ width:6, height:6, borderRadius:'50%', background:c, marginTop:6, flex:'none' }}/>
      <span style={{ color:'var(--ink-2)' }}>{text}</span>
    </div>
  );
};

window.CompliancePanel = CompliancePanel;
window.Bar = Bar;
window.AxleChart = AxleChart;
window.CogIndicator = CogIndicator;
