// ──────────────────────────── Magazzino ────────────────────────────

const { useState: useStateM, useEffect: useEffectM, useMemo: useMemoM, useRef: useRefM } = React;

// ─── Sub-tabs nav ───
const MagTabs = ({ tab, onTab }) => {
  const TABS = [
    { id: 'movimenti',     label: 'Movimenti',     icon: 'Refresh' },
    { id: 'inventario',    label: 'Inventario fisico', icon: 'Barcode' },
    { id: 'trasferimenti', label: 'Trasferimenti',  icon: 'Truck' },
    { id: 'richieste',     label: 'Richieste',      icon: 'Box' },
  ];
  return (
    <div className="flex items-center gap-1 px-7 hairline bg-paper">
      {TABS.map(t => {
        const Ico = I[t.icon];
        const active = tab === t.id;
        return (
          <button key={t.id} onClick={()=>onTab(t.id)}
            className={`flex items-center gap-2 h-11 px-4 text-[14px] font-medium transition-all duration-fast ease-standard border-b-2 -mb-px
              ${active ? 'text-ink border-ink' : 'text-muted border-transparent hover:text-ink'}`}>
            <Ico size={16}/>
            {t.label}
          </button>
        );
      })}
    </div>
  );
};

// ───────────────────────────── 1) MOVIMENTI ─────────────────────────────
const Movimenti = ({ activeStoreId = STORE.id }) => {
  const [q, setQ] = useStateM('');
  const [kind, setKind] = useStateM('Tutti');
  const [causal, setCausal] = useStateM('Tutte');
  const [range, setRange] = useStateM('7g');

  const kinds   = ['Tutti', 'Carico', 'Scarico', 'Rettifica'];
  const causals = ['Tutte', ...Array.from(new Set(MOVEMENTS.map(m=>m.causal)))];

  const filtered = useMemoM(() => {
    const ql = q.trim().toLowerCase();
    return MOVEMENTS.filter(m => {
      if (m.store && activeStoreId !== 'all' && m.store !== activeStoreId) return false;
      if (kind !== 'Tutti' && m.kind !== kind) return false;
      if (causal !== 'Tutte' && m.causal !== causal) return false;
      if (ql && !(m.name.toLowerCase().includes(ql) || m.sku.toLowerCase().includes(ql) || m.ref.toLowerCase().includes(ql))) return false;
      return true;
    });
  }, [q, kind, causal, activeStoreId]);

  // Aggregate
  const totIn  = filtered.filter(m=>m.qty>0).reduce((s,m)=>s+m.qty,0);
  const totOut = filtered.filter(m=>m.qty<0).reduce((s,m)=>s+Math.abs(m.qty),0);

  return (
    <div className="px-7 py-6 space-y-4 max-w-[1400px]">
      {/* KPI */}
      <div className="grid grid-cols-3 gap-4">
        <Card>
          <div className="text-[11px] uppercase tracking-[0.08em] text-muted font-medium">Pezzi in entrata</div>
          <div className="num mt-1.5 text-[28px] font-semibold text-pos">+{totIn}</div>
          <div className="text-[12px] text-muted mt-0.5">{filtered.filter(m=>m.qty>0).length} movimenti</div>
        </Card>
        <Card>
          <div className="text-[11px] uppercase tracking-[0.08em] text-muted font-medium">Pezzi in uscita</div>
          <div className="num mt-1.5 text-[28px] font-semibold text-neg">−{totOut}</div>
          <div className="text-[12px] text-muted mt-0.5">{filtered.filter(m=>m.qty<0).length} movimenti</div>
        </Card>
        <Card>
          <div className="text-[11px] uppercase tracking-[0.08em] text-muted font-medium">Saldo periodo</div>
          <div className={`num mt-1.5 text-[28px] font-semibold ${totIn-totOut >= 0 ? 'text-ink' : 'text-neg'}`}>
            {totIn-totOut >= 0 ? '+' : ''}{totIn-totOut}
          </div>
          <div className="text-[12px] text-muted mt-0.5">ultimi 7 giorni</div>
        </Card>
      </div>

      {/* Filters */}
      <div className="bg-surface rounded-2xl p-3.5 shadow-soft">
        <div className="flex flex-wrap items-center gap-2.5">
          <div className="relative flex-1 min-w-[260px]">
            <I.Search size={18} className="absolute left-3.5 top-1/2 -translate-y-1/2 text-muted"/>
            <input value={q} onChange={(e)=>setQ(e.target.value)}
              placeholder="Cerca per articolo, SKU o riferimento documento…"
              className="w-full h-11 pl-11 pr-4 rounded-md bg-sunken text-[14px] shadow-[inset_0_0_0_0.5px_var(--border-default)] focus:bg-surface focus:shadow-[var(--shadow-focus),inset_0_0_0_1px_var(--accent-blue)] transition-all duration-fast ease-standard"/>
          </div>
          <FilterSelect label="Tipo"     value={kind}   onChange={setKind}   options={kinds}/>
          <FilterSelect label="Causale"  value={causal} onChange={setCausal} options={causals}/>
          <FilterSelect label="Periodo"  value={range}  onChange={setRange}  options={[{v:'oggi',l:'Oggi'},{v:'7g',l:'Ultimi 7 giorni'},{v:'30g',l:'Ultimi 30 giorni'},{v:'mese',l:'Questo mese'}]}/>
          <Btn variant="outline" size="md" leading={<I.ArrowD size={16}/>} className="ml-auto"
            onClick={()=>{ if(window.__csv) window.__csv('movimenti.csv', ['ID','Data','Ora','Tipo','Causale','Articolo','SKU','Riferimento','Quantità','Operatore'], filtered.map(m=>[m.id, m.date, m.time, m.kind, m.causal, m.name, m.sku, m.ref, m.qty, m.op])); }}>Esporta CSV</Btn>
        </div>
      </div>

      {/* Movements table */}
      <Card padded={false}>
        <table className="w-full text-[13.5px]">
          <thead>
            <tr className="text-left text-muted uppercase text-[11px] tracking-[0.08em] hairline">
              <th className="px-5 py-3 font-medium">ID</th>
              <th className="px-5 py-3 font-medium">Data / Ora</th>
              <th className="px-5 py-3 font-medium">Tipo</th>
              <th className="px-5 py-3 font-medium">Causale</th>
              <th className="px-5 py-3 font-medium">Articolo</th>
              <th className="px-5 py-3 font-medium">SKU</th>
              <th className="px-5 py-3 font-medium">Riferimento</th>
              <th className="px-5 py-3 font-medium text-right">Quantità</th>
              <th className="px-5 py-3 font-medium">Op.</th>
            </tr>
          </thead>
          <tbody>
            {filtered.map(mv => {
              const pos = mv.qty > 0;
              return (
                <tr key={mv.id} className="hover:bg-paper border-b border-line2 last:border-0 cursor-pointer"
                  onClick={()=>{ if(window.__toast) window.__toast(`Movimento ${mv.id} · ${mv.causal} · rif. ${mv.ref}`, 'info'); }}>
                  <td className="px-5 py-3.5 num text-muted">{mv.id}</td>
                  <td className="px-5 py-3.5">
                    <div className="text-ink">{mv.date}</div>
                    <div className="num text-[11.5px] text-muted">{mv.time}</div>
                  </td>
                  <td className="px-5 py-3.5">
                    {mv.kind === 'Carico'    && <Pill tone="pos">Carico</Pill>}
                    {mv.kind === 'Scarico'   && <Pill tone="neg">Scarico</Pill>}
                    {mv.kind === 'Rettifica' && <Pill tone="warn">Rettifica</Pill>}
                  </td>
                  <td className="px-5 py-3.5 text-ink">{mv.causal}</td>
                  <td className="px-5 py-3.5 text-ink">{mv.name}</td>
                  <td className="px-5 py-3.5 num text-muted">{mv.sku}</td>
                  <td className="px-5 py-3.5 num text-ink">{mv.ref}</td>
                  <td className={`px-5 py-3.5 num text-right font-semibold ${pos ? 'text-pos' : 'text-neg'}`}>
                    {pos ? '+' : ''}{mv.qty}
                  </td>
                  <td className="px-5 py-3.5">
                    <span className="w-7 h-7 rounded-full bg-line2 text-ink text-[10px] font-semibold flex items-center justify-center">{mv.op}</span>
                  </td>
                </tr>
              );
            })}
          </tbody>
        </table>
        {filtered.length === 0 && (
          <div className="py-16 text-center text-muted text-[14px]">Nessun movimento corrisponde ai filtri.</div>
        )}
      </Card>
    </div>
  );
};

