/* ===== Excel upload modal — column mapping + row validation ===== */
const ExcelUploadModal = ({ open, onClose, onConfirm }) => {
  const [step, setStep] = React.useState(2); // skip to mapping for demo

  if (!open) return null;
  return (
    <div style={{
      position:'fixed', inset:0, zIndex:50,
      background:'rgba(20,8,8,0.45)', backdropFilter:'blur(4px)',
      display:'grid', placeItems:'center', padding:24,
    }} onClick={onClose}>
      <div className="card card--elev" style={{ width:'min(960px, 100%)', maxHeight:'90vh', display:'flex', flexDirection:'column', overflow:'hidden' }} onClick={e=>e.stopPropagation()}>
        {/* header */}
        <div style={{ padding:'14px 18px', borderBottom:'1px solid var(--line)', display:'flex', alignItems:'center', gap:14 }}>
          <Icon name="upload" size={18}/>
          <div style={{ flex:1 }}>
            <div style={{ fontWeight:700, fontSize:15 }}>Import cargo manifest</div>
            <div style={{ fontSize:12, color:'var(--ink-3)' }}>shanghai_export_w19.xlsx · 3 sheets · 142 rows</div>
          </div>
          <Stepper step={step} steps={['Upload','Sheets','Map columns','Validate']}/>
          <button className="btn btn--icon btn--ghost" onClick={onClose}><Icon name="x" size={16}/></button>
        </div>

        {/* body */}
        <div style={{ flex:1, overflow:'auto', padding:'18px 22px' }}>
          {step === 0 && <UploadDrop onNext={() => setStep(1)} />}
          {step === 1 && <SheetPicker onNext={() => setStep(2)} />}
          {step === 2 && <ColumnMapper onNext={() => setStep(3)} />}
          {step === 3 && <RowValidator onConfirm={() => { onConfirm(); }} />}
        </div>

        {/* footer */}
        <div style={{ padding:'12px 18px', borderTop:'1px solid var(--line)', display:'flex', alignItems:'center', gap:8 }}>
          <button className="btn btn--ghost"><Icon name="download" size={13}/> Download template</button>
          <button className="btn btn--ghost"><Icon name="info" size={13}/> Field definitions</button>
          <div style={{ flex:1 }}/>
          <button className="btn" onClick={() => setStep(Math.max(0, step-1))} disabled={step===0}>Back</button>
          {step < 3 ? (
            <button className="btn btn--primary" onClick={() => setStep(step+1)}>Continue</button>
          ) : (
            <button className="btn btn--primary" onClick={onConfirm}>Import 138 rows</button>
          )}
        </div>
      </div>
    </div>
  );
};

const Stepper = ({ step, steps }) => (
  <div style={{ display:'flex', alignItems:'center', gap:6 }}>
    {steps.map((s, i) => (
      <React.Fragment key={s}>
        <span style={{
          padding:'3px 8px', borderRadius:999, fontSize:11.5,
          background: i===step ? 'var(--mojro-red)' : i<step ? 'var(--ok-bg)' : 'transparent',
          color: i===step ? '#fff' : i<step ? 'var(--ok)' : 'var(--ink-3)',
          border: i===step ? 'none' : '1px solid var(--line)',
          fontWeight: i===step ? 600 : 500,
        }}>
          {i<step ? <Icon name="check" size={10} style={{ verticalAlign:'-1px', marginRight:4 }}/> : null}
          {s}
        </span>
        {i<steps.length-1 && <span style={{ color:'var(--ink-4)', fontSize:11 }}>›</span>}
      </React.Fragment>
    ))}
  </div>
);

const UploadDrop = ({ onNext }) => (
  <div style={{
    border:'2px dashed var(--line-strong)', borderRadius:10, padding:'36px',
    textAlign:'center', background:'var(--bg-elev)',
  }}>
    <Icon name="upload" size={32} style={{ color:'var(--mojro-red)' }}/>
    <div style={{ fontSize:15, fontWeight:600, marginTop:8 }}>Drop your file here or browse</div>
    <div style={{ fontSize:12, color:'var(--ink-3)', marginTop:4 }}>.xlsx, .xls, .csv up to 25 MB</div>
    <button className="btn btn--primary" style={{ marginTop:14 }} onClick={onNext}>Choose file</button>
  </div>
);

