/* ===== Rules configuration screen — matrix + constraint editor ===== */
const RulesScreen = ({ onOpenExcel }) => {
  const [matrix, setMatrix] = React.useState(window.Mojro.CAT_MATRIX);
  const [tab, setTab] = React.useState('matrix');

  const cycleCell = (a, b) => {
    const cur = matrix[a][b];
    const next = cur === 'allowed' ? 'warn' : cur === 'warn' ? 'blocked' : 'allowed';
    setMatrix(m => ({
      ...m,
      [a]: { ...m[a], [b]: next },
      [b]: { ...m[b], [a]: next }, // symmetric
    }));
  };

  return (
    <div style={{ height:'100%', overflow:'auto' }}>
      <div style={{ padding:'24px 32px 16px', borderBottom:'1px solid var(--line)', background:'#fff' }}>
        <div style={{ display:'flex', alignItems:'flex-end', gap:14 }}>
          <div>
            <div className="h-eyebrow">Rules & constraints</div>
            <h1 className="h-title" style={{ marginTop:4 }}>Loading rule library</h1>
            <div className="h-subtitle">Three rule levels: per-SKU rules, vehicle rules, and loading constraints. Save as named rule sets and apply to any session.</div>
          </div>
          <div style={{ marginLeft:'auto', display:'flex', gap:8 }}>
            <button className="btn"><Icon name="upload" size={12}/> Import Excel</button>
            <button className="btn"><Icon name="download" size={12}/> Export rule set</button>
            <button className="btn btn--primary"><Icon name="plus" size={12}/> New rule set</button>
          </div>
        </div>
        <div style={{ marginTop:18, display:'flex', gap:8 }}>
          {[
            { id:'matrix',     label:'Category compatibility', count: 6 },
            { id:'sku',        label:'SKU rules',              count: 14 },
            { id:'vehicle',    label:'Vehicle / container',    count: 6 },
            { id:'loading',    label:'Loading constraints',    count: 9 },
          ].map(t => (
            <button key={t.id} onClick={() => setTab(t.id)}
              style={{
                padding:'8px 14px', border:'none',
                background: tab===t.id ? 'var(--mojro-red)' : 'var(--bg-elev)',
                color: tab===t.id ? '#fff' : 'var(--ink-1)',
                fontSize:13, fontWeight: tab===t.id?600:500, borderRadius:6, cursor:'pointer',
              }}>
              {t.label}
              <span style={{ marginLeft:6, opacity:0.7, fontFamily:'var(--font-mono)' }}>{t.count}</span>
            </button>
          ))}
        </div>
      </div>

      <div style={{ padding:'24px 32px', maxWidth: 1280 }}>
        {tab === 'matrix' && <CategoryMatrix matrix={matrix} onCycleCell={cycleCell}/>}
        {tab === 'sku' && <SkuRulesTab/>}
        {tab === 'vehicle' && <VehicleRulesTab/>}
        {tab === 'loading' && <LoadingRulesTab/>}
      </div>
    </div>
  );
};