// ───────────────────────────── 2) INVENTARIO ─────────────────────────────
const Inventario = ({ activeStoreId = STORE.id, readOnly = false }) => {
  // counted state per SKU
  const [counted, setCounted] = useStateM(() => Object.fromEntries(INVENTORY_ROWS.map(r => [r.sku, 0])));
  const [scanInput, setScanInput] = useStateM('');
  const [flashSku, setFlashSku] = useStateM(null);
  const [filter, setFilter] = useStateM('tutti'); // tutti | scostamenti | rilevati | mancanti
  const [confirmClose, setConfirmClose] = useStateM(false);
  const rowRefs = useRefM({});
  const _store = (activeStoreId && activeStoreId !== 'all') ? activeStoreId : (window.STORE && window.STORE.id);

  // Carica la BOZZA inventario salvata per questo negozio (se esiste)
  useEffectM(() => {
    let alive = true;
    if (window.__API__ && window.__API__.get && _store) {
      window.__API__.get('/api/inventory/draft?store=' + encodeURIComponent(_store)).then(r => {
        if (alive && r && r.ok && r.draft && r.draft.counted) {
          setCounted(prev => ({ ...prev, ...r.draft.counted }));
          if (window.__toast) window.__toast('Bozza inventario ripristinata', 'info');
        }
      });
    }
    return () => { alive = false; };
  }, [_store]);

  const sospendiBozza = () => {
    if (window.__API__) window.__API__.post('/api/inventory/draft', { store: _store, counted })
      .then(() => { if (window.__toast) window.__toast('Inventario sospeso · bozza conservata', 'success'); }).catch(()=>{});
  };
  const inputRef = useRefM(null);

  // KPI in real time
  const totalRows = INVENTORY_ROWS.length;
  const surveyed = INVENTORY_ROWS.filter(r => counted[r.sku] > 0).length;
  const toSurvey = totalRows - surveyed;
  const totalExpected = INVENTORY_ROWS.reduce((s, r) => s + r.expected, 0);
  const totalCounted  = INVENTORY_ROWS.reduce((s, r) => s + (counted[r.sku] || 0), 0);
  const totalDelta    = totalCounted - totalExpected;
  const discrepancies = INVENTORY_ROWS.filter(r => (counted[r.sku] || 0) !== 0 && (counted[r.sku] || 0) !== r.expected).length;

  // Filter rows
  const visible = INVENTORY_ROWS.filter(r => {
    const c = counted[r.sku] || 0;
    if (filter === 'scostamenti') return c > 0 && c !== r.expected;
    if (filter === 'rilevati')    return c > 0;
    if (filter === 'mancanti')    return c === 0;
    return true;
  });

  const doScan = (sku) => {
    const r = INVENTORY_ROWS.find(x => x.sku === sku);
    if (!r) return;
    setCounted(prev => ({ ...prev, [sku]: (prev[sku] || 0) + 1 }));
    setFlashSku(sku);
    setTimeout(() => setFlashSku(null), 700);
    // scroll into view
    const el = rowRefs.current[sku];
    if (el) el.scrollIntoView({ block: 'center', behavior: 'smooth' });
  };

  const submitScan = (e) => {
    e.preventDefault();
    const v = scanInput.trim().toUpperCase();
    if (!v) return;
    const r = INVENTORY_ROWS.find(x => x.sku === v);
    if (r) doScan(v);
    setScanInput('');
    inputRef.current?.focus();
  };

  // Demo articles for quick scan buttons
  const DEMO_SCANS = INVENTORY_ROWS.slice(0, 6);

  const resetCount = (sku) => setCounted(prev => ({ ...prev, [sku]: 0 }));
  const setManual  = (sku, v) => setCounted(prev => ({ ...prev, [sku]: Math.max(0, parseInt(v) || 0) }));

  return (
    <div className="px-7 py-5 max-w-[1400px]">
      {/* Header: inventario in corso */}
      <div className="flex flex-wrap items-center justify-between gap-3 mb-4">
        <div>
          <div className="text-[11px] uppercase tracking-[0.08em] text-muted font-medium">Inventario in corso · {STORES.find(s=>s.id===activeStoreId)?.name || STORE.name}</div>
          <div className="text-[20px] font-semibold tracking-tight text-ink mt-0.5">INV 2026-05 · 21 maggio 2026</div>
        </div>
        <div className="flex items-center gap-2">
          <Btn variant="ghost" size="md" leading={<I.Pause size={16}/>} disabled={readOnly}
            onClick={sospendiBozza}>Sospendi</Btn>
          <Btn variant="outline" size="md" leading={<I.ArrowD size={16}/>}
            onClick={()=>{ if(window.__csv) window.__csv('inventario-bozza.csv', ['SKU','Articolo','Colore','Taglia','Atteso','Contato','Differenza'], INVENTORY_ROWS.map(r=>{ const c = counted[r.sku]||0; return [r.sku, r.name, r.color, r.size, r.expected, c, c-r.expected]; })); }}>Esporta bozza</Btn>
        </div>
      </div>

      {/* KPI strip */}
      <div className="grid grid-cols-4 gap-4 mb-4">
        <KpiTile label="Totale articoli"  value={totalRows} sub="da inventariare" />
        <KpiTile label="Già rilevati"     value={surveyed}   sub={`${Math.round(surveyed/totalRows*100)}% completato`} tone="pos" />
        <KpiTile label="Da rilevare"      value={toSurvey}   sub="articoli rimanenti" tone={toSurvey === 0 ? 'pos' : 'warn'} />
        <KpiTile label="Scostamenti"      value={discrepancies} sub={discrepancies === 0 ? 'nessuna discrepanza' : 'da verificare'} tone={discrepancies === 0 ? 'pos' : 'neg'} />
      </div>

      {/* Progress bar */}
      <div className="bg-surface rounded-2xl p-4 mb-4 shadow-soft">
        <div className="flex items-center justify-between text-[13px] mb-2.5">
          <span className="text-ink font-medium">Avanzamento conteggio</span>
          <span className="num text-muted"><span className="text-ink font-medium">{totalCounted}</span> / {totalExpected} pezzi attesi</span>
        </div>
        <div className="h-2.5 bg-line2 rounded-full overflow-hidden">
          <div className="h-full bg-[var(--accent-blue)] rounded-full transition-all" style={{ width: `${Math.min(100, (surveyed/totalRows)*100)}%` }}></div>
        </div>
      </div>

      {/* Scan bar */}
      <div className="bg-surface shadow-[inset_0_0_0_1px_var(--border-default)] rounded-2xl p-4 mb-4 shadow-soft">
        <form onSubmit={submitScan}>
          <div className="flex items-center gap-3">
            <div className="w-12 h-12 rounded-md bg-[var(--bg-selected)] text-[var(--accent-blue)] flex items-center justify-center shrink-0">
              <I.Barcode size={22}/>
            </div>
            <div className="flex-1">
              <div className="text-[11px] uppercase tracking-[0.08em] text-muted font-medium">Scansiona o digita SKU</div>
              <input
                ref={inputRef}
                autoFocus={!readOnly}
                disabled={readOnly}
                value={scanInput}
                onChange={(e)=>setScanInput(e.target.value)}
                placeholder="Punta il lettore o digita es. GI-1029-NV-48…"
                className="w-full mt-0.5 bg-transparent num text-[20px] font-medium text-ink focus:outline-none placeholder:text-[var(--text-tertiary)] placeholder:font-normal placeholder:text-[15px] disabled:opacity-40 disabled:cursor-not-allowed"
              />
            </div>
            <Btn variant="primary" size="lg" type="submit" disabled={readOnly} trailing={<I.ArrowR size={18}/>}>Conferma</Btn>
          </div>
        </form>
        <div className="mt-3 pt-3 border-t border-line2">
          <div className="text-[11px] uppercase tracking-[0.08em] text-muted font-medium mb-2">Simula scansione (demo)</div>
          <div className="flex flex-wrap gap-1.5">
            {DEMO_SCANS.map(d => (
              <button key={d.sku} onClick={()=>doScan(d.sku)} disabled={readOnly}
                className="h-10 px-3 rounded-sm border border-line bg-paper hover:border-strong text-[12.5px] num font-medium text-ink flex items-center gap-2 transition-all duration-fast ease-standard disabled:opacity-40 disabled:cursor-not-allowed">
                <I.Barcode size={14} className="text-muted"/>
                <span>{d.sku}</span>
              </button>
            ))}
          </div>
        </div>
      </div>

      {/* Filter chips */}
      <div className="flex items-center gap-1.5 mb-3">
        {[
          { id: 'tutti',       label: `Tutti (${totalRows})` },
          { id: 'rilevati',    label: `Rilevati (${surveyed})` },
          { id: 'mancanti',    label: `Da rilevare (${toSurvey})` },
          { id: 'scostamenti', label: `Scostamenti (${discrepancies})` },
        ].map(f => (
          <button key={f.id} onClick={()=>setFilter(f.id)}
            className={`px-3.5 h-10 rounded-sm text-[13px] font-medium ${filter === f.id ? 'bg-[var(--bg-selected)] text-[var(--accent-blue)]' : 'border border-line text-ink hover:bg-[var(--bg-hover)]'}`}>
            {f.label}
          </button>
        ))}
      </div>

      {/* Inventory rows */}
      <Card padded={false}>
        <div className="grid grid-cols-[1fr_120px_120px_140px_140px_140px] gap-2 px-5 h-11 items-center text-[11px] uppercase tracking-[0.08em] text-muted font-medium hairline">
          <div>Articolo</div>
          <div className="text-right">Atteso</div>
          <div className="text-right">Contato</div>
          <div className="text-right">Differenza</div>
          <div className="text-center">Stato</div>
          <div className="text-right">Manuale</div>
        </div>
        <div className="divide-y divide-line2">
          {visible.map(r => {
            const c = counted[r.sku] || 0;
            const delta = c - r.expected;
            const isCounted = c > 0;
            const ok = isCounted && delta === 0;
            const positive = delta > 0;
            const negative = delta < 0 && isCounted;
            const flashing = flashSku === r.sku;
            const rowTone =
              flashing ? 'bg-[var(--bg-selected)]' :
              !isCounted ? 'bg-surface' :
              ok ? 'bg-[var(--success-50)]' :
              positive ? 'bg-[var(--success-50)]' :
              'bg-[var(--danger-50)]';
            return (
              <div
                key={r.sku}
                ref={el => rowRefs.current[r.sku] = el}
                className={`row-h grid grid-cols-[1fr_120px_120px_140px_140px_140px] gap-2 px-5 items-center transition-all duration-fast ease-standard ${rowTone}`}
              >
                <div className="flex items-center gap-3 min-w-0">
                  <ProductThumb size={40}/>
                  <div className="min-w-0">
                    <div className="text-[14px] font-medium text-ink truncate">{r.name}</div>
                    <div className="num text-[11.5px] text-muted mt-0.5">{r.sku} · {r.color} · Tg {r.size}</div>
                  </div>
                </div>
                <div className="num text-[16px] text-ink text-right">{r.expected}</div>
                <div className={`num text-[18px] text-right font-medium ${!isCounted ? 'text-[var(--text-tertiary)]' : 'text-ink'}`}>{c}</div>
                <div className={`num text-[16px] text-right font-semibold ${!isCounted ? 'text-[var(--text-disabled)]' : ok ? 'text-pos' : positive ? 'text-pos' : 'text-neg'}`}>
                  {!isCounted ? '—' : ok ? '0' : positive ? `+${delta}` : delta}
                </div>
                <div className="flex justify-center">
                  {!isCounted    && <Pill tone="neutral">Da rilevare</Pill>}
                  {ok            && <Pill tone="pos">Match</Pill>}
                  {positive      && <Pill tone="pos">+{delta} ecced.</Pill>}
                  {negative      && <Pill tone="neg">{delta} mancante</Pill>}
                </div>
                <div className="flex items-center justify-end gap-1.5">
                  <input
                    type="number" min="0"
                    value={c || ''}
                    onChange={(e)=>setManual(r.sku, e.target.value)}
                    disabled={readOnly}
                    placeholder="0"
                    className="w-16 h-10 px-2 rounded-sm border border-line bg-surface num text-[14px] text-right focus:border-strong disabled:opacity-40 disabled:cursor-not-allowed"
                  />
                  {isCounted && !readOnly && (
                    <button onClick={()=>resetCount(r.sku)}
                      className="w-10 h-10 rounded-sm hover:bg-[var(--bg-hover)] flex items-center justify-center text-muted" title="Azzera">
                      <I.Refresh size={14}/>
                    </button>
                  )}
                </div>
              </div>
            );
          })}
          {visible.length === 0 && (
            <div className="py-16 text-center text-muted text-[14px]">Nessun articolo in questo filtro.</div>
          )}
        </div>
      </Card>

      {/* Close inventory CTA */}
      <div className="mt-5 sticky bottom-0 glass-thin rounded-2xl p-4 shadow-popover flex items-center justify-between gap-4">
        <div>
          <div className="text-[12px] text-muted">Saldo conteggio</div>
          <div className={`num text-[24px] font-semibold ${totalDelta === 0 ? 'text-ink' : totalDelta > 0 ? 'text-pos' : 'text-neg'}`}>
            {totalDelta === 0 ? 'In equilibrio' : (totalDelta > 0 ? `+${totalDelta}` : totalDelta) + ' pezzi'}
          </div>
        </div>
        <button
          onClick={()=>setConfirmClose(true)}
          disabled={surveyed === 0 || readOnly}
          className="h-16 px-8 rounded-md bg-[var(--accent-blue)] text-[var(--text-inverse)] font-semibold text-[17px] flex items-center gap-3 hover:bg-[var(--accent-blue-hover)] active:bg-[var(--accent-blue-active)] disabled:opacity-30 disabled:cursor-not-allowed transition-all duration-fast ease-standard shadow-soft"
        >
          <I.Check size={20}/>
          Chiudi inventario e rettifica giacenze
        </button>
      </div>

      <Modal open={confirmClose} onClose={()=>setConfirmClose(false)} title="Confermi la chiusura dell'inventario?" width="max-w-[520px]"
        footer={
          <div className="flex justify-end gap-2">
            <Btn variant="outline" size="md" onClick={()=>setConfirmClose(false)}>Annulla</Btn>
            <Btn variant="primary" size="md" onClick={()=>{
              setConfirmClose(false);
              if (window.__API__) window.__API__.mutate('/api/inventory/close', { storeId: ((typeof activeStoreId !== 'undefined' && activeStoreId && activeStoreId !== 'all') ? activeStoreId : ((window.STORE && window.STORE.id) || 'roma-spagna')), counted, rows: INVENTORY_ROWS.map(r => ({ sku: r.sku, name: r.name, expected: r.expected })) }).then(() => { if (window.__toast) window.__toast('Inventario chiuso · rettifiche generate'); try { fetch('/api/inventory/draft?store=' + encodeURIComponent(_store), { method: 'DELETE', credentials: 'same-origin' }); } catch (e) {} }).catch(()=>{});
            }}>Conferma e rettifica</Btn>
          </div>
        }>
        <div className="space-y-3 text-[14px]">
          <p className="text-muted">La chiusura genererà <span className="text-ink font-medium">{discrepancies} rettifiche</span> per allineare le giacenze a sistema con i conteggi fisici.</p>
          <div className="p-4 rounded-md bg-paper border border-line space-y-2 text-[13.5px]">
            <div className="flex justify-between"><span className="text-muted">Articoli rilevati</span><span className="num text-ink font-medium">{surveyed} / {totalRows}</span></div>
            <div className="flex justify-between"><span className="text-muted">Pezzi a sistema</span><span className="num text-ink">{totalExpected}</span></div>
            <div className="flex justify-between"><span className="text-muted">Pezzi contati</span><span className="num text-ink">{totalCounted}</span></div>
            <div className="flex justify-between pt-2 border-t border-line"><span className="text-ink font-medium">Saldo netto</span>
              <span className={`num font-semibold ${totalDelta === 0 ? 'text-ink' : totalDelta > 0 ? 'text-pos' : 'text-neg'}`}>
                {totalDelta > 0 ? '+' : ''}{totalDelta} pezzi
              </span>
            </div>
          </div>
          {toSurvey > 0 && (
            <p className="text-[12.5px] text-warn">⚠ {toSurvey} articoli non sono stati rilevati: verranno assunti a 0 pezzi.</p>
          )}
        </div>
      </Modal>
    </div>
  );
};

