/* ===== Palletization module ===== */
const PalletizationScreen = ({ onNavigate }) => {
  const [pallet, setPallet] = React.useState(window.Mojro.PALLETS[0]);
  const [pattern, setPattern] = React.useState('pinwheel');

  const cartons = [
    { id:'c1', sku:'BX-LRG-01', desc:'Apparel · large', qty:14, L:600, W:400, H:400, weight:22, color:'#E8893C' },
    { id:'c2', sku:'BX-MED-04', desc:'Electronics · medium', qty:22, L:500, W:360, H:280, weight:14, color:'#2E5FA8' },
    { id:'c3', sku:'BX-SML-02', desc:'Books · small',    qty: 8, L:300, W:240, H:180, weight:6,  color:'#1F8A5B' },
  ];

  const PATTERNS = [
    { id:'block',    name:'Block',     gain:0,   diag:'block'    },
    { id:'pinwheel', name:'Pinwheel',  gain:12,  diag:'pinwheel' },
    { id:'turned',   name:'Turned',    gain:6,   diag:'turned'   },
    { id:'mixed',    name:'Mixed',     gain:9,   diag:'mixed'    },
  ];

  return (
    <div style={{ height:'100%', display:'grid', gridTemplateColumns:'minmax(260px, 300px) minmax(420px, 1fr) minmax(280px, 300px)', gridTemplateRows:'auto minmax(0, 1fr)', minHeight:0 }}>
      {/* Header */}
      <div style={{ gridColumn:'1 / -1', borderBottom:'1px solid var(--line)', background:'#fff', padding:'10px 16px', display:'flex', alignItems:'center', gap:14 }}>
        <Icon name="pallet" size={18} style={{ color:'#F0B830' }}/>
        <div>
          <div className="h-eyebrow">Palletization</div>
          <div style={{ fontSize:14, fontWeight:700, marginTop:-2 }}>Pallet build · {pallet.name}</div>
        </div>
        <span className="chip">{cartons.length} carton SKUs · 44 pcs</span>
        <span className="chip chip--ok"><span className="dot"/>All stack rules satisfied</span>
        <div style={{ flex:1 }}/>
        <button className="btn btn--sm"><Icon name="report" size={12}/> Loading guide</button>
        <button className="btn btn--sm"><Icon name="download" size={12}/> Export</button>
        <button className="btn btn--sm btn--primary" onClick={() => onNavigate('containerization')}><Icon name="arrow-right" size={12}/> Send to containerization</button>
      </div>

      {/* LEFT — inputs */}
      <div style={{ borderRight:'1px solid var(--line)', background:'#fff', overflow:'auto' }}>
        <SectionTitle>Pallet spec</SectionTitle>
        <div style={{ padding:'8px 14px' }}>
          <div style={{ display:'grid', gridTemplateColumns:'1fr 1fr 1fr', gap:6, marginBottom:8 }}>
            {window.Mojro.PALLETS.map(p => (
              <button key={p.id}
                onClick={() => setPallet(p)}
                style={{
                  padding:'8px 6px', border:'1px solid '+(p.id===pallet.id?'var(--mojro-red)':'var(--line)'),
                  background: p.id===pallet.id?'rgba(193,51,51,0.04)':'#fff',
                  borderRadius:6, cursor:'pointer', textAlign:'left'
                }}>
                <div style={{ fontWeight:600, fontSize:12 }}>{p.name}</div>
                <div className="mono" style={{ fontSize:10.5, color:'var(--ink-3)' }}>{p.L}×{p.W}</div>
              </button>
            ))}
          </div>
          <FormGrid>
            <Field label="Max stack height" value="1800 mm"/>
            <Field label="Max load weight"  value={`${pallet.maxLoad} kg`}/>
            <Field label="Overhang limit"   value="5%"/>
            <Field label="Pallet weight"    value={`${pallet.weight} kg`}/>
          </FormGrid>
        </div>

        <SectionTitle>Stacking pattern</SectionTitle>
        <div style={{ padding:'8px 14px', display:'grid', gridTemplateColumns:'1fr 1fr', gap:8 }}>
          {PATTERNS.map(p => (
            <div key={p.id} onClick={() => setPattern(p.id)} style={{
              border:'1px solid '+(p.id===pattern?'var(--mojro-red)':'var(--line)'),
              borderRadius:6, padding:'8px',
              background: p.id===pattern ? 'rgba(193,51,51,0.04)' : '#fff', cursor:'pointer',
            }}>
              <div style={{ height:54, background:'var(--bg-elev)', borderRadius:4, marginBottom:6, display:'grid', placeItems:'center' }}>
                <PatternDiag pattern={p.diag}/>
              </div>
              <div style={{ display:'flex', justifyContent:'space-between', alignItems:'baseline' }}>
                <span style={{ fontWeight:600, fontSize:12 }}>{p.name}</span>
                <span className="mono" style={{ fontSize:11, color: p.gain>0?'var(--ok)':'var(--ink-3)' }}>
                  {p.gain>0 ? '+'+p.gain+'%' : 'baseline'}
                </span>
              </div>
            </div>
          ))}
        </div>

        <SectionTitle>Cartons / SKUs in build</SectionTitle>
        <div style={{ padding:'4px 0' }}>
          {cartons.map(c => (
            <div key={c.id} style={{ padding:'8px 14px', display:'flex', alignItems:'center', gap:10 }}>
              <span style={{ width:22, height:22, borderRadius:4, background:c.color }}/>
              <div style={{ flex:1, minWidth:0 }}>
                <div style={{ fontSize:12.5, fontWeight:600 }}>{c.sku}</div>
                <div style={{ fontSize:11, color:'var(--ink-3)' }}>{c.desc} · <span className="mono">{c.L}×{c.W}×{c.H}mm</span></div>
              </div>
              <span className="mono" style={{ fontSize:12, fontWeight:600 }}>×{c.qty}</span>
            </div>
          ))}
        </div>
      </div>

      {/* CENTER — pallet view */}
      <div style={{ position:'relative', overflow:'hidden', display:'flex', flexDirection:'column' }}>
        <div style={{ padding:'8px 14px', borderBottom:'1px solid var(--line)', background:'#fff', display:'flex', alignItems:'center', gap:8 }}>
          <SegBtn>{['3d','top','side'].map(v => <SegItem key={v} active={v==='3d'}>{v.toUpperCase()}</SegItem>)}</SegBtn>
          <span style={{ width:1, height:18, background:'var(--line)' }}/>
          <ToggleBtn icon="eye-off" label="X-ray" />
          <ToggleBtn icon="layers" label="Layer view" active />
          <div style={{ flex:1 }}/>
          <button className="btn btn--primary btn--sm"><Icon name="play" size={12}/> Run optimization</button>
        </div>
        <div style={{ flex:1, position:'relative' }}>
          <Scene3D
            items={[
              { id:'p-a', type:'carton', L:600, W:400, H:400, qty:14, color:'#E8893C', category:'general', stop:1 },
              { id:'p-b', type:'carton', L:500, W:360, H:280, qty:22, color:'#2E5FA8', category:'fragile', stop:1 },
              { id:'p-c', type:'box',    L:300, W:240, H:180, qty:8,  color:'#1F8A5B', category:'food',    stop:1 },
            ]}
            container={{ id:'pallet', L: pallet.L, W: pallet.W, H: 1800, maxPayload: pallet.maxLoad }}
            colorMode="item"
          />
          <div style={{ position:'absolute', top:14, left:14, padding:'6px 10px', background:'rgba(255,255,255,0.92)', border:'1px solid var(--line)', borderRadius:6, fontSize:11.5 }}>
            <div className="h-eyebrow" style={{ fontSize:10 }}>Layer · 3 of 5</div>
            <div className="mono" style={{ fontWeight:600 }}>1.32m / 1.80m max</div>
          </div>
        </div>
      </div>

      {/* RIGHT — pallet summary + loading guide preview */}
      <div style={{ borderLeft:'1px solid var(--line)', background:'var(--bg-elev)', overflow:'auto' }}>
        <div style={{ padding:'14px' }}>
          <div className="h-eyebrow">Pallet summary</div>
          <div style={{ display:'grid', gridTemplateColumns:'1fr 1fr', gap:8, marginTop:10 }}>
            <KpiTile label="Cube fill"     value="92%" sub="of 1.92 m³" tone="ok"/>
            <KpiTile label="Weight"        value="0.74t" sub="of 1.5t"  tone="ok"/>
            <KpiTile label="Height used"   value="1.32m" sub="of 1.8m"  tone="ok"/>
            <KpiTile label="Pallet count"  value="3"     sub="EUR EPAL"/>
          </div>
          <div style={{ marginTop:14 }}>
            <Bar label="Volume utilisation" sub="92% · 8% air" value={92} max={100} warnAt={0.7} badAt={0.99}/>
          </div>
          <div style={{ marginTop:10 }}>
            <Bar label="Stack height"      sub="73% of cap"   value={73} max={100} warnAt={0.85} badAt={0.99}/>
          </div>
          <div style={{ marginTop:10 }}>
            <Bar label="Load weight"       sub="49% of cap"   value={49} max={100} warnAt={0.85} badAt={0.99}/>
          </div>
        </div>
        <div style={{ padding:'0 14px 14px' }}>
          <div className="h-eyebrow">Layer-by-layer build</div>
          <div style={{ marginTop:8, display:'flex', flexDirection:'column', gap:6 }}>
            {[
              { layer:1, item:'BX-LRG-01 × 4 + BX-MED-04 × 2', h:'0.40m', tone:'ok' },
              { layer:2, item:'BX-LRG-01 × 4 + BX-MED-04 × 2', h:'0.40m', tone:'ok' },
              { layer:3, item:'BX-LRG-01 × 4 + BX-MED-04 × 4', h:'0.28m', tone:'ok' },
              { layer:4, item:'BX-MED-04 × 8',                 h:'0.28m', tone:'ok' },
              { layer:5, item:'BX-SML-02 × 8',                 h:'0.18m', tone:'warn' },
            ].map(l => (
              <div key={l.layer} style={{
                display:'flex', alignItems:'center', gap:10,
                padding:'8px 10px', background:'#fff', border:'1px solid var(--line)', borderRadius:6
              }}>
                <span style={{ width:24, height:24, borderRadius:4, background:'var(--mojro-maroon)', color:'#fff', display:'grid', placeItems:'center', fontSize:11, fontWeight:600 }}>L{l.layer}</span>
                <div style={{ flex:1, fontSize:12 }}>{l.item}</div>
                <span className="mono" style={{ fontSize:11, color:'var(--ink-3)' }}>{l.h}</span>
              </div>
            ))}
          </div>
          <button className="btn btn--sm" style={{ width:'100%', marginTop:10, justifyContent:'center' }}>
            <Icon name="report" size={12}/> Print loading guide (PDF)
          </button>
        </div>
      </div>
    </div>
  );
};

const SectionTitle = ({ children }) => (
  <div style={{ padding:'12px 14px 4px', fontSize:10.5, color:'var(--ink-3)', textTransform:'uppercase', letterSpacing:'0.1em', fontWeight:600 }}>{children}</div>
);

const Field = ({ label, value }) => (
  <div style={{ display:'flex', flexDirection:'column' }}>
    <span className="field-label">{label}</span>
    <span className="mono" style={{ fontSize:12, fontWeight:600 }}>{value}</span>
  </div>
);

const FormGrid = ({ children }) => (
  <div style={{ display:'grid', gridTemplateColumns:'1fr 1fr', gap:8, padding:'4px 0' }}>{children}</div>
);

window.PalletizationScreen = PalletizationScreen;