const CategoryMatrix = ({ matrix, onCycleCell }) => {
  const cats = window.Mojro.CATEGORIES;
  const stateColor = { allowed: 'var(--ok-bg)', warn: 'var(--warn-bg)', blocked: 'var(--bad-bg)' };
  const stateInk   = { allowed: 'var(--ok)',    warn: 'var(--warn)',    blocked: 'var(--bad)' };
  const stateLabel = { allowed: 'Allowed', warn: 'Warn', blocked: 'Blocked' };
  return (
    <div className="card" style={{ padding:'18px 20px' }}>
      <div style={{ display:'flex', alignItems:'flex-start', marginBottom:12 }}>
        <div>
          <h3 style={{ margin:0, fontSize:16 }}>Category compatibility matrix</h3>
          <div style={{ fontSize:12.5, color:'var(--ink-3)', marginTop:2 }}>Click any cell to cycle <b style={{ color:'var(--ok)' }}>Allowed</b> → <b style={{ color:'var(--warn)' }}>Warn</b> → <b style={{ color:'var(--bad)' }}>Blocked</b>. Matrix is symmetric.</div>
        </div>
        <div style={{ marginLeft:'auto', display:'flex', gap:6 }}>
          <span className="chip chip--ok"><span className="dot"/>Allowed</span>
          <span className="chip chip--warn"><span className="dot"/>Warn</span>
          <span className="chip chip--bad"><span className="dot"/>Blocked</span>
        </div>
      </div>
      <div style={{ overflowX:'auto' }}>
        <table style={{ borderCollapse:'separate', borderSpacing:0, marginTop:6 }}>
          <thead>
            <tr>
              <th style={{ padding:0 }}></th>
              {cats.map(c => (
                <th key={c.id} style={{ padding:'6px 8px', textAlign:'left', fontWeight:500, fontSize:12, color:'var(--ink-2)' }}>
                  <div style={{ display:'flex', alignItems:'center', gap:6, transform:'rotate(0deg)' }}>
                    <span style={{ width:8, height:8, borderRadius:2, background:c.color }}/>
                    {c.name}
                  </div>
                </th>
              ))}
              <th style={{ padding:'6px 8px' }}>
                <button className="btn btn--sm btn--ghost"><Icon name="plus" size={12}/></button>
              </th>
            </tr>
          </thead>
          <tbody>
            {cats.map(a => (
              <tr key={a.id}>
                <th style={{ padding:'6px 10px 6px 0', textAlign:'left', fontWeight:600, fontSize:13, color:'var(--ink-1)', whiteSpace:'nowrap' }}>
                  <div style={{ display:'flex', alignItems:'center', gap:6 }}>
                    <span style={{ width:8, height:8, borderRadius:2, background:a.color }}/>
                    {a.name}
                  </div>
                </th>
                {cats.map(b => {
                  const s = matrix[a.id][b.id];
                  const isDiag = a.id === b.id;
                  return (
                    <td key={b.id} style={{ padding:3 }}>
                      <button
                        onClick={() => onCycleCell(a.id, b.id)}
                        style={{
                          width:96, height:54, border:'1px solid '+stateInk[s], background: stateColor[s], borderRadius:6,
                          display:'flex', flexDirection:'column', alignItems:'center', justifyContent:'center', gap:2,
                          cursor:'pointer', color: stateInk[s], fontWeight:600, fontSize:12,
                          opacity: isDiag ? 0.55 : 1,
                        }}>
                        <Icon name={s==='allowed'?'check':s==='warn'?'warning':'x'} size={14}/>
                        <span>{stateLabel[s]}</span>
                      </button>
                    </td>
                  );
                })}
                <td style={{ padding:3 }}></td>
              </tr>
            ))}
            <tr>
              <th style={{ padding:'6px 10px 6px 0' }}>
                <button className="btn btn--sm btn--ghost"><Icon name="plus" size={12}/> Category</button>
              </th>
            </tr>
          </tbody>
        </table>
      </div>
      <div style={{ marginTop:14, padding:'10px 12px', background:'var(--bg-elev)', borderRadius:6, fontSize:12, color:'var(--ink-2)', display:'flex', alignItems:'center', gap:8 }}>
        <Icon name="info" size={12} style={{ color:'var(--info)' }}/>
        Blocked pairs cause an optimization error. Warn pairs trigger a separation distance — set in <b>Loading constraints → Segregation</b>.
      </div>
    </div>
  );
};

const SkuRulesTab = () => {
  const ROWS = [
    { sku:'PLT-EUR-C', desc:'Cleaning chem (palletised)', orient:'upright only', stk:'No top stack',   cat:'Hazmat',  pri:'Last on / first off' },
    { sku:'BX-MED-04', desc:'Electronics carton',         orient:'top-fixed',    stk:'Max 12 kg on top', cat:'Fragile', pri:'Stop 3' },
    { sku:'BR-200L',   desc:'200 L drum lubricant',        orient:'upright',      stk:'No stack',         cat:'Hazmat',  pri:'Floor only' },
    { sku:'PP-3M-DN50',desc:'Steel pipe 3 m',              orient:'horizontal',   stk:'Bundled',          cat:'General', pri:'Side wall' },
    { sku:'AP-1100',   desc:'Apparel tee',                 orient:'any',          stk:'Yes',              cat:'General', pri:'Any' },
  ];
  return (
    <div className="card" style={{ padding:0 }}>
      <div style={{ display:'flex', alignItems:'center', padding:'12px 16px', borderBottom:'1px solid var(--line)' }}>
        <div>
          <h3 style={{ margin:0, fontSize:16 }}>Per-SKU rules</h3>
          <div style={{ fontSize:12.5, color:'var(--ink-3)' }}>Orientation, stackability, category, priority. Override per session if needed.</div>
        </div>
        <div style={{ marginLeft:'auto', display:'flex', gap:6 }}>
          <input className="input" placeholder="Search SKU" style={{ width:220, padding:'5px 10px', fontSize:12 }}/>
          <button className="btn btn--sm"><Icon name="plus" size={12}/> Add rule</button>
        </div>
      </div>
      <table className="tbl">
        <thead><tr><th>SKU</th><th>Description</th><th>Orientation</th><th>Stackability</th><th>Category</th><th>Priority / stop</th><th></th></tr></thead>
        <tbody>
          {ROWS.map(r => (
            <tr key={r.sku}>
              <td className="mono" style={{ fontSize:12 }}>{r.sku}</td>
              <td>{r.desc}</td>
              <td><span className="chip">{r.orient}</span></td>
              <td><span className="chip">{r.stk}</span></td>
              <td>
                <span className="chip" style={{
                  background: window.Mojro.CATEGORIES.find(c=>c.name===r.cat)?.color+'22',
                  color: window.Mojro.CATEGORIES.find(c=>c.name===r.cat)?.color,
                }}>{r.cat}</span>
              </td>
              <td style={{ fontSize:12, color:'var(--ink-2)' }}>{r.pri}</td>
              <td><button className="btn btn--icon btn--ghost"><Icon name="kebab" size={12}/></button></td>
            </tr>
          ))}
        </tbody>
      </table>
    </div>
  );
};