const KpiTile = ({ label, value, sub, tone }) => {
  const colors = {
    pos:  'text-pos',
    warn: 'text-warn',
    neg:  'text-neg',
  };
  return (
    <div className="bg-surface rounded-2xl p-4 shadow-soft">
      <div className="text-[11px] uppercase tracking-[0.08em] text-muted font-medium">{label}</div>
      <div className={`num mt-1.5 text-[28px] font-semibold ${tone ? colors[tone] : 'text-ink'}`}>{value}</div>
      <div className="text-[12px] text-muted mt-0.5">{sub}</div>
    </div>
  );
};

// ───────────────────────────── Ricezione trasferimento ─────────────────────
const RicezioneView = ({ transfer, onBack, onConfirm }) => {
  const lines = (TRANSFER_LINES && TRANSFER_LINES[transfer.id]) || [];
  const [received, setReceived] = useStateM(
    () => Object.fromEntries(lines.map(l => [l.sku, l.qty]))
  );

  const from = STORES.find(s => s.id === transfer.from);
  const to   = STORES.find(s => s.id === transfer.to);

  const totalExpected = lines.reduce((s, l) => s + l.qty, 0);
  const totalReceived = lines.reduce((s, l) => s + (received[l.sku] || 0), 0);
  const discrepancies = lines.filter(l => (received[l.sku] || 0) !== l.qty).length;
  const excessCount   = lines.filter(l => (received[l.sku] || 0) > l.qty).length;
  const shortCount    = lines.filter(l => (received[l.sku] || 0) < l.qty).length;

  const setQty = (sku, v) =>
    setReceived(prev => ({ ...prev, [sku]: Math.max(0, parseInt(v) || 0) }));

  return (
    <div className="px-7 py-6 max-w-[1400px]">
      {/* Intestazione */}
      <div className="flex flex-wrap items-center justify-between gap-3 mb-4">
        <div>
          <button onClick={onBack} className="text-[13px] text-muted hover:text-ink inline-flex items-center gap-1.5 mb-1">
            <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round" strokeLinejoin="round"><path d="M15 6l-6 6 6 6"/></svg>
            Torna ai trasferimenti
          </button>
          <div className="text-[11px] uppercase tracking-[0.08em] text-muted font-medium">Ricezione merce · {STORE.name}</div>
          <div className="text-[20px] font-semibold tracking-tight text-ink mt-0.5">{transfer.id} · {transfer.date}</div>
        </div>
        <Btn variant="outline" size="md" leading={<I.ArrowD size={16}/>}
          onClick={()=>{ if(window.__csv) window.__csv(`DDT-${transfer.id}.csv`, ['SKU','Articolo','Atteso','Ricevuto','Differenza'], lines.map(l=>{ const rec = received[l.sku]||0; return [l.sku, l.name, l.qty, rec, rec-l.qty]; })); }}>Esporta DDT</Btn>
      </div>

      {/* KPI */}
      <div className="grid grid-cols-4 gap-4 mb-4">
        <KpiTile label="Pezzi attesi"   value={totalExpected} sub={`${lines.length} righe DDT`}/>
        <KpiTile label="Pezzi ricevuti" value={totalReceived} sub="da conteggio fisico"
          tone={totalReceived === totalExpected ? 'pos' : totalReceived > 0 ? 'warn' : undefined}/>
        <KpiTile label="In eccesso"  value={excessCount}  sub="righe extra"     tone={excessCount  > 0 ? 'warn' : undefined}/>
        <KpiTile label="Mancanti"    value={shortCount}   sub="righe in difetto" tone={shortCount   > 0 ? 'neg'  : undefined}/>
      </div>

      {/* Card informazioni trasferimento */}
      <div className="bg-surface rounded-2xl p-5 mb-4 shadow-soft">
        <div className="grid grid-cols-[1fr_40px_1fr_1fr_1fr] gap-4 items-start">
          <div>
            <div className="text-[11px] uppercase tracking-[0.08em] text-muted font-medium">Mittente</div>
            <div className="mt-1 text-[15px] font-semibold text-ink">{from?.name}</div>
            <div className="text-[12px] text-muted">{from?.city}</div>
          </div>
          <div className="flex items-center justify-center pt-5">
            <I.ArrowR size={18} className="text-muted"/>
          </div>
          <div>
            <div className="text-[11px] uppercase tracking-[0.08em] text-muted font-medium">Destinatario</div>
            <div className="mt-1 text-[15px] font-semibold text-ink">{to?.name}</div>
            <div className="text-[12px] text-muted">{to?.city}</div>
          </div>
          <KeyVal label="Data partenza" value={transfer.date}/>
          <KeyVal label="N° trasferimento" value={transfer.id} mono/>
        </div>
      </div>

      {/* Griglia confronto riga per riga */}
      <Card padded={false} title="Confronto DDT vs ricevuto">
        <div className="grid grid-cols-[1fr_88px_130px_100px_130px] gap-2 px-5 h-11 items-center text-[11px] uppercase tracking-[0.08em] text-muted font-medium hairline">
          <div>Articolo · SKU</div>
          <div className="text-right">Atteso</div>
          <div className="text-right">Ricevuto</div>
          <div className="text-right">Differenza</div>
          <div className="text-center">Stato</div>
        </div>
        <div className="divide-y divide-line2">
          {lines.map(l => {
            const rec   = received[l.sku] || 0;
            const delta = rec - l.qty;
            const ok     = delta === 0;
            const excess = delta > 0;
            const rowBg  = ok ? 'bg-[var(--success-50)]' : excess ? 'bg-[var(--warning-50)]' : 'bg-[var(--danger-50)]';
            return (
              <div key={l.sku}
                className={`row-h grid grid-cols-[1fr_88px_130px_100px_130px] gap-2 px-5 items-center transition-all duration-fast ease-standard ${rowBg}`}>
                <div className="flex items-center gap-3 min-w-0">
                  <ProductThumb size={40}/>
                  <div className="min-w-0">
                    <div className="text-[14px] font-medium text-ink truncate">{l.name}</div>
                    <div className="num text-[11.5px] text-muted mt-0.5">{l.sku}</div>
                  </div>
                </div>
                <div className="num text-[16px] text-ink text-right">{l.qty}</div>
                <div className="flex justify-end">
                  <input
                    type="number" min="0"
                    value={rec === 0 ? '' : rec}
                    onChange={e => setQty(l.sku, e.target.value)}
                    placeholder={String(l.qty)}
                    className="w-20 h-11 px-2 rounded-sm border border-line bg-surface num text-[15px] text-right focus:border-strong transition-all"
                  />
                </div>
                <div className={`num text-[15px] text-right font-semibold ${ok ? 'text-pos' : excess ? 'text-warn' : 'text-neg'}`}>
                  {ok ? '0' : excess ? `+${delta}` : String(delta)}
                </div>
                <div className="flex justify-center">
                  {ok     && <Pill tone="pos"><I.Check size={11}/> Match</Pill>}
                  {excess && <Pill tone="warn">+{delta} eccedente</Pill>}
                  {!ok && !excess && <Pill tone="neg">{delta} mancante</Pill>}
                </div>
              </div>
            );
          })}
          {lines.length === 0 && (
            <div className="py-16 text-center text-muted text-[14px]">Nessuna riga DDT disponibile per questo trasferimento.</div>
          )}
        </div>
      </Card>

      {/* Footer sticky con CTA 64px */}
      <div className="mt-5 sticky bottom-0 glass-thin rounded-2xl p-4 shadow-popover flex items-center justify-between gap-4">
        <div>
          {discrepancies === 0 && lines.length > 0
            ? <div className="text-[12.5px] text-pos font-medium flex items-center gap-1.5"><I.Check size={14}/> Tutto corrisponde al DDT — nessuna rettifica necessaria</div>
            : discrepancies > 0
              ? <div className="text-[12.5px] text-warn">{discrepancies} riga{discrepancies > 1 ? 'he' : ''} con scostamento — verrà generata una rettifica automatica</div>
              : null
          }
          <div className="num text-[24px] font-semibold text-ink mt-1">
            {totalReceived} <span className="text-muted text-[16px] font-normal">/ {totalExpected} pezzi attesi</span>
          </div>
        </div>
        <button
          onClick={() => onConfirm(transfer.id, received)}
          disabled={lines.length === 0}
          className="h-16 px-8 rounded-md bg-[var(--accent-blue)] text-[var(--text-inverse)] font-semibold text-[17px] flex items-center gap-3 hover:bg-[var(--accent-blue-hover)] active:bg-[var(--accent-blue-active)] disabled:opacity-30 disabled:cursor-not-allowed transition-all duration-fast ease-standard shadow-soft"
        >
          <I.Check size={20}/>
          Conferma ricezione
        </button>
      </div>
    </div>
  );
};

