/* ===== Containerization module — the flagship screen ===== */
const ContainerizationScreen = ({ onOpenExcel, showStopOption = true }) => {
  const [container, setContainer] = React.useState(window.Mojro.CONTAINERS[2]); // 40HC
  // Fleet — what containers are available, and how many of each.
  // The currently-selected `container` above is the one being visualized.
  const [fleet, setFleet] = React.useState([
    { id: '40hc',  qty: 1 },
    { id: '40ft',  qty: 2 },
    { id: '20ft',  qty: 1 },
  ]);
  const [addOpen, setAddOpen] = React.useState(false);
  const [cargo, setCargo] = React.useState(window.Mojro.SEED_CARGO);
  const [selectedItemId, setSelectedItemId] = React.useState(null);
  const [anchor, setAnchor] = React.useState(null);
  const [colorMode, setColorMode] = React.useState('item');
  const [viewMode, setViewMode] = React.useState('3d');
  const [xray, setXray] = React.useState(false);
  const [layerSlice, setLayerSlice] = React.useState(1.0);
  const [showAxleOverlay, setShowAxleOverlay] = React.useState(true);
  const [violations] = React.useState(window.Mojro.SEED_VIOLATIONS);
  const [activeTab, setActiveTab] = React.useState('manifest'); // manifest | special | constraints
  const [showPatterns, setShowPatterns] = React.useState(false);

  // If Tweaks hides the 'stop' colour mode while it's selected, fall back.
  React.useEffect(() => {
    if (!showStopOption && colorMode === 'stop') setColorMode('item');
  }, [showStopOption, colorMode]);

  // tag violations onto items
  const cargoTagged = React.useMemo(() => {
    return cargo.map(c => {
      const v = violations.find(v => v.item === c.id);
      return v ? { ...c, violation: v.severity } : c;
    });
  }, [cargo, violations]);

  const selectedItem = cargoTagged.find(c => c.id === selectedItemId);

  // demo KPIs / axles
  const kpis = { volumePct: 87, deadAir: 13, weight: 24.8, weightMax: 28.6, items: 76, skus: 8, containerCount: 1, cogX: 0.46, cogY: 0.52 };
  const axles = [
    { name: 'Steer',   load: 5.4,  limit: 7.5 },
    { name: 'Drive',   load: 10.6, limit: 11.5 },
    { name: 'Tandem',  load: 8.8,  limit: 9.5 },
  ];

  const handleSelectFromScene = (id, pos) => {
    setSelectedItemId(id);
    setAnchor(pos);
  };

  return (
    <div style={{ height:'100%', display:'grid', gridTemplateColumns:'minmax(260px, 300px) minmax(420px, 1fr) minmax(290px, 320px)', gridTemplateRows:'auto minmax(0, 1fr)', minHeight:0 }}>
      {/* Header bar */}
      <div style={{ gridColumn:'1 / -1', borderBottom:'1px solid var(--line)', background:'var(--bg-card)', padding:'10px 16px', display:'flex', alignItems:'center', gap:12, minWidth:0 }}>
        <Icon name="container" size={18} style={{ color:'var(--mojro-red)', flex:'none' }}/>
        <div style={{ minWidth:0 }}>
          <div style={{ fontSize:11, color:'var(--ink-3)', textTransform:'uppercase', letterSpacing:'0.08em' }}>Containerization</div>
          <div style={{ fontSize:14, fontWeight:700, marginTop:-2, whiteSpace:'nowrap', overflow:'hidden', textOverflow:'ellipsis' }}>
            New plan <span style={{ color:'var(--ink-4)', fontWeight:400 }}>· {container.name}</span>
          </div>
        </div>
        <div style={{ display:'flex', gap:6, marginLeft:6, flex:'none' }}>
          <span className="chip chip--ok"><span className="dot"/>autosaved · 12:42</span>
          <span className="chip">m / kg</span>
        </div>
        <div style={{ flex:1 }}/>
        <button className="btn btn--sm btn--icon" title="Share"><Icon name="share" size={13}/></button>
        <button className="btn btn--sm btn--icon" title="Export"><Icon name="download" size={13}/></button>
        <button className="btn btn--sm btn--icon" title="History"><Icon name="history" size={13}/></button>
        <button className="btn btn--primary btn--sm"><Icon name="play" size={12}/> Run optimization</button>
      </div>

      {/* LEFT — Cargo manifest / inputs */}
      <div style={{ borderRight:'1px solid var(--line)', background:'var(--bg-card)', display:'flex', flexDirection:'column', minHeight:0 }}>
        {/* Container picker */}
        <div style={{ padding:'14px 14px', borderBottom:'1px solid var(--line)' }}>
          <div className="h-eyebrow" style={{ marginBottom:8, display:'flex', alignItems:'center' }}>
            <span>Container / vehicle</span>
            <span className="mono" style={{ marginLeft:'auto', fontSize:10.5, color:'var(--ink-3)' }}>
              {fleet.reduce((s, r) => s + r.qty, 0)} available · {fleet.length} type{fleet.length === 1 ? '' : 's'}
            </span>
          </div>

          {/* Selected container — visualised in the canvas */}
          <div style={{ padding:'10px 12px', border:'1px solid var(--mojro-red)', borderRadius:8, background:'rgba(193,51,51,0.04)' }}>
            <div style={{ display:'flex', alignItems:'baseline', gap:8 }}>
              <strong style={{ fontSize:14 }}>{container.name}</strong>
              <span className="chip">{container.id.toUpperCase()}</span>
              <span style={{ marginLeft:'auto', fontSize:10.5, color:'var(--ink-3)', textTransform:'uppercase', letterSpacing:'0.08em' }}>viewing</span>
            </div>
            <div style={{ display:'grid', gridTemplateColumns:'1fr 1fr 1fr', gap:8, marginTop:8 }}>
              <Stat label="L" value={`${(container.L/1000).toFixed(2)}m`}/>
              <Stat label="W" value={`${(container.W/1000).toFixed(2)}m`}/>
              <Stat label="H" value={`${(container.H/1000).toFixed(2)}m`}/>
            </div>
            <div style={{ display:'grid', gridTemplateColumns:'1fr 1fr', gap:8, marginTop:6 }}>
              <Stat label="Max payload" value={`${(container.maxPayload/1000).toFixed(1)}t`}/>
              <Stat label="Internal vol." value="73.5 m³"/>
            </div>
          </div>

          {/* Fleet — rows of {type, qty} */}
          <div style={{ marginTop:10, display:'flex', flexDirection:'column', gap:6 }}>
            <div style={{ fontSize:10.5, color:'var(--ink-3)', textTransform:'uppercase', letterSpacing:'0.08em' }}>Fleet</div>
            {fleet.map(row => {
              const c = window.Mojro.CONTAINERS.find(x => x.id === row.id);
              if (!c) return null;
              const isViewing = c.id === container.id;
              return (
                <FleetRow
                  key={row.id}
                  container={c}
                  qty={row.qty}
                  viewing={isViewing}
                  onView={() => setContainer(c)}
                  onQty={(next) => setFleet(f => f.map(r => r.id === row.id ? { ...r, qty: Math.max(0, next) } : r))}
                  onRemove={() => {
                    setFleet(f => {
                      const nf = f.filter(r => r.id !== row.id);
                      if (isViewing && nf.length) {
                        const nc = window.Mojro.CONTAINERS.find(x => x.id === nf[0].id);
                        if (nc) setContainer(nc);
                      }
                      return nf;
                    });
                  }}
                />
              );
            })}

            {/* Add container — dropdown of types not yet in fleet */}
            <div style={{ position:'relative' }}>
              <button
                className="btn btn--sm"
                style={{ width:'100%', justifyContent:'center', borderStyle:'dashed' }}
                onClick={() => setAddOpen(o => !o)}
                disabled={fleet.length >= window.Mojro.CONTAINERS.length}
              >
                <Icon name="plus" size={12}/> Add container
              </button>
              {addOpen && (
                <div style={{
                  position:'absolute', left:0, right:0, top:'calc(100% + 4px)', zIndex:10,
                  background:'var(--bg-card)', border:'1px solid var(--line)', borderRadius:8,
                  boxShadow:'var(--sh-md)', overflow:'hidden'
                }}>
                  {window.Mojro.CONTAINERS
                    .filter(c => !fleet.find(r => r.id === c.id))
                    .map(c => (
                      <button
                        key={c.id}
                        onClick={() => {
                          setFleet(f => [...f, { id: c.id, qty: 1 }]);
                          setAddOpen(false);
                        }}
                        style={{
                          display:'flex', alignItems:'center', gap:8, width:'100%',
                          padding:'8px 10px', background:'transparent', border:'none',
                          textAlign:'left', cursor:'pointer', fontSize:12,
                          borderBottom:'1px solid var(--line)'
                        }}
                        onMouseEnter={e => e.currentTarget.style.background = 'var(--bg-elev)'}
                        onMouseLeave={e => e.currentTarget.style.background = 'transparent'}
                      >
                        <Icon name="container" size={13} style={{ color:'var(--ink-3)' }}/>
                        <span style={{ flex:1 }}>{c.name}</span>
                        <span className="mono" style={{ fontSize:10.5, color:'var(--ink-3)' }}>
                          {(c.L/1000).toFixed(1)}×{(c.W/1000).toFixed(1)}×{(c.H/1000).toFixed(1)}m
                        </span>
                      </button>
                    ))}
                  {window.Mojro.CONTAINERS.filter(c => !fleet.find(r => r.id === c.id)).length === 0 && (
                    <div style={{ padding:'10px 12px', fontSize:11.5, color:'var(--ink-3)' }}>All container types added.</div>
                  )}
                </div>
              )}
            </div>
          </div>
        </div>

        {/* Tabs */}
        <div style={{ display:'flex', padding:'0 14px', borderBottom:'1px solid var(--line)', gap:0 }}>
          {[
            { id:'manifest',    label:'Cargo',         count: cargo.length },
            { id:'special',     label:'Special modes', count: 3 },
            { id:'constraints', label:'Constraints',   count: 7 },
          ].map(t => (
            <button key={t.id}
              onClick={() => setActiveTab(t.id)}
              style={{
                background:'transparent', border:'none', padding:'10px 4px', marginRight:14,
                fontSize:12.5, fontWeight: activeTab===t.id ? 600 : 500,
                color: activeTab===t.id ? 'var(--ink-1)' : 'var(--ink-3)',
                borderBottom: activeTab===t.id ? '2px solid var(--mojro-red)' : '2px solid transparent',
                cursor:'pointer',
              }}>
              {t.label} <span className="mono" style={{ color:'var(--ink-4)', fontSize:11 }}>{t.count}</span>
            </button>
          ))}
        </div>

        {/* Tab content */}
        <div style={{ flex:1, overflow:'auto', minHeight:0 }}>
          {activeTab === 'manifest' && (
            <CargoManifestPanel cargo={cargoTagged} selectedId={selectedItemId} onSelect={setSelectedItemId} onOpenExcel={onOpenExcel}/>
          )}
          {activeTab === 'special' && <SpecialModesPanel/>}
          {activeTab === 'constraints' && <ConstraintsPanel/>}
        </div>
      </div>

      {/* CENTER — 3D canvas */}
      <div style={{ position:'relative', overflow:'hidden', display:'flex', flexDirection:'column', minHeight:0 }}>
        {/* canvas toolbar */}
        <CanvasToolbar
          colorMode={colorMode} onColorMode={setColorMode}
          viewMode={viewMode}   onViewMode={setViewMode}
          xray={xray} onXray={setXray}
          showAxleOverlay={showAxleOverlay} onShowAxleOverlay={setShowAxleOverlay}
          onTogglePatterns={() => setShowPatterns(true)}
          showStopOption={showStopOption}
        />

        {/* 3D area */}
        <div style={{ position:'relative', flex:1, minHeight:0 }}>
          <Scene3D
            items={cargoTagged}
            container={container}
            colorMode={colorMode}
            selectedId={selectedItemId}
            onSelect={handleSelectFromScene}
            viewMode={viewMode}
            xray={xray}
            layerSlice={layerSlice}
          />
          {/* layer slice slider */}
          <div style={{ position:'absolute', right:14, top:60, bottom:120, width:36, display:'flex', flexDirection:'column', alignItems:'center', background:'rgba(255,255,255,0.85)', border:'1px solid var(--line)', borderRadius:8, padding:'8px 0', backdropFilter:'blur(8px)' }}>
            <Icon name="layers" size={14} style={{ color:'var(--ink-3)' }}/>
            <input type="range" min="0.1" max="1" step="0.05" value={layerSlice} onChange={e => setLayerSlice(parseFloat(e.target.value))}
              style={{ writingMode:'bt-lr', WebkitAppearance:'slider-vertical', width:8, flex:1, margin:'8px 0' }}/>
            <span className="mono" style={{ fontSize:10, color:'var(--ink-3)' }}>{Math.round(layerSlice*100)}%</span>
          </div>

          {/* Floating axle overlay (top-view) */}
          {showAxleOverlay && viewMode === 'top' && (
            <AxleOverlay container={container}/>
          )}

          {/* Color legend */}
          <ColorLegend mode={colorMode} cargo={cargoTagged}/>

          {/* coords display */}
          <div style={{ position:'absolute', bottom:14, left:14, padding:'6px 10px', background:'rgba(255,255,255,0.92)', border:'1px solid var(--line)', borderRadius:6, fontSize:11, color:'var(--ink-3)', display:'flex', alignItems:'center', gap:10 }}>
            <Icon name="measure" size={11}/>
            <span>L drag · orbit</span>
            <span style={{ color:'var(--ink-4)' }}>|</span>
            <span>Shift+drag · pan</span>
            <span style={{ color:'var(--ink-4)' }}>|</span>
            <span>scroll · zoom</span>
            <span style={{ color:'var(--ink-4)' }}>|</span>
            <span>click · inspect</span>
          </div>

          {selectedItem && (
            <ItemDetailCard
              item={selectedItem}
              anchor={anchor}
              violations={violations}
              onClose={() => { setSelectedItemId(null); setAnchor(null); }}
              onLock={() => setCargo(c => c.map(i => i.id===selectedItem.id ? {...i, locked: !i.locked} : i))}
              onRemove={() => { setCargo(c => c.filter(i => i.id !== selectedItem.id)); setSelectedItemId(null); }}
            />
          )}

          {showPatterns && <PatternPicker onClose={() => setShowPatterns(false)}/>}
        </div>
      </div>

      {/* RIGHT — compliance panel */}
      <CompliancePanel kpis={kpis} axles={axles} violations={violations} onSelectItem={setSelectedItemId}/>
    </div>
  );
};