const SheetPicker = ({ onNext }) => (
  <div>
    <div className="h-eyebrow" style={{ marginBottom:8 }}>Detected sheets</div>
    {['cargo_manifest','rules','category_matrix'].map((n, i) => (
      <label key={n} style={{ display:'flex', alignItems:'center', gap:10, padding:'10px 12px', border:'1px solid var(--line)', borderRadius:8, marginBottom:6, cursor:'pointer', background: i===0 ? 'rgba(193,51,51,0.04)':'#fff', borderColor: i===0 ? 'var(--mojro-red)':'var(--line)' }}>
        <input type="radio" name="s" defaultChecked={i===0}/>
        <div style={{ flex:1 }}>
          <div style={{ fontWeight:600 }}>{n}</div>
          <div style={{ fontSize:12, color:'var(--ink-3)' }}>{[142, 18, 36][i]} rows · {[11,6,7][i]} columns</div>
        </div>
        <span className="chip chip--info">{['Cargo','Rules','Matrix'][i]}</span>
      </label>
    ))}
  </div>
);

const ColumnMapper = ({ onNext }) => {
  const COLS = [
    { their: 'SKU_CODE',        ours: 'sku',         conf: 0.99, sample: 'GD-1029' },
    { their: 'Description',     ours: 'desc',        conf: 0.96, sample: 'Loose box · Tools' },
    { their: 'Lenght (mm)',     ours: 'L',           conf: 0.92, sample: '380' },
    { their: 'Width-mm',        ours: 'W',           conf: 0.94, sample: '240' },
    { their: 'Hght',            ours: 'H',           conf: 0.78, sample: '220' },
    { their: 'WGT (kg)',        ours: 'weight',     conf: 0.95, sample: '11' },
    { their: 'QTY',             ours: 'qty',         conf: 0.99, sample: '6' },
    { their: 'Cat.',            ours: 'category',    conf: 0.71, sample: 'general' },
    { their: 'STK',             ours: 'stackable',   conf: 0.42, sample: 'Y' },
    { their: 'STOP_NO',         ours: 'stop',        conf: 0.88, sample: '2' },
    { their: 'orient',          ours: 'orientation', conf: 0.86, sample: 'upright' },
  ];
  return (
    <div>
      <div style={{ display:'flex', alignItems:'baseline', marginBottom:10 }}>
        <div>
          <div style={{ fontWeight:600, fontSize:14 }}>Column mapping</div>
          <div style={{ fontSize:12, color:'var(--ink-3)' }}>We auto-matched 11 of 11 columns. Review and confirm.</div>
        </div>
        <div style={{ marginLeft:'auto', display:'flex', gap:6 }}>
          <button className="btn btn--sm"><Icon name="download" size={11}/> Save mapping profile</button>
        </div>
      </div>
      <div style={{ border:'1px solid var(--line)', borderRadius:8, overflow:'hidden' }}>
        <table className="tbl">
          <thead><tr>
            <th style={{ width:'24%' }}>Your column</th>
            <th>Sample</th>
            <th style={{ width:'28%' }}>Mojro field</th>
            <th style={{ width:'18%' }}>Confidence</th>
          </tr></thead>
          <tbody>
            {COLS.map(c => {
              const tone = c.conf >= 0.9 ? 'ok' : c.conf >= 0.7 ? 'warn' : 'bad';
              return (
                <tr key={c.their}>
                  <td className="mono" style={{ fontSize:12 }}>{c.their}</td>
                  <td style={{ color:'var(--ink-3)', fontSize:12 }}>{c.sample}</td>
                  <td>
                    <select className="input" style={{ padding:'4px 8px', fontSize:12 }}>
                      <option>{c.ours}</option>
                    </select>
                  </td>
                  <td>
                    <div style={{ display:'flex', alignItems:'center', gap:6 }}>
                      <div style={{ flex:1, height:6, background:'#efe8df', borderRadius:3, overflow:'hidden' }}>
                        <div style={{ width: (c.conf*100)+'%', height:'100%', background: 'var(--'+tone+')'}}/>
                      </div>
                      <span className="mono" style={{ fontSize:11, color:'var(--ink-3)' }}>{Math.round(c.conf*100)}%</span>
                    </div>
                  </td>
                </tr>
              );
            })}
          </tbody>
        </table>
      </div>
    </div>
  );
};