// ───────────────────────────── 3) TRASFERIMENTI ─────────────────────────
const Trasferimenti = ({ activeStoreId = STORE.id, readOnly = false }) => {
  const [step, setStep] = useStateM(0); // 0 = lista; 1-3 = wizard
  const [dest, setDest] = useStateM(null);
  const [items, setItems] = useStateM([]); // { article, color, size, qty }
  const [sentRef, setSentRef] = useStateM(null);
  const [receiveId, setReceiveId] = useStateM(null);
  const [receivedLocally, setReceivedLocally] = useStateM(() => new Set());
  const [receiveToast, setReceiveToast] = useStateM(null);

  // Wizard step labels
  const WIZ = [
    { id: 1, label: 'Destinazione' },
    { id: 2, label: 'Articoli' },
    { id: 3, label: 'Riepilogo' },
  ];

  const visibleTransfers = useMemoM(() =>
    activeStoreId === 'all'
      ? TRANSFERS
      : TRANSFERS.filter(t => t.from === activeStoreId || t.to === activeStoreId),
    [activeStoreId]);

  const effectiveStatus = (t) => receivedLocally.has(t.id) ? 'Ricevuto' : t.status;

  const confirmReception = (id, receivedQtys) => {
    if (window.__API__) window.__API__.mutate('/api/transfers/' + encodeURIComponent(id) + '/receive', { received: receivedQtys }).then(()=>{ if (window.__toast) window.__toast('Trasferimento ricevuto · carico effettuato', 'success'); }).catch(()=>{});
    setReceivedLocally(prev => new Set([...prev, id]));
    setReceiveId(null);
    setReceiveToast(id);
    setTimeout(() => setReceiveToast(null), 4000);
  };

  if (receiveId) {
    const t = TRANSFERS.find(x => x.id === receiveId);
    return <RicezioneView transfer={t} onBack={() => setReceiveId(null)} onConfirm={confirmReception}/>;
  }

  if (step === 0) {
    // List view of past + new button
    return (
      <div className="px-7 py-6 space-y-4 max-w-[1400px]">
        <div className="flex items-center justify-between">
          <div>
            <h2 className="text-[18px] font-semibold tracking-tight text-ink">Trasferimenti tra negozi</h2>
            <p className="text-[13.5px] text-muted mt-0.5">Cronologia trasferimenti in entrata e uscita per il negozio corrente.</p>
          </div>
          <Btn variant="primary" size="lg" leading={<I.Plus size={16}/>} disabled={readOnly} onClick={()=>{ if(!readOnly){setStep(1); setDest(null); setItems([]);} }}>
            Nuovo trasferimento
          </Btn>
        </div>

        <div className="grid grid-cols-3 gap-4">
          <KpiTile label="In viaggio"     value={visibleTransfers.filter(t=>effectiveStatus(t)==='In viaggio').length} sub="da ricevere" tone="warn"/>
          <KpiTile label="Ricevuti (30g)" value={visibleTransfers.filter(t=>effectiveStatus(t)==='Ricevuto').length}  sub="completati"/>
          <KpiTile label="Articoli scambiati" value={visibleTransfers.reduce((s,t)=>s+t.items,0)}            sub="ultimi 30 giorni"/>
        </div>

        <Card title="Cronologia trasferimenti" padded={false}>
          <table className="w-full text-[13.5px]">
            <thead>
              <tr className="text-left text-muted uppercase text-[11px] tracking-[0.08em] hairline">
                <th className="px-5 py-3 font-medium">ID</th>
                <th className="px-5 py-3 font-medium">Data</th>
                <th className="px-5 py-3 font-medium">Da</th>
                <th className="px-5 py-3 font-medium">A</th>
                <th className="px-5 py-3 font-medium text-right">Articoli</th>
                <th className="px-5 py-3 font-medium">Stato</th>
                <th className="px-5 py-3 font-medium"></th>
              </tr>
            </thead>
            <tbody>
              {visibleTransfers.map(t => {
                const from = STORES.find(s=>s.id===t.from);
                const to   = STORES.find(s=>s.id===t.to);
                return (
                  <tr key={t.id} className="hover:bg-paper border-b border-line2 last:border-0">
                    <td className="px-5 py-3.5 num text-ink font-medium">{t.id}</td>
                    <td className="px-5 py-3.5 text-ink">{t.date}</td>
                    <td className="px-5 py-3.5 text-ink">{from?.name}</td>
                    <td className="px-5 py-3.5">
                      <span className="inline-flex items-center gap-2 text-ink">
                        <I.ArrowR size={13} className="text-muted"/>
                        {to?.name}
                      </span>
                    </td>
                    <td className="px-5 py-3.5 num text-ink text-right">{t.items}</td>
                    <td className="px-5 py-3.5">
                      {effectiveStatus(t) === 'In viaggio' && <Pill tone="warn"><I.Truck size={11}/> In viaggio</Pill>}
                      {effectiveStatus(t) === 'Ricevuto'   && <Pill tone="pos"><I.Check size={11}/> Ricevuto</Pill>}
                    </td>
                    <td className="px-5 py-3.5 text-right">
                      {(activeStoreId === 'all' || t.to === activeStoreId) && effectiveStatus(t) === 'In viaggio' ? (
                        <button
                          onClick={() => !readOnly && setReceiveId(t.id)}
                          disabled={readOnly}
                          className="h-9 px-3 rounded-md bg-[var(--warning-50)] text-[var(--warning-700)] text-[12.5px] font-medium hover:bg-[var(--warning-100)] active:bg-[var(--warning-200)] transition-colors duration-fast ease-standard flex items-center gap-1.5 ml-auto disabled:opacity-40 disabled:cursor-not-allowed">
                          <I.Truck size={13}/>
                          Ricevi merce
                        </button>
                      ) : (
                        <button onClick={()=>setReceiveId(t.id)} className="text-[12.5px] text-ink hover:underline">Apri</button>
                      )}
                    </td>
                  </tr>
                );
              })}
            </tbody>
          </table>
        </Card>
      </div>
    );
  }

  // Wizard
  const totalQty = items.reduce((s,i)=>s+i.qty, 0);
  const canNext = (step === 1 && dest) || (step === 2 && items.length > 0) || step === 3;

  const addItem = (article, color, size) => {
    setItems(prev => {
      const existing = prev.findIndex(x => x.article.id === article.id && x.color === color && x.size === size);
      if (existing >= 0) {
        const next = [...prev];
        next[existing] = { ...next[existing], qty: next[existing].qty + 1 };
        return next;
      }
      return [...prev, { article, color, size, qty: 1 }];
    });
  };
  const setItemQty = (idx, q) => {
    if (q <= 0) return setItems(prev => prev.filter((_,i)=>i!==idx));
    setItems(prev => prev.map((x,i)=> i===idx ? { ...x, qty: q } : x));
  };

  return (
    <div className="px-7 py-6 max-w-[1400px]">
      {/* Wizard header */}
      <div className="bg-surface rounded-2xl p-5 mb-5 shadow-soft">
        <div className="flex items-center justify-between mb-1">
          <button onClick={()=>setStep(0)} className="text-[13px] text-muted hover:text-ink inline-flex items-center gap-1.5">
            <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round" strokeLinejoin="round"><path d="M15 6l-6 6 6 6"/></svg>
            Torna ai trasferimenti
          </button>
          <span className="text-[12px] text-muted">Origine · <span className="text-ink font-medium">{STORES.find(s=>s.id===activeStoreId)?.name || STORE.name}</span></span>
        </div>
        <h2 className="text-[22px] font-semibold tracking-tight text-ink mt-2">Nuovo trasferimento</h2>

        {/* Steps progress */}
        <div className="mt-4 flex items-center gap-1">
          {WIZ.map((w, i) => {
            const active = step === w.id;
            const done = step > w.id;
            return (
              <React.Fragment key={w.id}>
                <div className="flex items-center gap-3 px-1">
                  <span className={`w-9 h-9 rounded-full flex items-center justify-center text-[14px] font-semibold transition-all duration-fast ease-standard
                    ${done ? 'bg-pos text-white' : active ? 'bg-[var(--bg-selected)] text-[var(--accent-blue)]' : 'bg-line2 text-muted'}`}>
                    {done ? <I.Check size={16}/> : w.id}
                  </span>
                  <span className={`text-[14px] font-medium ${active ? 'text-ink' : done ? 'text-ink' : 'text-muted'}`}>{w.label}</span>
                </div>
                {i < WIZ.length - 1 && (
                  <div className={`flex-1 h-px ${done ? 'bg-pos' : 'bg-line'}`}></div>
                )}
              </React.Fragment>
            );
          })}
        </div>
      </div>

      {/* Step 1: Destination */}
      {step === 1 && (
        <Card title="Scegli il negozio destinazione">
          <div className="grid grid-cols-2 gap-3">
            {STORES.filter(s => s.id !== activeStoreId).map(s => {
              const sel = dest === s.id;
              return (
                <button key={s.id} onClick={()=>setDest(s.id)}
                  className={`text-left p-5 rounded-md border-2 transition-all duration-fast ease-standard flex items-center gap-4
                    ${sel ? 'bg-[var(--bg-selected)] shadow-[inset_0_0_0_1px_var(--accent-blue)]' : 'border-line bg-surface hover:border-strong'}`}>
                  <span className={`w-12 h-12 rounded-md flex items-center justify-center ${sel ? 'bg-[var(--bg-selected)] text-[var(--accent-blue)]' : 'bg-line2 text-muted'}`}>
                    <I.Store size={22}/>
                  </span>
                  <div className="flex-1 min-w-0">
                    <div className="text-[16px] font-semibold text-ink">{s.name}</div>
                    <div className="text-[12.5px] text-muted">{s.city} · {s.short}</div>
                  </div>
                  {sel && <I.Check size={20} className="text-ink"/>}
                </button>
              );
            })}
          </div>
        </Card>
      )}

      {/* Step 2: Items */}
      {step === 2 && (
        <div className="grid grid-cols-[1fr_360px] gap-5">
          <Card title="Aggiungi articoli" padded={false}>
            <ItemPicker onAdd={addItem} activeStoreId={activeStoreId}/>
          </Card>
          <Card title={`Da trasferire (${items.length})`} padded={false}>
            {items.length === 0 ? (
              <div className="p-8 text-center text-muted text-[13.5px]">Nessun articolo aggiunto. Selezionali dalla lista a sinistra.</div>
            ) : (
              <div className="divide-y divide-line2">
                {items.map((it, idx) => (
                  <div key={idx} className="px-4 py-3 flex items-center gap-3">
                    <ProductThumb size={36}/>
                    <div className="flex-1 min-w-0">
                      <div className="text-[13.5px] font-medium text-ink truncate">{it.article.name}</div>
                      <div className="text-[11.5px] text-muted">{it.color} · Tg {it.size}</div>
                    </div>
                    <div className="flex items-center border border-line rounded-sm overflow-hidden">
                      <button onClick={()=>setItemQty(idx, it.qty-1)} className="w-8 h-9 hover:bg-[var(--bg-hover)] flex items-center justify-center"><I.Minus size={12}/></button>
                      <span className="w-9 text-center num text-[14px] font-medium text-ink">{it.qty}</span>
                      <button onClick={()=>setItemQty(idx, it.qty+1)} className="w-8 h-9 hover:bg-[var(--bg-hover)] flex items-center justify-center"><I.Plus size={12}/></button>
                    </div>
                  </div>
                ))}
                <div className="px-4 py-3 bg-paper flex items-center justify-between">
                  <span className="text-[13px] text-muted">Totale pezzi</span>
                  <span className="num text-[18px] font-semibold text-ink">{totalQty}</span>
                </div>
              </div>
            )}
          </Card>
        </div>
      )}

      {/* Step 3: Summary */}
      {step === 3 && (
        <Card title="Riepilogo trasferimento">
          <div className="grid grid-cols-3 gap-6 mb-5 pb-5 border-b border-line">
            <div>
              <div className="text-[11px] uppercase tracking-[0.08em] text-muted font-medium">Da</div>
              <div className="mt-1 text-[15px] font-semibold text-ink">{STORES.find(s=>s.id===activeStoreId)?.name || STORE.name}</div>
              <div className="text-[12px] text-muted">{STORES.find(s=>s.id===activeStoreId)?.city || STORE.address}</div>
            </div>
            <div className="flex items-center justify-center">
              <I.ArrowR size={22} className="text-muted"/>
            </div>
            <div>
              <div className="text-[11px] uppercase tracking-[0.08em] text-muted font-medium">A</div>
              <div className="mt-1 text-[15px] font-semibold text-ink">{STORES.find(s=>s.id===dest)?.name}</div>
              <div className="text-[12px] text-muted">{STORES.find(s=>s.id===dest)?.city}</div>
            </div>
          </div>

          <div className="grid grid-cols-4 gap-4 mb-5">
            <KeyVal label="ID provvisorio" value="TF 2026-0020" mono/>
            <KeyVal label="Data emissione" value="21 mag 2026"/>
            <KeyVal label="Operatore"      value={STORE.cashier}/>
            <KeyVal label="Articoli totali" value={`${items.length} righe · ${totalQty} pezzi`}/>
          </div>

          <div className="bg-surface shadow-md rounded-2xl overflow-hidden">
            <table className="w-full text-[13.5px]">
              <thead>
                <tr className="text-left text-muted uppercase text-[11px] tracking-[0.08em] hairline">
                  <th className="px-4 py-2.5 font-medium">Articolo</th>
                  <th className="px-4 py-2.5 font-medium">Variante</th>
                  <th className="px-4 py-2.5 font-medium text-right">Quantità</th>
                </tr>
              </thead>
              <tbody>
                {items.map((it, idx) => (
                  <tr key={idx} className="border-b border-line2 last:border-0">
                    <td className="px-4 py-2.5 text-ink">{it.article.name}</td>
                    <td className="px-4 py-2.5 text-ink">{it.color} · Tg {it.size}</td>
                    <td className="px-4 py-2.5 num text-ink text-right font-medium">{it.qty}</td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>

          <div className="mt-5 p-4 rounded-md bg-paper border border-line text-[13px] text-muted">
            <span className="text-ink font-medium">Cosa succederà.</span> Confermando, verrà generato un DDT di uscita per {STORES.find(s=>s.id===activeStoreId)?.name || STORE.name} e i pezzi resteranno in stato "in viaggio" fino alla ricezione da parte di {STORES.find(s=>s.id===dest)?.name}.
          </div>
        </Card>
      )}

      {/* Wizard footer */}
      <div className="mt-5 flex items-center justify-between bg-surface rounded-2xl p-4 shadow-soft">
        <div>
          {step > 1 && (
            <Btn variant="outline" size="lg" onClick={()=>setStep(step-1)}
              leading={<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round" strokeLinejoin="round"><path d="M15 6l-6 6 6 6"/></svg>}>
              Indietro
            </Btn>
          )}
        </div>
        <div className="flex items-center gap-3">
          <span className="text-[12.5px] text-muted">Step {step} di 3</span>
          {step < 3 ? (
            <Btn variant="primary" size="lg" disabled={!canNext} onClick={()=>setStep(step+1)} trailing={<I.ArrowR size={18}/>}>
              {step === 1 ? 'Aggiungi articoli' : 'Vai al riepilogo'}
            </Btn>
          ) : (
            <Btn variant="success" size="lg" onClick={()=>{
              const __from = ((typeof activeStoreId !== 'undefined' && activeStoreId && activeStoreId !== 'all') ? activeStoreId : ((window.STORE && window.STORE.id) || 'roma-spagna'));
              if (window.__API__) { window.__API__.mutate('/api/transfers', { from: __from, to: dest, items: items.map(it => ({ articleId: it.article.id, name: it.article.name + ' · ' + it.color + ' · ' + it.size, color: it.color, size: it.size, qty: it.qty })) }).then(r => { setSentRef(r && r.id ? r.id : 'TF'); if (window.__toast) window.__toast('Trasferimento creato', 'success'); }).catch(()=>setSentRef('TF')); }
              else { setSentRef('TF 2026-0020'); }
              setStep(0); setDest(null); setItems([]);
              setTimeout(() => setSentRef(null), 4000);
            }} leading={<I.Check size={18}/>}>
              Conferma e genera DDT
            </Btn>
          )}
        </div>
      </div>

      {sentRef && (
        <div className="fixed bottom-6 right-6 z-toast bg-[var(--success-500)] text-[var(--text-inverse)] px-5 py-3 rounded-md shadow-popover flex items-center gap-2.5">
          <I.Check size={20}/>
          <span className="text-[14px] font-medium">Trasferimento {sentRef} creato</span>
        </div>
      )}
      {receiveToast && (
        <div className="fixed bottom-6 right-6 z-toast bg-[var(--success-500)] text-[var(--text-inverse)] px-5 py-3 rounded-md shadow-popover flex items-center gap-2.5">
          <I.Check size={20}/>
          <span className="text-[14px] font-medium">Ricezione {receiveToast} confermata</span>
        </div>
      )}
    </div>
  );
};

// ─── Item picker for transfer step 2 ───
const ItemPicker = ({ onAdd, activeStoreId = STORE.id }) => {
  const [q, setQ] = useStateM('');
  const [active, setActive] = useStateM(null); // article id

  const ql = q.trim().toLowerCase();
  const filtered = ARTICLES.filter(a =>
    !ql || a.name.toLowerCase().includes(ql) || a.id.toLowerCase().includes(ql) || a.brand.toLowerCase().includes(ql)
  );

  return (
    <>
      <div className="p-3 hairline">
        <div className="relative">
          <I.Search size={16} className="absolute left-3 top-1/2 -translate-y-1/2 text-muted"/>
          <input value={q} onChange={(e)=>setQ(e.target.value)}
            placeholder="Cerca articolo da trasferire…"
            className="w-full h-10 pl-9 pr-3 rounded-sm border border-line bg-paper text-[13.5px] focus:border-strong"/>
        </div>
      </div>

      {!active ? (
        <div className="max-h-[460px] overflow-auto">
          {filtered.map(a => {
            const tot = totalStock(a, activeStoreId);
            return (
              <button key={a.id} onClick={()=>setActive(a.id)}
                className="w-full px-4 py-3 flex items-center gap-3 hover:bg-paper text-left border-b border-line2 last:border-0">
                <ProductThumb size={40}/>
                <div className="flex-1 min-w-0">
                  <div className="text-[13.5px] font-medium text-ink truncate">{a.name}</div>
                  <div className="text-[11.5px] text-muted">{a.brand} · {a.cat} · {tot} disp.</div>
                </div>
                <I.ArrowR size={14} className="text-muted"/>
              </button>
            );
          })}
          {filtered.length === 0 && (
            <div className="p-8 text-center text-muted text-[13.5px]">Nessun articolo trovato.</div>
          )}
        </div>
      ) : (
        <VariantPicker
          article={ARTICLES.find(a=>a.id===active)}
          activeStoreId={activeStoreId}
          onBack={()=>setActive(null)}
          onPick={(color, size) => onAdd(ARTICLES.find(a=>a.id===active), color, size)}
        />
      )}
    </>
  );
};

const VariantPicker = ({ article, onBack, onPick, activeStoreId = STORE.id }) => {
  const matrix = article.stock[activeStoreId] || {};
  return (
    <div className="p-4">
      <button onClick={onBack} className="text-[13px] text-muted hover:text-ink inline-flex items-center gap-1.5 mb-3">
        <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round" strokeLinejoin="round"><path d="M15 6l-6 6 6 6"/></svg>
        Cambia articolo
      </button>
      <div className="text-[14px] font-semibold text-ink">{article.name}</div>
      <div className="text-[11.5px] text-muted mb-3">{article.brand} · scegli la variante da aggiungere</div>

      <div className="overflow-x-auto">
        <table className="text-[12.5px] w-full border-separate border-spacing-0">
          <thead>
            <tr>
              <th className="text-left px-2 py-1.5 text-[10.5px] uppercase tracking-[0.08em] text-muted font-medium">Tg</th>
              {article.colors.map(c => (
                <th key={c} className="px-1.5 py-1.5">
                  <ColorDot name={c} size={12}/>
                </th>
              ))}
            </tr>
          </thead>
          <tbody>
            {article.sizes.map(s => (
              <tr key={s}>
                <td className="px-2 py-1 num text-[12px] text-ink">{s}</td>
                {article.colors.map(c => {
                  const v = matrix[c]?.[s] ?? 0;
                  const disabled = v === 0;
                  return (
                    <td key={c} className="px-0.5 py-0.5">
                      <button
                        disabled={disabled}
                        onClick={()=>onPick(c, s)}
                        className={`w-11 h-10 rounded-xs border text-[12.5px] num font-medium transition-all duration-fast ease-standard
                          ${disabled ? 'border-line2 bg-sunken text-[var(--text-disabled)] cursor-not-allowed' : 'border-line bg-surface text-ink hover:border-ink hover:bg-paper'}`}>
                        {v}
                      </button>
                    </td>
                  );
                })}
              </tr>
            ))}
          </tbody>
        </table>
      </div>
    </div>
  );
};

// ─── Top-level wrapper ───
// ───────────────────────────── RICHIESTE TRA NEGOZI ─────────────────────────
// Il negozio corrente chiede merce a un altro negozio/magazzino. Quando la
// richiesta viene EVASA dal fornitore, genera un trasferimento verso il richiedente.
const Richieste = ({ activeStoreId = STORE.id, readOnly = false }) => {
  const myStore = (activeStoreId && activeStoreId !== 'all') ? activeStoreId : (STORE.id);
  const reqs = (typeof REQUESTS !== 'undefined' ? REQUESTS : (window.REQUESTS || []));
  const otherStores = STORES.filter(s => s.id !== myStore);
  const [creating, setCreating] = useStateM(false);
  const [to, setTo] = useStateM(otherStores[0]?.id || '');
  const [artId, setArtId] = useStateM('');
  const [color, setColor] = useStateM('');
  const [size, setSize] = useStateM('');
  const [qty, setQty] = useStateM('1');
  const [note, setNote] = useStateM('');

  const art = (ARTICLES || []).find(a => a.id === artId);
  const colors = art ? (art.colors || Object.keys(art.stock?.[myStore] || {})) : [];
  const sizes = art ? (art.sizes || []) : [];

  const tone = (s) => s === 'In attesa' ? 'warn' : s === 'Evasa' ? 'pos' : s === 'Rifiutata' ? 'neg' : 'neutral';
  const storeName = (id) => STORES.find(s => s.id === id)?.name || id;

  const submit = () => {
    if (!to || !artId || !color || !size || !(parseInt(qty) > 0)) { if (window.__toast) window.__toast('Compila articolo, colore, taglia e quantità', 'error'); return; }
    if (window.__API__) window.__API__.mutate('/api/requests', { from: myStore, to, note: note.trim(), items: [{ articleId: artId, name: art?.name, color, size, qty: parseInt(qty) }] })
      .then(() => { if (window.__toast) window.__toast('Richiesta inviata a ' + storeName(to), 'success'); setCreating(false); setArtId(''); setColor(''); setSize(''); setQty('1'); setNote(''); }).catch(()=>{});
  };
  const fulfill = (id) => { if (window.__API__) window.__API__.mutate('/api/requests/' + encodeURIComponent(id) + '/fulfill', {}).then(()=>{ if (window.__toast) window.__toast('Richiesta evasa · trasferimento generato', 'success'); }).catch(()=>{}); };
  const reject = (id) => { if (window.__API__) window.__API__.mutate('/api/requests/' + encodeURIComponent(id) + '/reject', {}).then(()=>{ if (window.__toast) window.__toast('Richiesta rifiutata', 'info'); }).catch(()=>{}); };

  // richieste ricevute (altri chiedono a me) vs inviate (io chiedo)
  const incoming = reqs.filter(r => r.to === myStore);
  const outgoing = reqs.filter(r => r.from === myStore);

  return (
    <div className="px-7 py-6 max-w-[1100px] space-y-6">
      <div className="flex items-center justify-between">
        <h2 className="text-[18px] font-semibold tracking-tight text-ink">Richieste tra negozi</h2>
        {!readOnly && <Btn variant="primary" size="md" leading={<I.Plus size={16}/>} onClick={() => setCreating(v => !v)}>Nuova richiesta</Btn>}
      </div>

      {creating && (
        <Card title="Richiedi un prodotto a un altro negozio">
          <div className="grid grid-cols-2 gap-3">
            <label className="block"><span className="text-[12px] text-muted">Negozio fornitore</span>
              <select className="w-full h-11 px-3 rounded-md border border-line bg-surface text-[14px] mt-1" value={to} onChange={e=>setTo(e.target.value)}>
                {otherStores.map(s => <option key={s.id} value={s.id}>{s.name}</option>)}
              </select></label>
            <label className="block"><span className="text-[12px] text-muted">Articolo</span>
              <select className="w-full h-11 px-3 rounded-md border border-line bg-surface text-[14px] mt-1" value={artId} onChange={e=>{ setArtId(e.target.value); setColor(''); setSize(''); }}>
                <option value="">— scegli —</option>
                {(ARTICLES||[]).map(a => <option key={a.id} value={a.id}>{a.name}</option>)}
              </select></label>
            <label className="block"><span className="text-[12px] text-muted">Colore</span>
              <select className="w-full h-11 px-3 rounded-md border border-line bg-surface text-[14px] mt-1" value={color} onChange={e=>setColor(e.target.value)} disabled={!art}>
                <option value="">—</option>{colors.map(c => <option key={c} value={c}>{c}</option>)}
              </select></label>
            <label className="block"><span className="text-[12px] text-muted">Taglia</span>
              <select className="w-full h-11 px-3 rounded-md border border-line bg-surface text-[14px] mt-1" value={size} onChange={e=>setSize(e.target.value)} disabled={!art}>
                <option value="">—</option>{sizes.map(s => <option key={s} value={s}>{s}</option>)}
              </select></label>
            <label className="block"><span className="text-[12px] text-muted">Quantità</span>
              <input type="number" min="1" className="w-full h-11 px-3 rounded-md border border-line bg-surface text-[14px] num mt-1" value={qty} onChange={e=>setQty(e.target.value)}/></label>
            <label className="block"><span className="text-[12px] text-muted">Nota (facoltativa)</span>
              <input className="w-full h-11 px-3 rounded-md border border-line bg-surface text-[14px] mt-1" value={note} onChange={e=>setNote(e.target.value)} placeholder="es. urgente per cliente"/></label>
          </div>
          <div className="mt-4 flex justify-end gap-2">
            <Btn variant="outline" size="md" onClick={()=>setCreating(false)}>Annulla</Btn>
            <Btn variant="primary" size="md" onClick={submit}>Invia richiesta</Btn>
          </div>
        </Card>
      )}

      <Card title={`Richieste ricevute (${incoming.length})`} padded={false}>
        {incoming.length === 0 ? <div className="px-5 py-6 text-muted text-[13.5px]">Nessuna richiesta da altri negozi.</div> :
          incoming.map(r => (
            <div key={r.id} className="flex items-center justify-between px-5 py-3 border-b border-line2 last:border-0">
              <div className="min-w-0"><span className="num text-[13px] text-ink font-medium">{r.id}</span> <span className="text-[13px] text-muted">da {storeName(r.from)} · {r.items} art. · {r.date}</span>{r.note ? <div className="text-[12px] text-muted truncate">“{r.note}”</div> : null}</div>
              <div className="flex items-center gap-2 shrink-0">
                <Pill tone={tone(r.status)}>{r.status}</Pill>
                {!readOnly && r.status === 'In attesa' && <>
                  <Btn variant="success" size="sm" onClick={()=>fulfill(r.id)}>Evadi</Btn>
                  <Btn variant="outline" size="sm" onClick={()=>reject(r.id)}>Rifiuta</Btn>
                </>}
              </div>
            </div>
          ))}
      </Card>

      <Card title={`Richieste inviate (${outgoing.length})`} padded={false}>
        {outgoing.length === 0 ? <div className="px-5 py-6 text-muted text-[13.5px]">Nessuna richiesta inviata.</div> :
          outgoing.map(r => (
            <div key={r.id} className="flex items-center justify-between px-5 py-3 border-b border-line2 last:border-0">
              <div className="min-w-0"><span className="num text-[13px] text-ink font-medium">{r.id}</span> <span className="text-[13px] text-muted">a {storeName(r.to)} · {r.items} art. · {r.date}</span></div>
              <Pill tone={tone(r.status)}>{r.status}</Pill>
            </div>
          ))}
      </Card>
    </div>
  );
};

const MagazzinoView = ({ activeStoreId = STORE.id, readOnly = false }) => {
  const [tab, setTab] = useStateM('inventario');
  const activeStoreName = STORES.find(s=>s.id===activeStoreId)?.name || STORE.name;
  return (
    <>
      <Topbar
        eyebrow={`Magazzino · ${activeStoreName}`}
        title="Magazzino"
        right={readOnly ? <Pill tone="warn"><I.Lock size={11}/> Sola lettura</Pill> : null}
      />
      <MagTabs tab={tab} onTab={setTab}/>
      {tab === 'movimenti'     && <Movimenti activeStoreId={activeStoreId}/>}
      {tab === 'inventario'    && <Inventario activeStoreId={activeStoreId} readOnly={readOnly}/>}
      {tab === 'trasferimenti' && <Trasferimenti activeStoreId={activeStoreId} readOnly={readOnly}/>}
      {tab === 'richieste'     && <Richieste activeStoreId={activeStoreId} readOnly={readOnly}/>}
    </>
  );
};

Object.assign(window, { MagazzinoView, KpiTile });