/* -------- subcomponents -------- */

const Stat = ({ label, value }) => (
  <div>
    <div style={{ fontSize:10, color:'var(--ink-3)', textTransform:'uppercase', letterSpacing:'0.06em' }}>{label}</div>
    <div className="mono" style={{ fontSize:13, fontWeight:600 }}>{value}</div>
  </div>
);

const FleetRow = ({ container, qty, viewing, onView, onQty, onRemove }) => (
  <div style={{
    display:'flex', alignItems:'center', gap:8,
    padding:'7px 8px 7px 10px',
    background:'var(--bg-card)',
    border:'1px solid ' + (viewing ? 'var(--mojro-red)' : 'var(--line)'),
    borderRadius:7,
    boxShadow: viewing ? '0 0 0 2px rgba(193,51,51,0.08)' : 'none',
  }}>
    <button
      onClick={onView}
      title={viewing ? 'Currently visualized' : 'Visualize this container'}
      style={{
        flex:1, minWidth:0, display:'flex', flexDirection:'column', alignItems:'flex-start',
        gap:1, background:'transparent', border:'none', padding:0, cursor:'pointer', textAlign:'left',
      }}>
      <span style={{ fontSize:12, fontWeight:600, whiteSpace:'nowrap', overflow:'hidden', textOverflow:'ellipsis', maxWidth:'100%' }}>
        {container.name}
      </span>
      <span className="mono" style={{ fontSize:10.5, color:'var(--ink-3)' }}>
        {(container.L/1000).toFixed(1)}×{(container.W/1000).toFixed(1)}×{(container.H/1000).toFixed(1)}m · {(container.maxPayload/1000).toFixed(1)}t
      </span>
    </button>

    {/* Qty stepper */}
    <div style={{ display:'flex', alignItems:'center', border:'1px solid var(--line)', borderRadius:6, overflow:'hidden', background:'var(--bg-elev)' }}>
      <button
        onClick={() => onQty(qty - 1)}
        disabled={qty <= 0}
        style={{ width:22, height:22, border:'none', background:'transparent', cursor: qty<=0 ? 'not-allowed' : 'pointer', color: qty<=0 ? 'var(--ink-4)' : 'var(--ink-2)', fontSize:14, lineHeight:1 }}
        aria-label="Decrease quantity"
      >−</button>
      <span className="mono" style={{ width:24, textAlign:'center', fontSize:12, fontWeight:600 }}>{qty}</span>
      <button
        onClick={() => onQty(qty + 1)}
        style={{ width:22, height:22, border:'none', background:'transparent', cursor:'pointer', color:'var(--ink-2)', fontSize:14, lineHeight:1 }}
        aria-label="Increase quantity"
      >+</button>
    </div>

    <button
      onClick={onRemove}
      title="Remove from fleet"
      className="btn btn--sm btn--icon"
      style={{ padding:'3px 5px', color:'var(--ink-3)' }}
    >
      <Icon name="trash" size={12}/>
    </button>
  </div>
);