const RowValidator = ({ onConfirm }) => {
  const ROWS = [
    { row: 1, status:'ok',   sku:'GD-1029',  qty: 6,  L: 380, W: 240, H: 220, weight:11,  err: null },
    { row: 2, status:'ok',   sku:'BX-LRG-01',qty:14,  L: 600, W: 400, H: 400, weight:22,  err: null },
    { row: 3, status:'warn', sku:'PP-3M-DN50',qty:12, L: 3000,W: 60,  H: 60,  weight:18,  err: 'Length 3000mm exceeds preferred carton; will fit container only.' },
    { row: 4, status:'ok',   sku:'BR-200L',  qty: 4,  L: 580, W: 580, H: 880, weight:196, err: null },
    { row: 5, status:'bad',  sku:'BX-?',     qty: '?',L: '?', W: 400, H: 280, weight:14,  err: 'Missing required: sku, qty, L. Skip row or fix.' },
    { row: 6, status:'ok',   sku:'PLT-EUR-A',qty: 8,  L:1200, W: 800, H:1450, weight:720, err: null },
    { row: 7, status:'warn', sku:'PLT-EUR-C',qty: 4,  L:1200, W: 800, H:1300, weight:540, err: 'Category "Hazmat" requires segregation distance — applied automatically.' },
  ];
  const counts = ROWS.reduce((a, r) => (a[r.status]++, a), { ok:0, warn:0, bad:0 });
  return (
    <div>
      <div style={{ display:'flex', alignItems:'baseline', marginBottom:10 }}>
        <div>
          <div style={{ fontWeight:600, fontSize:14 }}>Row validation</div>
          <div style={{ fontSize:12, color:'var(--ink-3)' }}>{ROWS.length} rows scanned in <span className="mono">cargo_manifest</span></div>
        </div>
        <div style={{ marginLeft:'auto', display:'flex', gap:6 }}>
          <span className="chip chip--ok"><span className="dot"/> {counts.ok} valid</span>
          <span className="chip chip--warn"><span className="dot"/> {counts.warn} warnings</span>
          <span className="chip chip--bad"><span className="dot"/> {counts.bad} blocking</span>
        </div>
      </div>
      <div style={{ border:'1px solid var(--line)', borderRadius:8, overflow:'hidden' }}>
        <table className="tbl">
          <thead><tr>
            <th>Row</th>
            <th>Status</th>
            <th>SKU</th>
            <th>Qty</th>
            <th>L×W×H (mm)</th>
            <th>Weight (kg)</th>
            <th>Notes</th>
          </tr></thead>
          <tbody>
            {ROWS.map(r => (
              <tr key={r.row} style={{ background: r.status==='bad' ? 'var(--bad-bg)' : r.status==='warn' ? 'var(--warn-bg)' : undefined }}>
                <td className="mono" style={{ fontSize:11.5 }}>{r.row}</td>
                <td>
                  {r.status==='ok'   && <span className="chip chip--ok"><span className="dot"/>OK</span>}
                  {r.status==='warn' && <span className="chip chip--warn"><span className="dot"/>warn</span>}
                  {r.status==='bad'  && <span className="chip chip--bad"><span className="dot"/>error</span>}
                </td>
                <td className="mono" style={{ fontSize:12 }}>{r.sku}</td>
                <td className="mono" style={{ fontSize:12 }}>{r.qty}</td>
                <td className="mono" style={{ fontSize:12 }}>{r.L}×{r.W}×{r.H}</td>
                <td className="mono" style={{ fontSize:12 }}>{r.weight}</td>
                <td style={{ fontSize:11.5, color:'var(--ink-2)' }}>{r.err || <span style={{ color:'var(--ink-4)' }}>—</span>}</td>
              </tr>
            ))}
          </tbody>
        </table>
      </div>
      <div style={{ marginTop:10, padding:'10px 12px', background:'var(--info-bg)', borderRadius:6, fontSize:12, color:'var(--ink-2)' }}>
        <Icon name="info" size={12} style={{ verticalAlign:'-2px', marginRight:6, color:'var(--info)' }}/>
        Importing will <b>skip 1 blocking row</b> and apply 2 auto-corrections. You can fix and re-import the skipped row at any time.
      </div>
    </div>
  );
};

window.ExcelUploadModal = ExcelUploadModal;