const VehicleRulesTab = () => (
  <div style={{ display:'grid', gridTemplateColumns:'repeat(3, 1fr)', gap:14 }}>
    {window.Mojro.CONTAINERS.map(c => (
      <div key={c.id} className="card" style={{ padding:'14px' }}>
        <div style={{ display:'flex', alignItems:'flex-start', gap:8 }}>
          <Icon name="container" size={18} style={{ color:'var(--mojro-red)' }}/>
          <div style={{ flex:1 }}>
            <div style={{ fontWeight:700, fontSize:14 }}>{c.name}</div>
            <span className="chip">{c.id.toUpperCase()}</span>
          </div>
          <button className="btn btn--icon btn--ghost"><Icon name="kebab" size={12}/></button>
        </div>
        <div style={{ display:'grid', gridTemplateColumns:'1fr 1fr 1fr', gap:8, marginTop:12 }}>
          <Stat2 label="L (m)" value={(c.L/1000).toFixed(2)}/>
          <Stat2 label="W (m)" value={(c.W/1000).toFixed(2)}/>
          <Stat2 label="H (m)" value={c.H?(c.H/1000).toFixed(2):'—'}/>
        </div>
        <div style={{ display:'grid', gridTemplateColumns:'1fr 1fr', gap:8, marginTop:8 }}>
          <Stat2 label="Max payload" value={`${(c.maxPayload/1000).toFixed(1)} t`}/>
          <Stat2 label="Axles" value={c.axles.length}/>
        </div>
        <div style={{ marginTop:12 }}>
          <div className="h-eyebrow" style={{ fontSize:10 }}>Exclusion zones</div>
          <div style={{ display:'flex', flexWrap:'wrap', gap:4, marginTop:4 }}>
            <span className="chip" style={{ fontSize:10 }}>wheel arch · L+R</span>
            {c.id==='40hc' && <span className="chip" style={{ fontSize:10 }}>reefer unit</span>}
            <span className="chip" style={{ fontSize:10 }}>door swing</span>
          </div>
        </div>
      </div>
    ))}
    <div className="card" style={{ padding:'14px', display:'grid', placeItems:'center', minHeight:170, color:'var(--ink-3)', borderStyle:'dashed' }}>
      <button className="btn"><Icon name="plus" size={13}/> Add vehicle preset</button>
    </div>
  </div>
);

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

const LoadingRulesTab = () => {
  const RULES = [
    { type:'Segregation', label:'Hazmat ↔ Food separation', detail:'600 mm minimum gap · enforced strictly', on:true },
    { type:'Segregation', label:'Chilled ↔ Ambient buffer',  detail:'200 mm thermal buffer · warn-only',   on:true },
    { type:'Weight',     label:'Heaviest items on bottom',   detail:'auto · within each pallet/container', on:true },
    { type:'Weight',     label:'CoG within 40–60% from front', detail:'rebalance if drifts',              on:true },
    { type:'Axle',       label:'Drive axle ≤ 11.5 t',         detail:'EU directive · 2015/719',          on:true },
    { type:'Sequence',   label:'LIFO by stop',                detail:'Stop 1 loaded last (rear-most)',     on:true },
    { type:'Sequence',   label:'Priority zone for stop 1',    detail:'reserve rear 30% length',           on:false },
    { type:'Overhang',   label:'Pallet overhang ≤ 5%',         detail:'all sides',                          on:true },
    { type:'Floor',      label:'Floor strength 4500 kg/m²',    detail:'per axle zone',                      on:true },
  ];
  return (
    <div className="card" style={{ padding:0 }}>
      <div style={{ padding:'12px 16px', borderBottom:'1px solid var(--line)', display:'flex', alignItems:'center' }}>
        <div>
          <h3 style={{ margin:0, fontSize:16 }}>Loading constraints</h3>
          <div style={{ fontSize:12.5, color:'var(--ink-3)' }}>Segregation, weight distribution, sequence, overhang.</div>
        </div>
        <div style={{ marginLeft:'auto' }}><button className="btn btn--sm"><Icon name="plus" size={12}/> Add constraint</button></div>
      </div>
      <div style={{ padding:'8px 0' }}>
        {RULES.map((r,i) => (
          <div key={i} style={{ padding:'10px 16px', display:'flex', alignItems:'center', gap:14, borderBottom: i===RULES.length-1 ? 'none':'1px solid var(--line)' }}>
            <span className="chip" style={{ minWidth:96, justifyContent:'center' }}>{r.type}</span>
            <div style={{ flex:1 }}>
              <div style={{ fontSize:13.5, fontWeight: r.on?500:400, color: r.on?'var(--ink-1)':'var(--ink-3)' }}>{r.label}</div>
              <div style={{ fontSize:12, color:'var(--ink-3)', marginTop:1 }}>{r.detail}</div>
            </div>
            <button className="btn btn--sm btn--ghost"><Icon name="settings" size={12}/></button>
            <Toggle on={r.on}/>
          </div>
        ))}
      </div>
    </div>
  );
};

window.RulesScreen = RulesScreen;