const CargoManifestPanel = ({ cargo, selectedId, onSelect, onOpenExcel }) => {
  const [filter, setFilter] = React.useState('all');
  const filtered = filter === 'all' ? cargo : cargo.filter(c => c.tag.toLowerCase() === filter);
  return (
    <div>
      <div style={{ padding:'10px 14px', display:'flex', gap:6, alignItems:'center', borderBottom:'1px solid var(--line)' }}>
        <div style={{ position:'relative', flex:1 }}>
          <Icon name="search" size={12} style={{ position:'absolute', left:8, top:8, color:'var(--ink-4)' }}/>
          <input className="input" placeholder="Search SKU or description" style={{ paddingLeft:26, fontSize:12, padding:'5px 10px 5px 26px' }}/>
        </div>
        <button className="btn btn--sm btn--icon" title="Filter"><Icon name="filter" size={12}/></button>
      </div>
      <div style={{ padding:'8px 14px', display:'flex', gap:4, borderBottom:'1px solid var(--line)' }}>
        {['all','pallet','carton','sku','barrel','pipe'].map(f => (
          <button key={f}
            onClick={() => setFilter(f)}
            className={"chip" + (filter===f ? ' chip--dark' : '')}
            style={{ cursor:'pointer', textTransform:'capitalize', background: filter===f ? 'var(--bg-chrome-2)' : undefined, color: filter===f ? 'var(--ink-on-dark)' : undefined }}>
            {f}
          </button>
        ))}
      </div>

      <div style={{ padding:'4px 0' }}>
        {filtered.map(item => (
          <CargoRow key={item.id} item={item} selected={selectedId===item.id} onClick={() => onSelect(item.id)}/>
        ))}
      </div>

      <div style={{ padding:'10px 14px', display:'flex', gap:6, borderTop:'1px solid var(--line)' }}>
        <button className="btn btn--sm" style={{ flex:1 }}><Icon name="plus" size={12}/> Add row</button>
        <button className="btn btn--sm" style={{ flex:1 }} onClick={onOpenExcel}><Icon name="upload" size={12}/> Upload Excel</button>
      </div>

      <div style={{ padding:'10px 14px', background:'var(--bg-elev)', borderTop:'1px solid var(--line)' }}>
        <div style={{ display:'flex', alignItems:'center', gap:8, marginBottom:6 }}>
          <Icon name="info" size={12} style={{ color:'var(--info)' }}/>
          <span style={{ fontSize:11.5, color:'var(--ink-2)' }}>This manifest accepts <b>any combination</b> of pallets, cartons, SKUs and special cargo in one session.</span>
        </div>
      </div>
    </div>
  );
};

const CargoRow = ({ item, selected, onClick }) => {
  const cat = window.Mojro.CATEGORIES.find(c => c.id === item.category);
  return (
    <div
      onClick={onClick}
      style={{
        display:'flex', alignItems:'center', gap:10,
        padding:'8px 14px', cursor:'pointer',
        background: selected ? 'rgba(193,51,51,0.06)' : 'transparent',
        borderLeft: selected ? '2px solid var(--mojro-red)' : '2px solid transparent',
      }}
      onMouseEnter={e=>{ if(!selected) e.currentTarget.style.background='rgba(0,0,0,0.025)';}}
      onMouseLeave={e=>{ if(!selected) e.currentTarget.style.background='transparent';}}
    >
      <span style={{ width:24, height:24, borderRadius:5, background: item.color, color:'#fff', display:'grid', placeItems:'center', flex:'none' }}>
        <Icon name={window.Mojro.CARGO_TYPE_ICONS[item.type] || 'box'} size={13}/>
      </span>
      <div style={{ flex:1, minWidth:0 }}>
        <div style={{ display:'flex', alignItems:'center', gap:4 }}>
          <span style={{ fontSize:12.5, fontWeight:600, whiteSpace:'nowrap', overflow:'hidden', textOverflow:'ellipsis' }}>{item.sku}</span>
          {item.locked && <Icon name="lock" size={10} style={{ color:'var(--ink-3)' }}/>}
          {item.violation === 'bad'  && <Icon name="warning" size={10} style={{ color:'var(--bad)' }}/>}
          {item.violation === 'warn' && <Icon name="warning" size={10} style={{ color:'var(--warn)' }}/>}
        </div>
        <div style={{ fontSize:11, color:'var(--ink-3)', whiteSpace:'nowrap', overflow:'hidden', textOverflow:'ellipsis' }}>
          {item.desc}
        </div>
      </div>
      <div style={{ display:'flex', flexDirection:'column', alignItems:'flex-end' }}>
        <span className="mono" style={{ fontSize:12, fontWeight:600 }}>×{item.qty}</span>
        <span style={{ fontSize:10, color: cat?.color, fontWeight:500 }}>{cat?.name}</span>
      </div>
    </div>
  );
};

const CanvasToolbar = ({ colorMode, onColorMode, viewMode, onViewMode, xray, onXray, showAxleOverlay, onShowAxleOverlay, onTogglePatterns, showStopOption = true }) => (
  /* `showStopOption` (Tweaks) removes the “Stop” entry from the Colour-by segment. */
  <div style={{
    padding:'8px 14px', borderBottom:'1px solid var(--line)', background:'var(--bg-card)',
    display:'flex', alignItems:'center', gap:8, flexWrap:'wrap'
  }}>
    {/* view modes */}
    <SegBtn>
      {['3d','top','side'].map(v => (
        <SegItem key={v} active={viewMode===v} onClick={() => onViewMode(v)}>{v.toUpperCase()}</SegItem>
      ))}
    </SegBtn>

    <span style={{ width:1, height:18, background:'var(--line)' }}/>

    {/* color mode */}
    <span style={{ fontSize:11, color:'var(--ink-3)' }}>Colour by</span>
    <SegBtn>
      {[
        ['item','SKU'], ['category','Category'], ['weight','Weight'],
        ...(showStopOption ? [['stop','Stop']] : [])
      ].map(([id,label]) => (
        <SegItem key={id} active={colorMode===id} onClick={() => onColorMode(id)}>{label}</SegItem>
      ))}
    </SegBtn>

    <span style={{ width:1, height:18, background:'var(--line)' }}/>

    {/* feature toggles */}
    <ToggleBtn icon="eye-off" label="X-ray" active={xray} onClick={() => onXray(!xray)} />
    <ToggleBtn icon="axle" label="Axle overlay" active={showAxleOverlay} onClick={() => onShowAxleOverlay(!showAxleOverlay)} />
    <button className="btn btn--sm" onClick={onTogglePatterns}><Icon name="grid" size={12}/> Loading patterns</button>

    <div style={{ flex:1 }}/>

    {/* right side */}
    <button className="btn btn--sm btn--icon" title="Undo"><Icon name="rotate" size={13}/></button>
    <button className="btn btn--sm btn--icon" title="Measure"><Icon name="measure" size={13}/></button>
    <button className="btn btn--sm btn--icon" title="Fullscreen"><Icon name="expand" size={13}/></button>
  </div>
);

const SegBtn = ({ children }) => (
  <div style={{ display:'flex', background:'var(--bg-elev)', border:'1px solid var(--line)', borderRadius:6, padding:2, gap:1 }}>
    {children}
  </div>
);
const SegItem = ({ active, children, onClick }) => (
  <button onClick={onClick} style={{
    padding:'3px 9px', borderRadius:4, border:'none',
    background: active ? 'var(--bg-card)' : 'transparent',
    boxShadow: active ? 'var(--sh-sm)' : 'none',
    color: active ? 'var(--ink-1)' : 'var(--ink-3)',
    fontSize: 11.5, fontWeight: active ? 600 : 500, cursor:'pointer'
  }}>{children}</button>
);
const ToggleBtn = ({ icon, label, active, onClick }) => (
  <button onClick={onClick} className="btn btn--sm" style={{
    background: active ? 'var(--mojro-maroon)' : 'var(--bg-card)',
    color: active ? '#fff' : 'var(--ink-1)',
    borderColor: active ? 'var(--mojro-maroon)' : 'var(--line-strong)',
  }}>
    <Icon name={icon} size={12}/> {label}
  </button>
);

const ColorLegend = ({ mode, cargo }) => {
  let items = [];
  if (mode === 'item') {
    items = cargo.slice(0, 6).map(c => ({ color: c.color, label: c.sku }));
  } else if (mode === 'category') {
    items = window.Mojro.CATEGORIES.map(c => ({ color: c.color, label: c.name }));
  } else if (mode === 'stop') {
    items = [
      { color:'#C13333', label:'Stop 1 (rear)' },
      { color:'#E8893C', label:'Stop 2' },
      { color:'#F0B830', label:'Stop 3' },
    ];
  } else { // weight gradient
    return (
      <div style={{ position:'absolute', bottom:14, right:14, background:'rgba(255,255,255,0.92)', padding:'8px 10px', borderRadius:6, border:'1px solid var(--line)', fontSize:11 }}>
        <div style={{ fontSize:10, color:'var(--ink-3)', textTransform:'uppercase', letterSpacing:'0.08em', marginBottom:4 }}>Weight contribution</div>
        <div style={{ display:'flex', alignItems:'center', gap:6 }}>
          <span style={{ color:'var(--ink-3)' }}>light</span>
          <div style={{ width:120, height:8, background:'linear-gradient(90deg,#2E5FA8,#F0B830,#C13333)', borderRadius:4 }}/>
          <span style={{ color:'var(--ink-3)' }}>heavy</span>
        </div>
      </div>
    );
  }
  return (
    <div style={{ position:'absolute', bottom:14, right:14, background:'rgba(255,255,255,0.92)', padding:'8px 10px', borderRadius:6, border:'1px solid var(--line)', fontSize:11 }}>
      <div style={{ fontSize:10, color:'var(--ink-3)', textTransform:'uppercase', letterSpacing:'0.08em', marginBottom:6 }}>Legend · by {mode}</div>
      <div style={{ display:'flex', flexDirection:'column', gap:3 }}>
        {items.map(i => (
          <div key={i.label} style={{ display:'flex', alignItems:'center', gap:6 }}>
            <span style={{ width:10, height:10, borderRadius:2, background:i.color }}/>
            <span style={{ fontSize:11.5 }}>{i.label}</span>
          </div>
        ))}
      </div>
    </div>
  );
};

const AxleOverlay = ({ container }) => (
  <div style={{ position:'absolute', inset:0, pointerEvents:'none' }}>
    {/* placeholder: in real product overlays anchor on top-view of container */}
    <div style={{ position:'absolute', left:'15%', right:'15%', top:'40%', bottom:'40%', border:'2px dashed rgba(193,51,51,0.55)', borderRadius:4, display:'flex', alignItems:'flex-start', justifyContent:'flex-end', padding:6 }}>
      <span className="chip chip--warn" style={{ fontSize:10 }}>Drive axle zone · 10.6t</span>
    </div>
  </div>
);

const SpecialModesPanel = () => (
  <div style={{ padding:'12px 14px', display:'flex', flexDirection:'column', gap:14 }}>
    <SpecialCard
      title="Pipe loading"
      icon="pipe"
      desc="Steel pipes, profiles, beams"
      modes={[
        { id:'end',  label:'End-loading',  desc:'Parallel to length',     pieces:'120 pcs', selected:true },
        { id:'side', label:'Side-loading', desc:'Cross-loaded on bunks', pieces:'92 pcs',  selected:false },
      ]}
      footer="Chocks/dunnage at 600mm intervals · 12 bundles"
    />
    <SpecialCard
      title="Barrel loading"
      icon="barrel"
      desc="Drums, kegs, cylinders"
      modes={[
        { id:'up',   label:'Upright',     desc:'Bung-up · stackable',         pieces:'44 drums', selected:true },
        { id:'hor',  label:'Horizontal',  desc:'Pyramid stack 8-7-6-5', pieces:'26 drums', selected:false },
      ]}
      footer="Saddle wedges placed at base · cradle braces every 4 drums"
    />
    <SpecialCard
      title="Roll / cylinder loading"
      icon="roll"
      desc="Paper rolls, cable spools"
      modes={[
        { id:'par',   label:'Axis · parallel',      desc:'Parallel to travel',     pieces:'18 rolls', selected:false },
        { id:'perp',  label:'Axis · perpendicular', desc:'Cross-loaded',            pieces:'22 rolls', selected:true },
      ]}
      footer="Saddle blocks under every roll; no-roll wedges at ends"
    />
  </div>
);

const SpecialCard = ({ title, icon, desc, modes, footer }) => (
  <div className="card" style={{ padding:'10px 12px' }}>
    <div style={{ display:'flex', alignItems:'center', gap:8 }}>
      <Icon name={icon} size={16} style={{ color:'var(--mojro-red)' }}/>
      <div>
        <div style={{ fontWeight:600, fontSize:13 }}>{title}</div>
        <div style={{ fontSize:11, color:'var(--ink-3)' }}>{desc}</div>
      </div>
    </div>
    <div style={{ display:'grid', gridTemplateColumns:'1fr 1fr', gap:6, marginTop:10 }}>
      {modes.map(m => (
        <div key={m.id} style={{
          padding:'8px 10px',
          border:'1px solid ' + (m.selected ? 'var(--mojro-red)' : 'var(--line)'),
          background: m.selected ? 'rgba(193,51,51,0.05)' : 'transparent',
          borderRadius:6, cursor:'pointer'
        }}>
          <div style={{ fontWeight:600, fontSize:12 }}>{m.label}</div>
          <div style={{ fontSize:11, color:'var(--ink-3)', marginTop:1 }}>{m.desc}</div>
          <div className="mono" style={{ fontSize:11, color: m.selected ? 'var(--mojro-red)' : 'var(--ink-2)', marginTop:4, fontWeight:600 }}>{m.pieces}</div>
        </div>
      ))}
    </div>
    <div style={{ marginTop:8, padding:'6px 8px', background:'var(--bg-elev)', borderRadius:5, fontSize:11.5, color:'var(--ink-3)' }}>{footer}</div>
  </div>
);

const ConstraintsPanel = () => (
  <div style={{ padding:'12px 14px', display:'flex', flexDirection:'column', gap:10 }}>
    <ConstraintRow on  type="Segregation" label="Hazmat ⤬ Food separation" detail="600 mm · enforced"/>
    <ConstraintRow on  type="Weight"      label="Heaviest items on bottom" detail="auto-applied"/>
    <ConstraintRow on  type="Axle"        label="Drive axle limit 11.5t"   detail="legal · DE/AT/FR"/>
    <ConstraintRow on  type="CoG"         label="CoG within 40-60% from front"/>
    <ConstraintRow on  type="Sequence"    label="LIFO loading by stop"     detail="stop 1 last in"/>
    <ConstraintRow on  type="Overhang"    label="≤ 5% off pallet edge"/>
    <ConstraintRow off type="Floor"       label="Floor strength 4500 kg/m²"/>
    <button className="btn btn--sm" style={{ marginTop:6 }}><Icon name="plus" size={12}/> Add constraint</button>
  </div>
);

const ConstraintRow = ({ on, type, label, detail }) => (
  <div style={{ padding:'8px 10px', border:'1px solid var(--line)', borderRadius:6, display:'flex', alignItems:'center', gap:8, background: on ? '#fff' : 'var(--bg-elev)' }}>
    <span className="chip" style={{ minWidth:78, justifyContent:'center', fontSize:10 }}>{type}</span>
    <div style={{ flex:1 }}>
      <div style={{ fontSize:12.5, fontWeight: on ? 500 : 400, color: on ? 'var(--ink-1)' : 'var(--ink-3)' }}>{label}</div>
      {detail && <div style={{ fontSize:11, color:'var(--ink-3)' }}>{detail}</div>}
    </div>
    <Toggle on={on}/>
  </div>
);

const Toggle = ({ on }) => (
  <div style={{
    width:28, height:16, borderRadius:8, padding:1.5,
    background: on ? 'var(--mojro-red)' : '#cdc3b8',
    display:'flex', alignItems:'center',
    transition:'background 120ms',
  }}>
    <div style={{
      width:13, height:13, borderRadius:'50%', background:'#fff',
      transform: `translateX(${on?12:0}px)`,
      transition:'transform 120ms',
      boxShadow: 'var(--sh-sm)',
    }}/>
  </div>
);

// Loading pattern picker (modal-like floating card)
const PatternPicker = ({ onClose }) => {
  const PATTERNS = [
    { id:'straight', name:'Straight',  diag: <PatternDiag pattern="straight"/>,  util: 78 },
    { id:'turned',   name:'Turned 90°', diag: <PatternDiag pattern="turned"/>,    util: 73 },
    { id:'pinwheel', name:'Pinwheel',   diag: <PatternDiag pattern="pinwheel"/>,  util: 87, best: true },
    { id:'mixed',    name:'Mixed',      diag: <PatternDiag pattern="mixed"/>,     util: 84 },
  ];
  const [sel, setSel] = React.useState('pinwheel');
  return (
    <div style={{ position:'absolute', top:60, right:60, zIndex:20, background:'#fff', border:'1px solid var(--line)', borderRadius:10, boxShadow:'var(--sh-pop)', width:540 }}>
      <div style={{ padding:'12px 14px', display:'flex', alignItems:'center', borderBottom:'1px solid var(--line)' }}>
        <div>
          <div style={{ fontWeight:700, fontSize:14 }}>Pallet loading pattern</div>
          <div style={{ fontSize:12, color:'var(--ink-3)' }}>EUR pallets · 18 in load · 40ft HC</div>
        </div>
        <button className="btn btn--icon btn--ghost" style={{ marginLeft:'auto' }} onClick={onClose}><Icon name="x" size={14}/></button>
      </div>
      <div style={{ padding:14, display:'grid', gridTemplateColumns:'repeat(4, 1fr)', gap:8 }}>
        {PATTERNS.map(p => (
          <div key={p.id} onClick={() => setSel(p.id)} style={{
            border:'1px solid ' + (sel===p.id ? 'var(--mojro-red)' : 'var(--line)'),
            borderRadius:8, padding:'8px 10px',
            background: sel===p.id ? 'rgba(193,51,51,0.04)' : '#fff', cursor:'pointer',
            position:'relative',
          }}>
            {p.best && <span className="chip chip--ok" style={{ position:'absolute', top:6, right:6, fontSize:10 }}>Best</span>}
            <div style={{ height:60, background:'var(--bg-elev)', borderRadius:5, padding:6, marginBottom:6, display:'grid', placeItems:'center' }}>
              {p.diag}
            </div>
            <div style={{ fontWeight:600, fontSize:12.5 }}>{p.name}</div>
            <div style={{ display:'flex', alignItems:'baseline', gap:4, marginTop:2 }}>
              <span className="mono" style={{ fontWeight:700 }}>{p.util}%</span>
              <span style={{ fontSize:11, color:'var(--ink-3)' }}>utilisation</span>
            </div>
          </div>
        ))}
      </div>
      <div style={{ padding:'10px 14px', display:'flex', alignItems:'center', gap:8, borderTop:'1px solid var(--line)' }}>
        <span style={{ fontSize:12, color:'var(--ink-3)' }}>Pinwheel +9% density vs straight</span>
        <button className="btn" style={{ marginLeft:'auto' }} onClick={onClose}>Cancel</button>
        <button className="btn btn--primary" onClick={onClose}>Apply pattern</button>
      </div>
    </div>
  );
};

const PatternDiag = ({ pattern }) => {
  // 60x48 viewBox top-view
  const rect = (x,y,w,h,rot=0) => <rect key={`${x}-${y}-${rot}`} x={x} y={y} width={w} height={h} fill="#C13333" opacity="0.85" transform={rot?`rotate(${rot} ${x+w/2} ${y+h/2})`:''}/>;
  switch(pattern) {
    case 'straight':
      return (<svg viewBox="0 0 60 48" width="100%" height="100%">
        <rect x="0" y="0" width="60" height="48" fill="#efe8df"/>
        {[0,1,2].map(c => [0,1].map(r => rect(2+c*20, 4+r*22, 16, 18)))}
      </svg>);
    case 'turned':
      return (<svg viewBox="0 0 60 48" width="100%" height="100%">
        <rect x="0" y="0" width="60" height="48" fill="#efe8df"/>
        {[0,1,2,3,4].map(c => rect(2+c*12, 12, 10, 24))}
      </svg>);
    case 'pinwheel':
      return (<svg viewBox="0 0 60 48" width="100%" height="100%">
        <rect x="0" y="0" width="60" height="48" fill="#efe8df"/>
        {/* alternating straight + turned */}
        {rect(2,4,16,18)}{rect(2,26,16,18)}
        {rect(20,4,10,40)}
        {rect(32,4,16,18)}{rect(32,26,16,18)}
      </svg>);
    case 'mixed':
      return (<svg viewBox="0 0 60 48" width="100%" height="100%">
        <rect x="0" y="0" width="60" height="48" fill="#efe8df"/>
        {rect(2,4,16,18)}{rect(2,26,16,18)}
        {rect(20,4,16,18)}{rect(20,26,16,18)}
        {rect(38,4,10,18)}{rect(50,4,10,18)}
        {rect(40,28,16,16)}
      </svg>);
  }
};

window.ContainerizationScreen = ContainerizationScreen;
