// ──────────────────────────── Acquisti ────────────────────────────
const { useState: useStateAQ, useMemo: useMemoAQ, useEffect: useEffectAQ, useRef: useRefAQ } = React;

// ─── Pill tone per stato ordine/consegna ───
const ORDER_STATUS_TONE = {
  'Bozza':    'neutral',
  'Inviato':  'info',
  'Ricevuto': 'pos',
};
const DELIVERY_STATUS_TONE = {
  'Bozza':      'neutral',
  'Confermata': 'pos',
};
const RETURN_STATUS_TONE = {
  'Bozza':      'neutral',
  'Confermato': 'pos',
};
// Motivi reso: gestiti dall'Admin (LISTS.motivi_reso); fallback ai valori storici.
const getMotiviReso = () => (window.LISTS && window.LISTS.motivi_reso && window.LISTS.motivi_reso.length) ? window.LISTS.motivi_reso : ['Difettoso', 'Errato', 'Non conforme', 'Fine conto vendita', 'Altro'];

// ─── KPI tile locale ───
const AcqKpi = ({ label, value, sub, tone }) => {
  const tones = { 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 ? tones[tone] : 'text-ink'}`}>{value}</div>
      {sub && <div className="text-[12px] text-muted mt-0.5">{sub}</div>}
    </div>
  );
};

// ─── Sub-tabs nav ───
const AcqTabs = ({ tab, onTab }) => {
  const TABS = [
    { id: 'ordini',   label: 'Ordini',        icon: 'Receipt' },
    { id: 'consegne', label: 'Consegne',       icon: 'Truck' },
    { id: 'resi',     label: 'Resi fornitore', icon: 'Return' },
  ];
  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>
  );
};

// ─── Placeholder tab ───
const AcqPlaceholder = ({ label }) => (
  <div className="px-7 py-10 flex items-center justify-center">
    <div className="text-center p-10 rounded-2xl" style={{ border: '2px dashed var(--border-default)' }}>
      <I.Clock size={32} className="text-muted mx-auto mb-3"/>
      <div className="text-[17px] font-semibold text-ink">{label}</div>
      <div className="text-[13.5px] text-muted mt-1">In arrivo prossimamente</div>
    </div>
  </div>
);

// ─── CSV parser per consegne (rispetta campi quotati) ───
const parseCSVLineAQ = (line) => {
  const result = [];
  let cur = '';
  let inQ = false;
  for (let i = 0; i < line.length; i++) {
    const ch = line[i];
    if (ch === '"') { inQ = !inQ; }
    else if (ch === ',' && !inQ) { result.push(cur); cur = ''; }
    else { cur += ch; }
  }
  result.push(cur);
  return result;
};

// Righe DDT simulate per la demo AI
const FAKE_DDT_ROWS = [
  { name: 'Giacca monopetto lana',    sku: 'GI-1029', receivedQty: 8,  unitPrice: 440.00 },
  { name: 'Pantalone tailored',        sku: 'PA-3415', receivedQty: 12, unitPrice: 160.00 },
  { name: 'Trench cotone gabardine',   sku: 'TR-6612', receivedQty: 6,  unitPrice: 560.00 },
  { name: 'Maglia girocollo cashmere', sku: 'MA-1140', receivedQty: 8,  unitPrice: 230.00 },
  { name: 'Sciarpa seta stampata',     sku: 'SC-0501', receivedQty: 15, unitPrice: 95.00  },
  { name: 'Cintura pelle intrecciata', sku: 'AC-7812', receivedQty: 10, unitPrice: 65.00  },
];

// ─── Modale import righe consegna da CSV ───
const ConsegnaImportModal = ({ onClose, onImport, isFullForm }) => {
  const [rows, setRows]         = useStateAQ([]);
  const [file, setFile]         = useStateAQ(null);
  const [dragging, setDragging] = useStateAQ(false);
  const fileRef                 = useRefAQ(null);

  const parseFile = (f) => {
    if (!f) return;
    setFile(f);
    const reader = new FileReader();
    reader.onload = (ev) => {
      const lines = ev.target.result
        .split('\n').map(l => l.trim()).filter(l => l && !l.startsWith('#'));
      if (lines.length < 2) { setRows([]); return; }
      const headers = lines[0].split(',').map(h => h.trim().toLowerCase().replace(/\s+/g, ''));
      const parsed = lines.slice(1).map((line, i) => {
        const vals = parseCSVLineAQ(line);
        const row  = {};
        headers.forEach((h, idx) => { row[h] = (vals[idx] || '').trim(); });
        const sku   = (row['sku'] || '').toUpperCase();
        const nome  = row['nome'] || '';
        const qty   = parseInt(row['quantitaricevuta'] || row['qty'] || '0') || 0;
        const price = parseFloat((row['prezzoacquisto'] || row['prezzo'] || '0').replace(',', '.')) || 0;
        const art   = sku ? ARTICLES.find(a => a.id === sku) : null;
        const valid = !!sku && !!nome && qty > 0;
        const kind  = !valid ? 'Errore' : art ? 'Esistente' : 'Nuovo';
        return {
          _i: i, sku, nome, qty, price, art, valid, kind,
          error: !sku ? 'SKU mancante' : !nome ? 'Nome mancante' : qty <= 0 ? 'Quantità non valida' : '',
        };
      });
      setRows(parsed);
    };
    reader.readAsText(f, 'UTF-8');
  };

  const downloadTemplate = () => {
    const csv = [
      '# Fac-simile importazione righe consegna Bone & Ink',
      '# Colonne obbligatorie: sku, nome, quantitaRicevuta',
      '# Colonne opzionali: prezzoAcquisto',
      'sku,nome,quantitaRicevuta,prezzoAcquisto',
      'GI-1029,"Giacca monopetto lana",8,440.00',
      'PA-3415,"Pantalone tailored",12,160.00',
      'NEW-001,"Nuovo prodotto da creare",5,85.00',
    ].join('\n');
    const a = document.createElement('a');
    a.href = 'data:text/csv;charset=utf-8,' + encodeURIComponent(csv);
    a.download = 'fac-simile-righe-consegna.csv';
    document.body.appendChild(a); a.click(); document.body.removeChild(a);
  };

  const validRows = rows.filter(r => r.valid);

  const doImport = () => {
    onImport(validRows.map(r => ({
      articleId: r.art?.id || null,
      name: r.nome, sku: r.art?.id || null, tmpSku: r.art ? null : r.sku,
      orderedQty: null, receivedQty: r.qty, unitPrice: r.price,
      isNew: !r.art, newStatus: !r.art ? (isFullForm ? 'Pubblicato' : 'Bozza') : null,
    })));
    onClose();
  };

  return (
    <div className="fixed inset-0 z-modal flex items-center justify-center" style={{ background: 'rgba(0,0,0,0.45)' }}>
      <div className="bg-surface rounded-2xl shadow-modal w-full max-w-[720px] mx-4 flex flex-col" style={{ maxHeight: '88vh' }}>
        <div className="flex items-center justify-between px-6 py-4 border-b border-line">
          <div>
            <div className="text-[17px] font-semibold text-ink">Importa righe consegna da CSV</div>
            <div className="text-[12.5px] text-muted mt-0.5">Colonne: sku · nome · quantitaRicevuta · prezzoAcquisto</div>
          </div>
          <button onClick={onClose} className="w-9 h-9 rounded-full flex items-center justify-center text-muted hover:bg-paper focus-ring">
            <I.X size={18}/>
          </button>
        </div>

        <div className="flex-1 overflow-y-auto px-6 py-5 space-y-4">
          <div
            onDragOver={e => { e.preventDefault(); setDragging(true); }}
            onDragLeave={() => setDragging(false)}
            onDrop={e => { e.preventDefault(); setDragging(false); const f = e.dataTransfer.files[0]; if (f) parseFile(f); }}
            onClick={() => fileRef.current && fileRef.current.click()}
            className="rounded-xl p-8 text-center cursor-pointer transition-all duration-fast ease-standard"
            style={{
              border: `2px dashed ${dragging ? 'var(--accent-blue)' : 'var(--border-default)'}`,
              background: dragging ? 'var(--bg-selected)' : 'transparent',
            }}
          >
            <input ref={fileRef} type="file" accept=".csv" className="sr-only"
              onChange={e => parseFile(e.target.files[0])}/>
            <I.ArrowU size={28} className="mx-auto mb-3 text-muted"/>
            <div className="text-[15px] font-medium text-ink">
              {file ? file.name : 'Trascina il file CSV qui o clicca per selezionare'}
            </div>
            <div className="text-[12.5px] text-muted mt-1">Solo file .csv</div>
          </div>

          <div className="flex justify-end">
            <button onClick={downloadTemplate}
              className="flex items-center gap-1.5 text-[13px] text-[var(--accent-blue)] hover:underline focus-ring rounded-md px-1 py-0.5">
              <I.ArrowD size={13}/>
              Scarica fac-simile CSV
            </button>
          </div>

          {rows.length > 0 && (
            <div>
              <div className="flex items-center justify-between mb-2">
                <span className="text-[12px] uppercase tracking-[0.08em] text-muted font-medium">
                  Anteprima — {rows.length} righe
                </span>
                <span className="text-[12.5px] text-muted">
                  <span className="text-pos font-medium">{rows.filter(r => r.kind === 'Esistente').length}</span> esistenti ·{' '}
                  <span className="text-warn font-medium">{rows.filter(r => r.kind === 'Nuovo').length}</span> nuovi ·{' '}
                  <span className="text-neg font-medium">{rows.filter(r => r.kind === 'Errore').length}</span> errori
                </span>
              </div>
              <Card padded={false}>
                <div className="overflow-x-auto">
                  <table className="w-full text-[12.5px]">
                    <thead>
                      <tr className="hairline text-left text-muted uppercase text-[10.5px] tracking-[0.08em]">
                        <th className="px-4 py-2.5 font-medium">SKU</th>
                        <th className="px-4 py-2.5 font-medium">Nome</th>
                        <th className="px-4 py-2.5 font-medium text-right">Qty</th>
                        <th className="px-4 py-2.5 font-medium text-right">Prezzo</th>
                        <th className="px-4 py-2.5 font-medium">Stato</th>
                      </tr>
                    </thead>
                    <tbody>
                      {rows.map(r => (
                        <tr key={r._i} className={`border-b border-line2 last:border-0 ${r.kind === 'Errore' ? 'bg-[var(--danger-50)]' : ''}`}>
                          <td className="px-4 py-3 num text-muted">{r.sku || '—'}</td>
                          <td className="px-4 py-3 text-ink">{r.nome || <span className="italic text-neg">mancante</span>}</td>
                          <td className="px-4 py-3 num text-ink text-right">{r.qty || '—'}</td>
                          <td className="px-4 py-3 num text-ink text-right">{r.price > 0 ? fmtEur(r.price) : '—'}</td>
                          <td className="px-4 py-3">
                            {r.kind === 'Esistente' && <Pill tone="pos">Esistente</Pill>}
                            {r.kind === 'Nuovo'     && <Pill tone="warn">Nuovo</Pill>}
                            {r.kind === 'Errore'    && <Pill tone="neg">{r.error}</Pill>}
                          </td>
                        </tr>
                      ))}
                    </tbody>
                  </table>
                </div>
              </Card>
            </div>
          )}
        </div>

        <div className="flex items-center justify-between px-6 py-4 border-t border-line">
          <Btn variant="outline" size="md" onClick={onClose}>Annulla</Btn>
          <button onClick={doImport} disabled={validRows.length === 0}
            className="h-16 px-6 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)] disabled:opacity-30 disabled:cursor-not-allowed transition-all duration-fast ease-standard shadow-soft">
            <I.Check size={20}/>
            Aggiungi {validRows.length > 0 ? `${validRows.length} ` : ''}righe valide
          </button>
        </div>
      </div>
    </div>
  );
};

// ─── Modale AI DDT — DEMO ───
const AiDdtModal = ({ onClose, onImport, isFullForm }) => {
  const [phase, setPhase]       = useStateAQ('upload'); // 'upload' | 'processing' | 'review'
  const [file, setFile]         = useStateAQ(null);
  const [dragging, setDragging] = useStateAQ(false);
  const [editRows, setEditRows] = useStateAQ([]);
  const fileRef                 = useRefAQ(null);

  useEffectAQ(() => {
    if (phase !== 'processing') return;
    const timer = setTimeout(() => {
      setEditRows(FAKE_DDT_ROWS.map(r => {
        const art = ARTICLES.find(a => a.id === r.sku);
        return { ...r, kind: art ? 'Esistente' : 'Nuovo', articleId: art?.id || null };
      }));
      setPhase('review');
    }, 2500);
    return () => clearTimeout(timer);
  }, [phase]);

  const handleFile = (f) => { if (!f) return; setFile(f); setPhase('processing'); };

  const updateEditRow = (idx, field, val) =>
    setEditRows(prev => prev.map((r, i) => i !== idx ? r : { ...r, [field]: val }));

  const doImport = () => {
    onImport(editRows.map(r => ({
      articleId: r.articleId, name: r.name,
      sku: r.articleId || null, tmpSku: r.articleId ? null : r.sku,
      orderedQty: null, receivedQty: r.receivedQty, unitPrice: r.unitPrice,
      isNew: !r.articleId, newStatus: !r.articleId ? (isFullForm ? 'Pubblicato' : 'Bozza') : null,
    })));
    onClose();
  };

  return (
    <div className="fixed inset-0 z-modal flex items-center justify-center" style={{ background: 'rgba(0,0,0,0.45)' }}>
      <div className="bg-surface rounded-2xl shadow-modal w-full max-w-[760px] mx-4 flex flex-col" style={{ maxHeight: '90vh' }}>
        {/* Header */}
        <div className="flex items-center gap-3 px-6 py-4 border-b border-line">
          <div className="flex-1">
            <div className="flex items-center gap-2">
              <span className="text-[17px] font-semibold text-ink">Carica DDT con AI</span>
              <span className="text-[10.5px] font-bold uppercase tracking-[0.1em] px-2 py-0.5 rounded-sm"
                style={{ background: 'var(--warning-50)', color: 'var(--warning-700)', border: '1px solid var(--warning-700)' }}>
                DEMO
              </span>
            </div>
            <div className="text-[12.5px] text-muted mt-0.5">Funzionalità dimostrativa — riconosce automaticamente le righe dal documento</div>
          </div>
          <button onClick={onClose} className="w-9 h-9 rounded-full flex items-center justify-center text-muted hover:bg-paper focus-ring">
            <I.X size={18}/>
          </button>
        </div>

        <div className="flex-1 overflow-y-auto px-6 py-5">
          {/* Fase 1: upload */}
          {phase === 'upload' && (
            <div className="space-y-4">
              <div className="p-4 rounded-xl text-[13px]"
                style={{ background: 'var(--warning-50)', color: 'var(--warning-700)' }}>
                <strong>Funzionalità DEMO.</strong> Questa funzione non elabora documenti reali. Il caricamento di qualsiasi file avvierà una simulazione con dati di esempio.
              </div>
              <div
                onDragOver={e => { e.preventDefault(); setDragging(true); }}
                onDragLeave={() => setDragging(false)}
                onDrop={e => { e.preventDefault(); setDragging(false); const f = e.dataTransfer.files[0]; if (f) handleFile(f); }}
                onClick={() => fileRef.current && fileRef.current.click()}
                className="rounded-xl p-10 text-center cursor-pointer transition-all duration-fast ease-standard"
                style={{
                  border: `2px dashed ${dragging ? 'var(--accent-blue)' : 'var(--border-default)'}`,
                  background: dragging ? 'var(--bg-selected)' : 'transparent',
                }}
              >
                <input ref={fileRef} type="file" accept=".pdf,.png,.jpg,.jpeg,.webp" className="sr-only"
                  onChange={e => handleFile(e.target.files[0])}/>
                <I.ArrowU size={32} className="mx-auto mb-4 text-muted"/>
                <div className="text-[16px] font-medium text-ink">Trascina il DDT qui o clicca per selezionare</div>
                <div className="text-[12.5px] text-muted mt-1.5">PDF, PNG, JPG · max 20 MB</div>
              </div>
            </div>
          )}

          {/* Fase 2: elaborazione */}
          {phase === 'processing' && (
            <div className="space-y-4 py-4">
              <div className="text-center mb-6">
                <div className="text-[15px] font-medium text-ink">Analisi documento in corso…</div>
                <div className="text-[13px] text-muted mt-1">L'AI sta riconoscendo le righe del DDT</div>
              </div>
              {[0.9, 0.75, 0.6, 0.45].map((op, i) => (
                <div key={i} className="h-14 rounded-xl bg-paper animate-pulse" style={{ opacity: op }}/>
              ))}
            </div>
          )}

          {/* Fase 3: revisione */}
          {phase === 'review' && (
            <div className="space-y-4">
              <div className="flex items-center justify-between">
                <div className="text-[13.5px] font-medium text-ink">
                  {editRows.length} righe riconosciute · verifica e modifica prima di importare
                </div>
                <span className="text-[10.5px] font-bold uppercase tracking-[0.1em] px-2 py-0.5 rounded-sm"
                  style={{ background: 'var(--warning-50)', color: 'var(--warning-700)', border: '1px solid var(--warning-700)' }}>
                  DATI SIMULATI
                </span>
              </div>
              <Card padded={false}>
                <div className="grid grid-cols-[1fr_80px_140px_110px] gap-2 px-5 h-11 items-center text-[11px] uppercase tracking-[0.08em] text-muted font-medium hairline">
                  <div>Prodotto</div>
                  <div className="text-right">Qty</div>
                  <div className="text-right">Prezzo unit.</div>
                  <div>Catalogo</div>
                </div>
                <div className="divide-y divide-line2">
                  {editRows.map((r, idx) => (
                    <div key={idx} className="grid grid-cols-[1fr_80px_140px_110px] gap-2 px-5 items-center row-h">
                      <div className="flex items-center gap-3 min-w-0">
                        <div className="w-9 h-9 rounded-md stripe-ph shrink-0"/>
                        <div className="min-w-0">
                          <input value={r.name}
                            onChange={e => updateEditRow(idx, 'name', e.target.value)}
                            className="w-full text-[13.5px] font-medium text-ink bg-transparent border-b border-transparent hover:border-line focus:border-strong focus:outline-none transition-all duration-fast ease-standard"/>
                          <span className="num text-[11px] text-muted">{r.sku}</span>
                        </div>
                      </div>
                      <div className="flex justify-end">
                        <input type="number" min="1" value={r.receivedQty}
                          onChange={e => updateEditRow(idx, 'receivedQty', Math.max(1, parseInt(e.target.value) || 1))}
                          className="w-16 h-9 px-2 rounded-sm border border-line bg-surface num text-[13px] text-right focus:border-strong transition-all"/>
                      </div>
                      <div className="flex justify-end">
                        <input type="number" min="0" step="0.01" value={r.unitPrice}
                          onChange={e => updateEditRow(idx, 'unitPrice', parseFloat(e.target.value) || 0)}
                          className="w-24 h-9 px-2 rounded-sm border border-line bg-surface num text-[13px] text-right focus:border-strong transition-all"/>
                      </div>
                      <div>
                        {r.kind === 'Esistente' ? <Pill tone="pos">Esistente</Pill> : <Pill tone="warn">Nuovo</Pill>}
                      </div>
                    </div>
                  ))}
                </div>
              </Card>
            </div>
          )}
        </div>

        <div className="flex items-center justify-between px-6 py-4 border-t border-line">
          <Btn variant="outline" size="md" onClick={onClose}>Annulla</Btn>
          {phase === 'review' ? (
            <button onClick={doImport}
              className="h-16 px-6 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)] transition-all duration-fast ease-standard shadow-soft">
              <I.Check size={20}/>
              Usa queste {editRows.length} righe
            </button>
          ) : (
            <Btn variant="outline" size="md" disabled={true}>
              {phase === 'processing' ? 'Elaborazione…' : 'Carica documento'}
            </Btn>
          )}
        </div>
      </div>
    </div>
  );
};

// ══════════════════════════════════════════════════════════════════════
//  ORDINI
// ══════════════════════════════════════════════════════════════════════

const OrdiniList = ({ orders, onNew, onOpen }) => {
  const [q, setQ]                             = useStateAQ('');
  const [filterFornitore, setFilterFornitore] = useStateAQ('Tutti');
  const [filterStato, setFilterStato]         = useStateAQ('Tutti');
  const [filterStore, setFilterStore]         = useStateAQ('Tutti');

  const fornitori = useMemoAQ(() =>
    ['Tutti', ...Array.from(new Set(orders.map(o =>
      SUPPLIERS.find(s => s.id === o.supplierId)?.name || o.supplierId
    )))],
  [orders]);

  const filtered = useMemoAQ(() => {
    const ql = q.trim().toLowerCase();
    return orders.filter(o => {
      const sName  = SUPPLIERS.find(s => s.id === o.supplierId)?.name || o.supplierId;
      const stName = STORES.find(s => s.id === o.storeId)?.name || o.storeId;
      if (filterFornitore !== 'Tutti' && sName !== filterFornitore) return false;
      if (filterStato !== 'Tutti' && o.status !== filterStato) return false;
      if (filterStore !== 'Tutti' && stName !== filterStore) return false;
      if (ql && !o.id.toLowerCase().includes(ql) && !sName.toLowerCase().includes(ql)) return false;
      return true;
    });
  }, [q, filterFornitore, filterStato, filterStore, orders]);

  const negozi = ['Tutti', ...STORES.map(s => s.name)];
  const stati  = ['Tutti', 'Bozza', 'Inviato', 'Ricevuto'];

  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">Ordini a fornitore</h2>
          <p className="text-[13.5px] text-muted mt-0.5">Gestione ordini di acquisto per tutti i punti vendita.</p>
        </div>
        <button onClick={onNew}
          className="h-16 px-6 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)] transition-all duration-fast ease-standard shadow-soft">
          <I.Plus size={20}/>
          Nuovo ordine
        </button>
      </div>

      <div className="grid grid-cols-3 gap-4">
        <AcqKpi label="Bozze"    value={orders.filter(o => o.status === 'Bozza').length}    sub="da completare"/>
        <AcqKpi label="Inviati"  value={orders.filter(o => o.status === 'Inviato').length}  sub="in attesa consegna" tone="warn"/>
        <AcqKpi label="Ricevuti" value={orders.filter(o => o.status === 'Ricevuto').length} sub="completati" tone="pos"/>
      </div>

      <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-[240px]">
            <I.Search size={16} 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 numero ordine o fornitore…"
              className="w-full h-11 pl-10 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="Fornitore" value={filterFornitore} onChange={setFilterFornitore} options={fornitori}/>
          <FilterSelect label="Stato"     value={filterStato}     onChange={setFilterStato}     options={stati}/>
          <FilterSelect label="Negozio"   value={filterStore}     onChange={setFilterStore}     options={negozi}/>
        </div>
      </div>

      <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">N° Ordine</th>
              <th className="px-5 py-3 font-medium">Fornitore</th>
              <th className="px-5 py-3 font-medium">Negozio</th>
              <th className="px-5 py-3 font-medium">Data ordine</th>
              <th className="px-5 py-3 font-medium">Consegna prev.</th>
              <th className="px-5 py-3 font-medium">Stato</th>
              <th className="px-5 py-3 font-medium text-right">Totale</th>
              <th className="px-5 py-3 font-medium"></th>
            </tr>
          </thead>
          <tbody>
            {filtered.map(o => {
              const supplier = SUPPLIERS.find(s => s.id === o.supplierId);
              const store    = STORES.find(s => s.id === o.storeId);
              return (
                <tr key={o.id} onClick={() => onOpen(o.id)}
                    className="hover:bg-paper border-b border-line2 last:border-0 cursor-pointer">
                  <td className="px-5 py-4 num text-ink font-medium">{o.id}</td>
                  <td className="px-5 py-4 text-ink">{supplier?.name || o.supplierId}</td>
                  <td className="px-5 py-4 text-ink">{store?.name || o.storeId}</td>
                  <td className="px-5 py-4 text-ink">{o.dateOrder}</td>
                  <td className="px-5 py-4 text-ink">{o.dateExpected || '—'}</td>
                  <td className="px-5 py-4">
                    <Pill tone={ORDER_STATUS_TONE[o.status] || 'neutral'}>{o.status}</Pill>
                  </td>
                  <td className="px-5 py-4 num text-ink text-right font-semibold">
                    {o.total > 0 ? fmtEur(o.total) : '—'}
                  </td>
                  <td className="px-5 py-4 text-right">
                    <span className="text-[12.5px] text-[var(--accent-blue)] pointer-events-none">
                      {o.status === 'Bozza' ? 'Modifica' : 'Apri'}
                    </span>
                  </td>
                </tr>
              );
            })}
          </tbody>
        </table>
        {filtered.length === 0 && (
          <div className="py-16 text-center text-muted text-[14px]">Nessun ordine corrisponde ai filtri.</div>
        )}
      </Card>
    </div>
  );
};

const OrdineDetail = ({ order, lines, onBack }) => {
  const supplier  = SUPPLIERS.find(s => s.id === order.supplierId);
  const store     = STORES.find(s => s.id === order.storeId);
  const totalCalc = lines.reduce((s, l) => s + l.qty * l.unitPrice, 0);

  return (
    <div className="px-7 py-6 max-w-[1400px]">
      <button onClick={onBack}
        className="text-[13px] text-muted hover:text-ink inline-flex items-center gap-1.5 mb-3 focus-ring rounded-md px-2 py-1 -ml-2">
        <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 agli ordini
      </button>

      <div className="flex items-start justify-between gap-4 mb-5">
        <div>
          <div className="text-[11px] uppercase tracking-[0.08em] text-muted font-medium">Ordine fornitore</div>
          <div className="text-[22px] font-semibold tracking-tight text-ink mt-0.5">{order.id}</div>
        </div>
        <Pill tone={ORDER_STATUS_TONE[order.status] || 'neutral'}>{order.status}</Pill>
      </div>

      <Card className="mb-4">
        <div className="grid gap-5" style={{ gridTemplateColumns: 'repeat(4, 1fr)' }}>
          <KeyVal label="Fornitore"            value={supplier?.name || order.supplierId}/>
          <KeyVal label="Negozio destinazione" value={store?.name || order.storeId}/>
          <KeyVal label="Data ordine"          value={order.dateOrder}/>
          <KeyVal label="Consegna prevista"    value={order.dateExpected || '—'}/>
        </div>
        {supplier && (
          <div className="mt-4 pt-4 border-t border-line grid grid-cols-3 gap-4 text-[13px]">
            <div><span className="text-muted">Categoria · </span><span className="text-ink">{supplier.cat}</span></div>
            <div><span className="text-muted">Referente · </span><span className="text-ink">{supplier.contact}</span></div>
            <div><span className="text-muted">Email · </span><span className="text-ink">{supplier.email}</span></div>
          </div>
        )}
      </Card>

      <Card title={`Prodotti — ${lines.length} righe`} padded={false}>
        <div className="grid grid-cols-[1fr_100px_140px_140px] gap-2 px-5 h-11 items-center text-[11px] uppercase tracking-[0.08em] text-muted font-medium hairline">
          <div>Prodotto</div>
          <div className="text-right">Quantità</div>
          <div className="text-right">Prezzo unit.</div>
          <div className="text-right">Totale riga</div>
        </div>
        <div className="divide-y divide-line2">
          {lines.map((l, idx) => (
            <div key={idx} className="row-h grid grid-cols-[1fr_100px_140px_140px] gap-2 px-5 items-center">
              <div className="flex items-center gap-3 min-w-0">
                <div className="w-9 h-9 rounded-md stripe-ph shrink-0"/>
                <div className="min-w-0">
                  <div className="text-[14px] font-medium text-ink truncate">{l.name}</div>
                  <div className="flex items-center gap-1.5 mt-0.5">
                    <span className="num text-[11px] text-muted">{l.sku || l.tmpSku || '—'}</span>
                    {l.isNew && <Pill tone="warn">Nuovo</Pill>}
                  </div>
                </div>
              </div>
              <div className="num text-[15px] text-ink text-right">{l.qty}</div>
              <div className="num text-[15px] text-ink text-right">{fmtEur(l.unitPrice)}</div>
              <div className="num text-[15px] font-semibold text-ink text-right">{fmtEur(l.qty * l.unitPrice)}</div>
            </div>
          ))}
          {lines.length === 0 && (
            <div className="py-10 text-center text-muted text-[13.5px]">Nessuna riga prodotto.</div>
          )}
        </div>
        <div className="px-5 py-4 border-t border-line flex justify-end items-center gap-6">
          <span className="text-[13px] text-muted">Totale ordine</span>
          <span className="num text-[22px] font-semibold text-ink">{fmtEur(totalCalc)}</span>
        </div>
      </Card>
    </div>
  );
};

const OrdineWizard = ({ existing, initialLines, onSave, onCancel }) => {
  const [step, setStep]                       = useStateAQ(1);
  const [supplierId, setSupplierId]           = useStateAQ(existing?.supplierId || '');
  const [storeId, setStoreId]                 = useStateAQ(existing?.storeId || STORE.id);
  const [dateOrder, setDateOrder]             = useStateAQ('2026-05-29');
  const [dateExpected, setDateExpected]       = useStateAQ('');
  const [lines, setLines]                     = useStateAQ(initialLines || []);
  const [searchQ, setSearchQ]                 = useStateAQ('');
  const [showNewForm, setShowNewForm]         = useStateAQ(false);
  const [newName, setNewName]                 = useStateAQ('');
  const [newSku, setNewSku]                   = useStateAQ('');
  const [newQty, setNewQty]                   = useStateAQ(1);
  const [newPrice, setNewPrice]               = useStateAQ('');

  const WIZ = [{ id: 1, label: 'Testata' }, { id: 2, label: 'Prodotti' }];
  const canNext1 = supplierId && storeId;
  const total    = lines.reduce((s, l) => s + l.qty * l.unitPrice, 0);

  const searchResults = useMemoAQ(() => {
    const ql = searchQ.trim().toLowerCase();
    if (!ql) return [];
    return ARTICLES.filter(a =>
      a.name.toLowerCase().includes(ql) || a.id.toLowerCase().includes(ql) || a.brand.toLowerCase().includes(ql)
    ).slice(0, 8);
  }, [searchQ]);

  const addCatalogLine = (article) => {
    if (lines.find(l => !l.isNew && l.articleId === article.id)) return;
    setLines(prev => [...prev, {
      articleId: article.id, name: article.name, sku: article.id,
      qty: 1, unitPrice: Math.round(article.basePrice * 0.5), isNew: false,
    }]);
    setSearchQ('');
  };

  const addNewLine = () => {
    if (!newName.trim() || !newSku.trim()) return;
    setLines(prev => [...prev, {
      articleId: null, name: newName.trim(), sku: null,
      tmpSku: newSku.trim().toUpperCase(), qty: newQty,
      unitPrice: parseFloat(newPrice) || 0, isNew: true,
    }]);
    setNewName(''); setNewSku(''); setNewQty(1); setNewPrice('');
    setShowNewForm(false);
  };

  const updateLine = (idx, field, val) =>
    setLines(prev => prev.map((l, i) => i !== idx ? l : { ...l, [field]: val }));
  const removeLine = (idx) =>
    setLines(prev => prev.filter((_, i) => i !== idx));

  const doSave = (status) => {
    const id = existing?.id || ('OA 2026-' + String(Date.now()).slice(-4));
    const t  = lines.reduce((s, l) => s + l.qty * l.unitPrice, 0);
    onSave({ id, supplierId, storeId, dateOrder, dateExpected, status, total: t }, lines, id);
  };

  const cls = 'w-full h-11 px-3 rounded-md border border-line bg-surface text-[14px] text-ink focus:border-strong focus:outline-none transition-all duration-fast ease-standard';
  const lbl = 'block text-[12px] font-semibold uppercase tracking-[0.04em] text-muted mb-1.5';

  return (
    <div className="px-7 py-6 max-w-[1400px]">
      <div className="bg-surface rounded-2xl p-5 mb-5 shadow-soft">
        <button onClick={onCancel}
          className="text-[13px] text-muted hover:text-ink inline-flex items-center gap-1.5 focus-ring rounded-md px-2 py-1 -ml-2">
          <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 agli ordini
        </button>
        <h2 className="text-[22px] font-semibold tracking-tight text-ink mt-2">
          {existing ? `Modifica ${existing.id}` : 'Nuovo ordine a fornitore'}
        </h2>
        <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 || done ? 'text-ink' : 'text-muted'}`}>{w.label}</span>
                </div>
                {i < WIZ.length - 1 && <div className={`flex-1 h-px ${done ? 'bg-pos' : 'bg-line'}`}/>}
              </React.Fragment>
            );
          })}
        </div>
      </div>

      {step === 1 && (
        <Card title="Intestazione ordine">
          <div className="grid grid-cols-2 gap-5">
            <div>
              <label className={lbl}>Fornitore</label>
              <select className={cls} value={supplierId} onChange={e => setSupplierId(e.target.value)}>
                <option value="">— Seleziona fornitore —</option>
                {SUPPLIERS.map(s => <option key={s.id} value={s.id}>{s.name}</option>)}
              </select>
            </div>
            <div>
              <label className={lbl}>Negozio destinazione</label>
              <select className={cls} value={storeId} onChange={e => setStoreId(e.target.value)}>
                {STORES.map(s => <option key={s.id} value={s.id}>{s.name}</option>)}
              </select>
            </div>
            <div>
              <label className={lbl}>Data ordine</label>
              <input type="date" className={cls} value={dateOrder} onChange={e => setDateOrder(e.target.value)}/>
            </div>
            <div>
              <label className={lbl}>Data consegna prevista</label>
              <input type="date" className={cls} value={dateExpected} onChange={e => setDateExpected(e.target.value)}/>
            </div>
          </div>
          {supplierId && (() => {
            const s = SUPPLIERS.find(x => x.id === supplierId);
            return s ? (
              <div className="mt-4 p-4 rounded-xl bg-sunken grid grid-cols-3 gap-4 text-[13px]">
                <div><span className="text-muted">Categoria · </span><span className="text-ink">{s.cat}</span></div>
                <div><span className="text-muted">Referente · </span><span className="text-ink">{s.contact}</span></div>
                <div><span className="text-muted">Città · </span><span className="text-ink">{s.city}</span></div>
              </div>
            ) : null;
          })()}
        </Card>
      )}

      {step === 2 && (
        <div className="space-y-4">
          <Card title="Aggiungi prodotti dal catalogo">
            <div className="relative mb-3">
              <I.Search size={16} className="absolute left-3.5 top-1/2 -translate-y-1/2 text-muted"/>
              <input value={searchQ} onChange={e => setSearchQ(e.target.value)}
                placeholder="Cerca prodotto per nome, codice o brand…"
                className="w-full h-11 pl-10 pr-4 rounded-md border border-line bg-surface text-[14px] focus:border-strong transition-all duration-fast ease-standard"/>
            </div>
            {searchResults.length > 0 && (
              <div className="rounded-xl overflow-hidden" style={{ border: '0.5px solid var(--border-default)' }}>
                {searchResults.map(a => (
                  <button key={a.id} onClick={() => addCatalogLine(a)}
                    className="w-full px-4 py-3 flex items-center gap-3 hover:bg-paper text-left border-b border-line2 last:border-0 transition-colors duration-fast ease-standard">
                    <div className="w-9 h-9 rounded-md stripe-ph shrink-0"/>
                    <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} · {a.id}</div>
                    </div>
                    <span className="flex items-center gap-1 text-[12px] text-[var(--accent-blue)] shrink-0">
                      <I.Plus size={13}/> Aggiungi
                    </span>
                  </button>
                ))}
              </div>
            )}
            {searchQ.trim() !== '' && searchResults.length === 0 && (
              <p className="text-[13px] text-muted mt-1">Nessun prodotto trovato per "{searchQ}".</p>
            )}
          </Card>

          <Card title="Prodotto non ancora in catalogo">
            {!showNewForm ? (
              <button onClick={() => setShowNewForm(true)}
                className="h-11 flex items-center gap-2 text-[13.5px] font-medium text-[var(--accent-blue)] hover:underline focus-ring rounded-md px-1">
                <I.Plus size={14}/>
                + Prodotto nuovo (non ancora in catalogo)
              </button>
            ) : (
              <div className="grid grid-cols-2 gap-4">
                <div>
                  <label className={lbl}>Nome prodotto *</label>
                  <input value={newName} onChange={e => setNewName(e.target.value)}
                    placeholder="es. Cappello cashmere" className={cls}/>
                </div>
                <div>
                  <label className={lbl}>SKU / Codice provvisorio *</label>
                  <input value={newSku} onChange={e => setNewSku(e.target.value)}
                    placeholder="es. HAT-0001" className={cls}/>
                </div>
                <div>
                  <label className={lbl}>Quantità</label>
                  <input type="number" min="1" value={newQty}
                    onChange={e => setNewQty(Math.max(1, parseInt(e.target.value) || 1))}
                    className={cls}/>
                </div>
                <div>
                  <label className={lbl}>Prezzo d'acquisto (€)</label>
                  <input type="number" min="0" step="0.01" value={newPrice}
                    onChange={e => setNewPrice(e.target.value)}
                    placeholder="0.00" className={cls}/>
                </div>
                <div className="col-span-2 flex gap-2">
                  <Btn variant="primary" size="md" disabled={!newName.trim() || !newSku.trim()} onClick={addNewLine}>
                    Aggiungi riga
                  </Btn>
                  <Btn variant="outline" size="md" onClick={() => setShowNewForm(false)}>Annulla</Btn>
                </div>
              </div>
            )}
          </Card>

          <Card title={`Righe ordine (${lines.length})`} padded={false}>
            {lines.length === 0 ? (
              <div className="p-8 text-center text-muted text-[13.5px]">
                Nessun prodotto aggiunto. Cerca nel catalogo o aggiungi un articolo nuovo.
              </div>
            ) : (
              <>
                <div className="grid grid-cols-[1fr_100px_150px_140px_48px] gap-2 px-5 h-11 items-center text-[11px] uppercase tracking-[0.08em] text-muted font-medium hairline">
                  <div>Prodotto</div>
                  <div className="text-right">Quantità</div>
                  <div className="text-right">Prezzo unit. (€)</div>
                  <div className="text-right">Totale riga</div>
                  <div/>
                </div>
                <div className="divide-y divide-line2">
                  {lines.map((l, idx) => (
                    <div key={idx} className="row-h grid grid-cols-[1fr_100px_150px_140px_48px] gap-2 px-5 items-center">
                      <div className="flex items-center gap-3 min-w-0">
                        <div className="w-9 h-9 rounded-md stripe-ph shrink-0"/>
                        <div className="min-w-0">
                          <div className="text-[13.5px] font-medium text-ink truncate">{l.name}</div>
                          <div className="flex items-center gap-1.5 mt-0.5">
                            <span className="num text-[11px] text-muted">{l.sku || l.tmpSku}</span>
                            {l.isNew && <Pill tone="warn">Nuovo</Pill>}
                          </div>
                        </div>
                      </div>
                      <div className="flex justify-end">
                        <input type="number" min="1" value={l.qty}
                          onChange={e => updateLine(idx, 'qty', Math.max(1, parseInt(e.target.value) || 1))}
                          className="w-16 h-10 px-2 rounded-sm border border-line bg-surface num text-[14px] text-right focus:border-strong transition-all"/>
                      </div>
                      <div className="flex justify-end">
                        <input type="number" min="0" step="0.01" value={l.unitPrice}
                          onChange={e => updateLine(idx, 'unitPrice', parseFloat(e.target.value) || 0)}
                          className="w-28 h-10 px-2 rounded-sm border border-line bg-surface num text-[14px] text-right focus:border-strong transition-all"/>
                      </div>
                      <div className="num text-[14px] font-semibold text-ink text-right">{fmtEur(l.qty * l.unitPrice)}</div>
                      <div className="flex justify-center">
                        <button onClick={() => removeLine(idx)}
                          className="w-9 h-9 rounded-md flex items-center justify-center text-muted hover:bg-[var(--danger-50)] hover:text-[var(--danger-700)] transition-colors duration-fast ease-standard focus-ring">
                          <I.Trash size={14}/>
                        </button>
                      </div>
                    </div>
                  ))}
                </div>
                <div className="px-5 py-4 border-t border-line flex justify-end items-center gap-6">
                  <span className="text-[13px] text-muted">Totale ordine</span>
                  <span className="num text-[22px] font-semibold text-ink">{fmtEur(total)}</span>
                </div>
              </>
            )}
          </Card>
        </div>
      )}

      <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>
          ) : (
            <Btn variant="outline" size="lg" onClick={onCancel}>Annulla</Btn>
          )}
        </div>
        <div className="flex items-center gap-3">
          <span className="text-[12.5px] text-muted">Step {step} di 2</span>
          {step < 2 ? (
            <Btn variant="primary" size="lg" disabled={!canNext1} onClick={() => setStep(2)} trailing={<I.ArrowR size={18}/>}>
              Avanti
            </Btn>
          ) : (
            <>
              <Btn variant="outline" size="lg" onClick={() => doSave('Bozza')}>
                Salva come bozza
              </Btn>
              <button onClick={() => doSave('Inviato')} 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}/>
                Invia ordine
              </button>
            </>
          )}
        </div>
      </div>
    </div>
  );
};

// ══════════════════════════════════════════════════════════════════════
//  CONSEGNE
// ══════════════════════════════════════════════════════════════════════

const ConsegneList = ({ deliveries, onNew, onOpen }) => {
  const [q, setQ]                             = useStateAQ('');
  const [filterFornitore, setFilterFornitore] = useStateAQ('Tutti');
  const [filterStato, setFilterStato]         = useStateAQ('Tutti');
  const [filterStore, setFilterStore]         = useStateAQ('Tutti');
  const [onlyCV, setOnlyCV]                   = useStateAQ(false);

  const fornitori = useMemoAQ(() =>
    ['Tutti', ...Array.from(new Set(deliveries.map(d =>
      SUPPLIERS.find(s => s.id === d.supplierId)?.name || d.supplierId
    )))],
  [deliveries]);

  const filtered = useMemoAQ(() => {
    const ql = q.trim().toLowerCase();
    return deliveries.filter(d => {
      const sName  = SUPPLIERS.find(s => s.id === d.supplierId)?.name || d.supplierId;
      const stName = STORES.find(s => s.id === d.storeId)?.name || d.storeId;
      if (filterFornitore !== 'Tutti' && sName !== filterFornitore) return false;
      if (filterStato !== 'Tutti' && d.status !== filterStato) return false;
      if (filterStore !== 'Tutti' && stName !== filterStore) return false;
      if (onlyCV && !d.contoVendita) return false;
      if (ql && !d.id.toLowerCase().includes(ql) && !(d.linkedOrderId || '').toLowerCase().includes(ql)) return false;
      return true;
    });
  }, [q, filterFornitore, filterStato, filterStore, onlyCV, deliveries]);

  const negozi = ['Tutti', ...STORES.map(s => s.name)];
  const stati  = ['Tutti', 'Bozza', 'Confermata'];

  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">Consegne merce</h2>
          <p className="text-[13.5px] text-muted mt-0.5">Carico da fornitore e aggiornamento giacenze.</p>
        </div>
        <button onClick={onNew}
          className="h-16 px-6 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)] transition-all duration-fast ease-standard shadow-soft">
          <I.Plus size={20}/>
          Nuova consegna
        </button>
      </div>

      <div className="grid grid-cols-3 gap-4">
        <AcqKpi label="Bozze"         value={deliveries.filter(d => d.status === 'Bozza').length}      sub="da completare"/>
        <AcqKpi label="Confermate"    value={deliveries.filter(d => d.status === 'Confermata').length} sub="completate" tone="pos"/>
        <AcqKpi label="Conto vendita" value={deliveries.filter(d => d.contoVendita).length}            sub="in giacenza esterna"/>
      </div>

      <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-[240px]">
            <I.Search size={16} 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 numero consegna o ordine collegato…"
              className="w-full h-11 pl-10 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="Fornitore" value={filterFornitore} onChange={setFilterFornitore} options={fornitori}/>
          <FilterSelect label="Stato"     value={filterStato}     onChange={setFilterStato}     options={stati}/>
          <FilterSelect label="Negozio"   value={filterStore}     onChange={setFilterStore}     options={negozi}/>
          <label className="flex items-center gap-2 h-11 px-3 rounded-md text-[13.5px] cursor-pointer select-none transition-colors duration-fast ease-standard"
            style={{ border: '0.5px solid var(--border-default)', background: onlyCV ? 'var(--bg-selected)' : 'var(--bg-surface)', color: onlyCV ? 'var(--accent-blue)' : 'var(--text-secondary)' }}>
            <input type="checkbox" checked={onlyCV} onChange={e => setOnlyCV(e.target.checked)}
              className="w-4 h-4 accent-[var(--accent-blue)]"/>
            Solo conto vendita
          </label>
        </div>
      </div>

      <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">N° Consegna</th>
              <th className="px-5 py-3 font-medium">Fornitore</th>
              <th className="px-5 py-3 font-medium">Negozio</th>
              <th className="px-5 py-3 font-medium">Data carico</th>
              <th className="px-5 py-3 font-medium">Ordine rif.</th>
              <th className="px-5 py-3 font-medium">Stato</th>
              <th className="px-5 py-3 font-medium text-right">Totale</th>
              <th className="px-5 py-3 font-medium"></th>
            </tr>
          </thead>
          <tbody>
            {filtered.map(d => {
              const supplier = SUPPLIERS.find(s => s.id === d.supplierId);
              const store    = STORES.find(s => s.id === d.storeId);
              return (
                <tr key={d.id} onClick={() => onOpen(d.id)}
                    className="hover:bg-paper border-b border-line2 last:border-0 cursor-pointer">
                  <td className="px-5 py-4">
                    <div className="num font-medium text-ink">{d.id}</div>
                    {d.contoVendita && <div className="mt-0.5"><Pill tone="warn">Conto vendita</Pill></div>}
                  </td>
                  <td className="px-5 py-4 text-ink">{supplier?.name || d.supplierId}</td>
                  <td className="px-5 py-4 text-ink">{store?.name || d.storeId}</td>
                  <td className="px-5 py-4 text-ink">{d.dateCarico || '—'}</td>
                  <td className="px-5 py-4 num text-ink">{d.linkedOrderId || '—'}</td>
                  <td className="px-5 py-4">
                    <Pill tone={DELIVERY_STATUS_TONE[d.status] || 'neutral'}>{d.status}</Pill>
                  </td>
                  <td className="px-5 py-4 num text-ink text-right font-semibold">
                    {d.total > 0 ? fmtEur(d.total) : '—'}
                  </td>
                  <td className="px-5 py-4 text-right">
                    <span className="text-[12.5px] text-[var(--accent-blue)] pointer-events-none">
                      {d.status === 'Bozza' ? 'Modifica' : 'Apri'}
                    </span>
                  </td>
                </tr>
              );
            })}
          </tbody>
        </table>
        {filtered.length === 0 && (
          <div className="py-16 text-center text-muted text-[14px]">Nessuna consegna corrisponde ai filtri.</div>
        )}
      </Card>
    </div>
  );
};

// ─── Scelta modalità nuova consegna ───
const ConsegnaNewSelect = ({ inviatiOrders, onSelectMode, onCancel }) => (
  <div className="px-7 py-6 max-w-[1400px]">
    <button onClick={onCancel}
      className="text-[13px] text-muted hover:text-ink inline-flex items-center gap-1.5 mb-5 focus-ring rounded-md px-2 py-1 -ml-2">
      <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 alle consegne
    </button>
    <div className="mb-6">
      <h2 className="text-[22px] font-semibold tracking-tight text-ink">Nuova consegna</h2>
      <p className="text-[14px] text-muted mt-1">Come vuoi creare la consegna?</p>
    </div>
    <div className="grid grid-cols-2 gap-5 max-w-[720px]">
      <button onClick={() => onSelectMode('from-order')} disabled={inviatiOrders.length === 0}
        className="p-6 rounded-2xl text-left transition-all duration-fast ease-standard shadow-soft disabled:opacity-40 disabled:cursor-not-allowed hover:bg-[var(--bg-hover)]"
        style={{ border: '1.5px solid var(--border-default)', background: 'var(--bg-surface)' }}>
        <div className="w-11 h-11 rounded-xl bg-[var(--bg-selected)] flex items-center justify-center mb-4">
          <I.Receipt size={22} className="text-[var(--accent-blue)]"/>
        </div>
        <div className="text-[16px] font-semibold text-ink">Da ordine esistente</div>
        <div className="text-[13px] text-muted mt-1">Collega la consegna a un ordine già inviato</div>
        <div className="text-[12px] mt-2" style={{ color: inviatiOrders.length === 0 ? 'var(--warning-700)' : 'var(--text-tertiary)' }}>
          {inviatiOrders.length === 0
            ? 'Nessun ordine in stato "Inviato" disponibile'
            : `${inviatiOrders.length} ordine${inviatiOrders.length > 1 ? 'i' : ''} disponibile${inviatiOrders.length > 1 ? 'i' : ''}`}
        </div>
      </button>
      <button onClick={() => onSelectMode('free')}
        className="p-6 rounded-2xl text-left transition-all duration-fast ease-standard shadow-soft hover:bg-[var(--bg-hover)]"
        style={{ border: '1.5px solid var(--border-default)', background: 'var(--bg-surface)' }}>
        <div className="w-11 h-11 rounded-xl bg-[var(--bg-selected)] flex items-center justify-center mb-4">
          <I.Plus size={22} className="text-[var(--accent-blue)]"/>
        </div>
        <div className="text-[16px] font-semibold text-ink">Carico libero</div>
        <div className="text-[13px] text-muted mt-1">Consegna senza ordine di riferimento</div>
        <div className="text-[12px] text-muted mt-2">Conto vendita o consegna diretta</div>
      </button>
    </div>
  </div>
);

// ─── Selezione ordine per la nuova consegna ───
const ConsegnaOrderPicker = ({ orders, onPick, onCancel }) => (
  <div className="px-7 py-6 max-w-[1400px]">
    <button onClick={onCancel}
      className="text-[13px] text-muted hover:text-ink inline-flex items-center gap-1.5 mb-5 focus-ring rounded-md px-2 py-1 -ml-2">
      <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>
      Indietro
    </button>
    <div className="mb-5">
      <h2 className="text-[22px] font-semibold tracking-tight text-ink">Seleziona l'ordine</h2>
      <p className="text-[14px] text-muted mt-1">Scegli l'ordine a cui collegare la consegna.</p>
    </div>
    <Card padded={false}>
      {orders.length === 0 ? (
        <div className="py-16 text-center text-muted text-[14px]">Nessun ordine in stato "Inviato".</div>
      ) : (
        <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">N° Ordine</th>
              <th className="px-5 py-3 font-medium">Fornitore</th>
              <th className="px-5 py-3 font-medium">Negozio</th>
              <th className="px-5 py-3 font-medium">Data ordine</th>
              <th className="px-5 py-3 font-medium">Consegna prev.</th>
              <th className="px-5 py-3 font-medium text-right">Totale</th>
              <th className="px-5 py-3 font-medium"></th>
            </tr>
          </thead>
          <tbody>
            {orders.map(o => {
              const supplier = SUPPLIERS.find(s => s.id === o.supplierId);
              const store    = STORES.find(s => s.id === o.storeId);
              return (
                <tr key={o.id} onClick={() => onPick(o.id)}
                    className="hover:bg-paper border-b border-line2 last:border-0 cursor-pointer">
                  <td className="px-5 py-4 num font-medium text-ink">{o.id}</td>
                  <td className="px-5 py-4 text-ink">{supplier?.name || o.supplierId}</td>
                  <td className="px-5 py-4 text-ink">{store?.name || o.storeId}</td>
                  <td className="px-5 py-4 text-ink">{o.dateOrder}</td>
                  <td className="px-5 py-4 text-ink">{o.dateExpected || '—'}</td>
                  <td className="px-5 py-4 num text-ink text-right font-semibold">{o.total > 0 ? fmtEur(o.total) : '—'}</td>
                  <td className="px-5 py-4 text-right">
                    <span className="text-[12.5px] text-[var(--accent-blue)] pointer-events-none">Seleziona</span>
                  </td>
                </tr>
              );
            })}
          </tbody>
        </table>
      )}
    </Card>
  </div>
);

// ─── Wizard consegna (2 step) ───
const ConsegnaWizard = ({
  existing, existingLines, fromOrderId, fromOrder, fromOrderLines, mode, session, onSave, onCancel,
}) => {
  const [step, setStep]                         = useStateAQ(1);
  const [supplierId, setSupplierId]             = useStateAQ(existing?.supplierId || fromOrder?.supplierId || '');
  const [storeId, setStoreId]                   = useStateAQ(existing?.storeId || fromOrder?.storeId || STORE.id);
  const [dateCarico, setDateCarico]             = useStateAQ('2026-05-29');
  const [numDocFornitore, setNumDocFornitore]   = useStateAQ(existing?.numDocFornitore || '');
  const [dateDocFornitore, setDateDocFornitore] = useStateAQ('');
  const [contoVendita, setContoVendita]         = useStateAQ(existing?.contoVendita || false);
  const [note, setNote]                         = useStateAQ(existing?.note || '');

  const [lines, setLines] = useStateAQ(() => {
    if (existing && existingLines && existingLines.length > 0) return existingLines;
    if (fromOrderLines && fromOrderLines.length > 0) {
      return fromOrderLines.map(l => ({
        articleId: l.articleId,
        name: l.name, sku: l.sku, tmpSku: l.tmpSku || null,
        orderedQty: l.qty, receivedQty: l.qty,
        unitPrice: l.unitPrice, isNew: l.isNew || false, newStatus: null,
      }));
    }
    if (existing && existingLines) return existingLines;
    return [];
  });

  const [searchQ, setSearchQ]         = useStateAQ('');
  const [showNewForm, setShowNewForm] = useStateAQ(false);
  const [newName, setNewName]         = useStateAQ('');
  const [newSku, setNewSku]           = useStateAQ('');
  const [newPrice, setNewPrice]       = useStateAQ('');
  const [newQty, setNewQty]           = useStateAQ(1);
  const [newCat, setNewCat]           = useStateAQ('');
  const [newSeason, setNewSeason]     = useStateAQ('');
  const [newSalePrice, setNewSalePrice] = useStateAQ('');
  const [newColors, setNewColors]     = useStateAQ('');
  const [newSizes, setNewSizes]       = useStateAQ('');
  const [showCsvModal, setShowCsvModal] = useStateAQ(false);
  const [showAiModal, setShowAiModal]   = useStateAQ(false);

  const isFullForm    = !session || session.op.role !== 'Magazziniere';
  const showOrdCol    = fromOrderId !== null && fromOrderId !== undefined;
  const WIZ           = [{ id: 1, label: 'Testata' }, { id: 2, label: 'Prodotti' }];
  const canNext1      = supplierId && storeId;
  const total         = lines.reduce((s, l) => s + (l.receivedQty || 0) * l.unitPrice, 0);

  const searchResults = useMemoAQ(() => {
    const ql = searchQ.trim().toLowerCase();
    if (!ql) return [];
    return ARTICLES.filter(a =>
      a.name.toLowerCase().includes(ql) || a.id.toLowerCase().includes(ql) || a.brand.toLowerCase().includes(ql)
    ).slice(0, 8);
  }, [searchQ]);

  const addCatalogLine = (article) => {
    if (lines.find(l => !l.isNew && l.articleId === article.id)) return;
    setLines(prev => [...prev, {
      articleId: article.id, name: article.name, sku: article.id, tmpSku: null,
      orderedQty: null, receivedQty: 1,
      unitPrice: Math.round(article.basePrice * 0.5), isNew: false, newStatus: null,
    }]);
    setSearchQ('');
  };

  const addNewLine = () => {
    if (!newName.trim() || !newSku.trim()) return;
    setLines(prev => [...prev, {
      articleId: null, name: newName.trim(), sku: null,
      tmpSku: newSku.trim().toUpperCase(), orderedQty: null,
      receivedQty: newQty, unitPrice: parseFloat(newPrice) || 0,
      isNew: true, newStatus: isFullForm ? 'Pubblicato' : 'Bozza',
      newCat: newCat.trim(), newSeason: newSeason.trim(),
      newSalePrice: parseFloat(newSalePrice) || 0,
      newColors: newColors.trim(), newSizes: newSizes.trim(),
    }]);
    setNewName(''); setNewSku(''); setNewQty(1); setNewPrice('');
    setNewCat(''); setNewSeason(''); setNewSalePrice(''); setNewColors(''); setNewSizes('');
    setShowNewForm(false);
  };

  const updateLine = (idx, field, val) =>
    setLines(prev => prev.map((l, i) => i !== idx ? l : { ...l, [field]: val }));
  const removeLine = (idx) =>
    setLines(prev => prev.filter((_, i) => i !== idx));

  const importLines = (newLines) => {
    setLines(prev => {
      const merged = [...prev];
      newLines.forEach(nl => {
        const key = nl.sku || nl.tmpSku;
        if (!key || !merged.find(l => (l.sku || l.tmpSku) === key)) merged.push(nl);
      });
      return merged;
    });
  };

  const doSave = (conferma) => {
    const id = existing?.id || ('DC 2026-' + String(Date.now()).slice(-4));
    const t  = lines.reduce((s, l) => s + (l.receivedQty || 0) * l.unitPrice, 0);
    onSave({
      id, supplierId, storeId, dateCarico, numDocFornitore, dateDocFornitore,
      linkedOrderId: fromOrderId || existing?.linkedOrderId || null,
      contoVendita, note, status: conferma ? 'Confermata' : 'Bozza', total: t,
    }, lines, id, conferma);
  };

  const cls = 'w-full h-11 px-3 rounded-md border border-line bg-surface text-[14px] text-ink focus:border-strong focus:outline-none transition-all duration-fast ease-standard';
  const lbl = 'block text-[12px] font-semibold uppercase tracking-[0.04em] text-muted mb-1.5';

  const discrepancyCount = showOrdCol
    ? lines.filter(l => l.orderedQty !== null && (l.receivedQty || 0) !== l.orderedQty).length
    : 0;

  return (
    <div className="px-7 py-6 max-w-[1400px]">
      {/* Wizard header */}
      <div className="bg-surface rounded-2xl p-5 mb-5 shadow-soft">
        <button onClick={onCancel}
          className="text-[13px] text-muted hover:text-ink inline-flex items-center gap-1.5 focus-ring rounded-md px-2 py-1 -ml-2">
          <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 alle consegne
        </button>
        <h2 className="text-[22px] font-semibold tracking-tight text-ink mt-2 flex items-center gap-2 flex-wrap">
          {existing ? `Modifica ${existing.id}` : 'Nuova consegna'}
          {fromOrderId && <span className="text-[14px] font-normal text-muted">· da {fromOrderId}</span>}
        </h2>
        <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 || done ? 'text-ink' : 'text-muted'}`}>{w.label}</span>
                </div>
                {i < WIZ.length - 1 && <div className={`flex-1 h-px ${done ? 'bg-pos' : 'bg-line'}`}/>}
              </React.Fragment>
            );
          })}
        </div>
      </div>

      {/* ── Step 1: Testata ── */}
      {step === 1 && (
        <Card title="Intestazione consegna">
          <div className="grid grid-cols-2 gap-5">
            <div>
              <label className={lbl}>Fornitore</label>
              <select className={cls} value={supplierId} onChange={e => setSupplierId(e.target.value)}
                disabled={!!fromOrderId} style={fromOrderId ? { opacity: 0.6 } : {}}>
                <option value="">— Seleziona fornitore —</option>
                {SUPPLIERS.map(s => <option key={s.id} value={s.id}>{s.name}</option>)}
              </select>
            </div>
            <div>
              <label className={lbl}>Negozio destinazione</label>
              <select className={cls} value={storeId} onChange={e => setStoreId(e.target.value)}
                disabled={!!fromOrderId} style={fromOrderId ? { opacity: 0.6 } : {}}>
                {STORES.map(s => <option key={s.id} value={s.id}>{s.name}</option>)}
              </select>
            </div>
            <div>
              <label className={lbl}>Data carico</label>
              <input type="date" className={cls} value={dateCarico} onChange={e => setDateCarico(e.target.value)}/>
            </div>
            <div>
              <label className={lbl}>N° documento fornitore (DDT)</label>
              <input type="text" className={cls} value={numDocFornitore}
                onChange={e => setNumDocFornitore(e.target.value)} placeholder="es. DDT-2026-1045"/>
            </div>
            <div>
              <label className={lbl}>Data documento fornitore</label>
              <input type="date" className={cls} value={dateDocFornitore}
                onChange={e => setDateDocFornitore(e.target.value)}/>
            </div>
            <div className="flex items-end gap-3 pb-0.5">
              <div className="flex-1">
                <div className={lbl}>Conto vendita</div>
                <div className="flex items-center gap-3 h-11">
                  <button type="button" onClick={() => setContoVendita(!contoVendita)}
                    className="focus-ring"
                    style={{
                      position: 'relative', flexShrink: 0, border: 'none', padding: 0, cursor: 'pointer',
                      width: '44px', height: '26px', borderRadius: '13px',
                      background: contoVendita ? 'var(--accent-blue)' : 'var(--border-strong)',
                      transition: 'background 160ms cubic-bezier(0.32,0.72,0,1)',
                    }}>
                    <span style={{
                      position: 'absolute', top: '3px', left: contoVendita ? '21px' : '3px',
                      width: '20px', height: '20px', borderRadius: '50%',
                      background: 'white', boxShadow: '0 1px 3px rgba(0,0,0,0.25)',
                      transition: 'left 160ms cubic-bezier(0.32,0.72,0,1)',
                    }}/>
                  </button>
                  <span className="text-[13.5px] text-ink">{contoVendita ? 'Attivo' : 'Non attivo'}</span>
                  {contoVendita && <Pill tone="warn">Conto vendita</Pill>}
                </div>
              </div>
            </div>
          </div>
          <div className="mt-5">
            <label className={lbl}>Note</label>
            <textarea value={note} onChange={e => setNote(e.target.value)}
              placeholder="Note aggiuntive sulla consegna…"
              className="w-full h-20 px-3 py-2 rounded-md border border-line bg-surface text-[14px] text-ink focus:border-strong focus:outline-none resize-none transition-all duration-fast ease-standard"/>
          </div>
        </Card>
      )}

      {/* ── Step 2: Prodotti ── */}
      {step === 2 && (
        <div className="space-y-4">
          {/* Strumenti importazione */}
          <div className="flex items-center gap-3 flex-wrap">
            <button type="button" onClick={() => setShowCsvModal(true)}
              className="h-11 flex items-center gap-2 px-4 rounded-md border border-line bg-surface text-[13.5px] font-medium text-ink hover:border-strong transition-all duration-fast ease-standard focus-ring">
              <I.ArrowU size={16}/>
              Importa righe da file
            </button>
            <button type="button" onClick={() => setShowAiModal(true)}
              className="h-11 flex items-center gap-2 px-4 rounded-md border border-line bg-surface text-[13.5px] font-medium text-ink hover:border-strong transition-all duration-fast ease-standard focus-ring">
              <I.QR size={16}/>
              Carica DDT con AI
            </button>
            <Pill tone="info">Demo</Pill>
          </div>

          {/* Ricerca catalogo */}
          <Card title="Aggiungi prodotti dal catalogo">
            <div className="relative mb-3">
              <I.Search size={16} className="absolute left-3.5 top-1/2 -translate-y-1/2 text-muted"/>
              <input value={searchQ} onChange={e => setSearchQ(e.target.value)}
                placeholder="Cerca prodotto per nome, codice o brand…"
                className="w-full h-11 pl-10 pr-4 rounded-md border border-line bg-surface text-[14px] focus:border-strong transition-all duration-fast ease-standard"/>
            </div>
            {searchResults.length > 0 && (
              <div className="rounded-xl overflow-hidden" style={{ border: '0.5px solid var(--border-default)' }}>
                {searchResults.map(a => (
                  <button key={a.id} onClick={() => addCatalogLine(a)}
                    className="w-full px-4 py-3 flex items-center gap-3 hover:bg-paper text-left border-b border-line2 last:border-0 transition-colors duration-fast ease-standard">
                    <div className="w-9 h-9 rounded-md stripe-ph shrink-0"/>
                    <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} · {a.id}</div>
                    </div>
                    <span className="flex items-center gap-1 text-[12px] text-[var(--accent-blue)] shrink-0">
                      <I.Plus size={13}/> Aggiungi
                    </span>
                  </button>
                ))}
              </div>
            )}
            {searchQ.trim() !== '' && searchResults.length === 0 && (
              <p className="text-[13px] text-muted mt-1">Nessun prodotto trovato per "{searchQ}".</p>
            )}
          </Card>

          {/* Prodotto nuovo */}
          <Card title={isFullForm ? 'Nuovo prodotto — form completo' : 'Nuovo prodotto — form ridotto (salverà in Bozza)'}>
            {!showNewForm ? (
              <button onClick={() => setShowNewForm(true)}
                className="h-11 flex items-center gap-2 text-[13.5px] font-medium text-[var(--accent-blue)] hover:underline focus-ring rounded-md px-1">
                <I.Plus size={14}/>
                {isFullForm ? '+ Nuovo prodotto (nascerà Pubblicato)' : '+ Nuovo prodotto (nascerà in Bozza)'}
              </button>
            ) : (
              <div>
                {!isFullForm && (
                  <div className="mb-4 p-3 rounded-xl text-[12.5px]"
                    style={{ background: 'var(--warning-50)', color: 'var(--warning-700)' }}>
                    Il prodotto verrà creato in stato <strong>Bozza</strong> e non sarà visibile al POS finché un Manager non lo completa nel Catalogo.
                  </div>
                )}
                <div className="grid grid-cols-2 gap-4">
                  <div>
                    <label className={lbl}>Nome prodotto *</label>
                    <input value={newName} onChange={e => setNewName(e.target.value)}
                      placeholder="es. Cappello cashmere beret" className={cls}/>
                  </div>
                  <div>
                    <label className={lbl}>SKU / Codice *</label>
                    <input value={newSku} onChange={e => setNewSku(e.target.value)}
                      placeholder="es. HAT-0001" className={cls}/>
                  </div>
                  <div>
                    <label className={lbl}>Prezzo d'acquisto (€)</label>
                    <input type="number" min="0" step="0.01" value={newPrice}
                      onChange={e => setNewPrice(e.target.value)} placeholder="0.00" className={cls}/>
                  </div>
                  {isFullForm ? (
                    <>
                      <div>
                        <label className={lbl}>Prezzo di vendita (€) *</label>
                        <input type="number" min="0" step="0.01" value={newSalePrice}
                          onChange={e => setNewSalePrice(e.target.value)} placeholder="0.00" className={cls}/>
                      </div>
                      <div>
                        <label className={lbl}>Categoria</label>
                        <input value={newCat} onChange={e => setNewCat(e.target.value)}
                          placeholder="es. Capospalla" className={cls}/>
                      </div>
                      <div>
                        <label className={lbl}>Stagione</label>
                        <input value={newSeason} onChange={e => setNewSeason(e.target.value)}
                          placeholder="es. AI 2026" className={cls}/>
                      </div>
                      <div>
                        <label className={lbl}>Colori (separati da virgola)</label>
                        <input value={newColors} onChange={e => setNewColors(e.target.value)}
                          placeholder="es. Navy, Beige" className={cls}/>
                      </div>
                      <div>
                        <label className={lbl}>Taglie (separate da virgola)</label>
                        <input value={newSizes} onChange={e => setNewSizes(e.target.value)}
                          placeholder="es. S, M, L, XL" className={cls}/>
                      </div>
                    </>
                  ) : (
                    <div>
                      <label className={lbl}>Quantità ricevuta</label>
                      <input type="number" min="1" value={newQty}
                        onChange={e => setNewQty(Math.max(1, parseInt(e.target.value) || 1))}
                        className={cls}/>
                    </div>
                  )}
                </div>
                <div className="mt-4 flex gap-2">
                  <Btn variant="primary" size="md"
                    disabled={!newName.trim() || !newSku.trim()} onClick={addNewLine}>
                    Aggiungi riga
                  </Btn>
                  <Btn variant="outline" size="md" onClick={() => setShowNewForm(false)}>Annulla</Btn>
                </div>
              </div>
            )}
          </Card>

          {/* Righe consegna */}
          <Card title={`Righe consegna (${lines.length})`} padded={false}>
            {lines.length === 0 ? (
              <div className="p-8 text-center text-muted text-[13.5px]">
                Nessun prodotto aggiunto. Cerca nel catalogo o aggiungi un prodotto nuovo.
              </div>
            ) : (
              <>
                {/* Header colonne — layout dipende da showOrdCol */}
                {showOrdCol ? (
                  <div className="grid grid-cols-[1fr_80px_104px_152px_140px_48px] gap-2 px-5 h-11 items-center text-[11px] uppercase tracking-[0.08em] text-muted font-medium hairline">
                    <div>Prodotto</div>
                    <div className="text-right">Ordinato</div>
                    <div className="text-right">Ricevuto</div>
                    <div className="text-right">Prezzo unit. (€)</div>
                    <div className="text-right">Totale riga</div>
                    <div/>
                  </div>
                ) : (
                  <div className="grid grid-cols-[1fr_104px_152px_140px_48px] gap-2 px-5 h-11 items-center text-[11px] uppercase tracking-[0.08em] text-muted font-medium hairline">
                    <div>Prodotto</div>
                    <div className="text-right">Ricevuto</div>
                    <div className="text-right">Prezzo unit. (€)</div>
                    <div className="text-right">Totale riga</div>
                    <div/>
                  </div>
                )}
                <div className="divide-y divide-line2">
                  {lines.map((l, idx) => {
                    const ord    = l.orderedQty;
                    const rec    = l.receivedQty || 0;
                    const hasOrd = ord !== null && ord !== undefined;
                    const ok     = !hasOrd || rec === ord;
                    const exc    = hasOrd && rec > ord;
                    const rowBg  = !hasOrd ? '' : ok ? 'bg-[var(--success-50)]' : exc ? 'bg-[var(--warning-50)]' : 'bg-[var(--danger-50)]';
                    return showOrdCol ? (
                      <div key={idx} className={`grid grid-cols-[1fr_80px_104px_152px_140px_48px] gap-2 px-5 items-center row-h transition-all duration-fast ease-standard ${rowBg}`}>
                        <div className="flex items-center gap-3 min-w-0">
                          <div className="w-9 h-9 rounded-md stripe-ph shrink-0"/>
                          <div className="min-w-0">
                            <div className="text-[13.5px] font-medium text-ink truncate">{l.name}</div>
                            <div className="flex items-center gap-1.5 mt-0.5">
                              <span className="num text-[11px] text-muted">{l.sku || l.tmpSku || '—'}</span>
                              {l.isNew && <Pill tone={l.newStatus === 'Bozza' ? 'warn' : 'pos'}>{l.newStatus === 'Bozza' ? 'Bozza' : 'Nuovo'}</Pill>}
                            </div>
                          </div>
                        </div>
                        <div className={`num text-[15px] text-right ${ok ? 'text-pos' : 'text-muted'}`}>{hasOrd ? ord : '—'}</div>
                        <div className="flex justify-end">
                          <input type="number" min="0" value={rec === 0 ? '' : rec}
                            onChange={e => updateLine(idx, 'receivedQty', Math.max(0, parseInt(e.target.value) || 0))}
                            placeholder={hasOrd ? String(ord) : '0'}
                            className="w-20 h-10 px-2 rounded-sm border border-line bg-surface num text-[14px] text-right focus:border-strong transition-all"/>
                        </div>
                        <div className="flex justify-end">
                          <input type="number" min="0" step="0.01" value={l.unitPrice}
                            onChange={e => updateLine(idx, 'unitPrice', parseFloat(e.target.value) || 0)}
                            className="w-28 h-10 px-2 rounded-sm border border-line bg-surface num text-[14px] text-right focus:border-strong transition-all"/>
                        </div>
                        <div className="num text-[14px] font-semibold text-ink text-right">{fmtEur(rec * l.unitPrice)}</div>
                        <div className="flex justify-center">
                          <button type="button" onClick={() => removeLine(idx)}
                            className="w-9 h-9 rounded-md flex items-center justify-center text-muted hover:bg-[var(--danger-50)] hover:text-[var(--danger-700)] transition-colors duration-fast ease-standard focus-ring">
                            <I.Trash size={14}/>
                          </button>
                        </div>
                      </div>
                    ) : (
                      <div key={idx} className={`grid grid-cols-[1fr_104px_152px_140px_48px] gap-2 px-5 items-center row-h ${rowBg}`}>
                        <div className="flex items-center gap-3 min-w-0">
                          <div className="w-9 h-9 rounded-md stripe-ph shrink-0"/>
                          <div className="min-w-0">
                            <div className="text-[13.5px] font-medium text-ink truncate">{l.name}</div>
                            <div className="flex items-center gap-1.5 mt-0.5">
                              <span className="num text-[11px] text-muted">{l.sku || l.tmpSku || '—'}</span>
                              {l.isNew && <Pill tone={l.newStatus === 'Bozza' ? 'warn' : 'pos'}>{l.newStatus === 'Bozza' ? 'Bozza' : 'Nuovo'}</Pill>}
                            </div>
                          </div>
                        </div>
                        <div className="flex justify-end">
                          <input type="number" min="0" value={rec === 0 ? '' : rec}
                            onChange={e => updateLine(idx, 'receivedQty', Math.max(0, parseInt(e.target.value) || 0))}
                            placeholder="0"
                            className="w-20 h-10 px-2 rounded-sm border border-line bg-surface num text-[14px] text-right focus:border-strong transition-all"/>
                        </div>
                        <div className="flex justify-end">
                          <input type="number" min="0" step="0.01" value={l.unitPrice}
                            onChange={e => updateLine(idx, 'unitPrice', parseFloat(e.target.value) || 0)}
                            className="w-28 h-10 px-2 rounded-sm border border-line bg-surface num text-[14px] text-right focus:border-strong transition-all"/>
                        </div>
                        <div className="num text-[14px] font-semibold text-ink text-right">{fmtEur(rec * l.unitPrice)}</div>
                        <div className="flex justify-center">
                          <button type="button" onClick={() => removeLine(idx)}
                            className="w-9 h-9 rounded-md flex items-center justify-center text-muted hover:bg-[var(--danger-50)] hover:text-[var(--danger-700)] transition-colors duration-fast ease-standard focus-ring">
                            <I.Trash size={14}/>
                          </button>
                        </div>
                      </div>
                    );
                  })}
                </div>
                {discrepancyCount > 0 && (
                  <div className="px-5 py-3 border-t border-line flex items-center gap-2 text-[12.5px]"
                    style={{ color: 'var(--warning-700)', background: 'var(--warning-50)' }}>
                    <I.Bell size={13}/>
                    {discrepancyCount} riga{discrepancyCount > 1 ? 'he' : ''} con quantità diversa dall'ordinato
                  </div>
                )}
                <div className="px-5 py-4 border-t border-line flex justify-end items-center gap-6">
                  <span className="text-[13px] text-muted">Totale consegna</span>
                  <span className="num text-[22px] font-semibold text-ink">{fmtEur(total)}</span>
                </div>
              </>
            )}
          </Card>
        </div>
      )}

      {/* Footer wizard */}
      <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>
          ) : (
            <Btn variant="outline" size="lg" onClick={onCancel}>Annulla</Btn>
          )}
        </div>
        <div className="flex items-center gap-3">
          <span className="text-[12.5px] text-muted">Step {step} di 2</span>
          {step < 2 ? (
            <Btn variant="primary" size="lg" disabled={!canNext1} onClick={() => setStep(2)} trailing={<I.ArrowR size={18}/>}>
              Avanti
            </Btn>
          ) : (
            <>
              <Btn variant="outline" size="lg" onClick={() => doSave(false)}>Salva come bozza</Btn>
              <button type="button" onClick={() => doSave(true)} 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 carico
              </button>
            </>
          )}
        </div>
      </div>
      {showCsvModal && (
        <ConsegnaImportModal onClose={() => setShowCsvModal(false)} onImport={importLines} isFullForm={isFullForm}/>
      )}
      {showAiModal && (
        <AiDdtModal onClose={() => setShowAiModal(false)} onImport={importLines} isFullForm={isFullForm}/>
      )}
    </div>
  );
};

// ─── Schermata di riepilogo post-conferma ───
const ConsegnaConfermaView = ({ delivery, lines, linkedOrder, onBack, onCatalog }) => {
  const newPublished = lines.filter(l => l.isNew && l.newStatus !== 'Bozza').length;
  const newDraft     = lines.filter(l => l.isNew && l.newStatus === 'Bozza').length;
  const totalNew     = newPublished + newDraft;
  const giacenze     = lines.filter(l => !l.isNew).length;
  const discrepanze  = linkedOrder
    ? lines.filter(l => l.orderedQty !== null && l.orderedQty !== undefined && (l.receivedQty || 0) !== l.orderedQty).length
    : 0;
  const supplier = SUPPLIERS.find(s => s.id === delivery.supplierId);
  const store    = STORES.find(s => s.id === delivery.storeId);

  return (
    <div className="px-7 py-12 max-w-[720px] mx-auto text-center">
      <div className="w-16 h-16 rounded-full flex items-center justify-center mx-auto mb-5"
        style={{ background: 'var(--success-50)' }}>
        <I.Check size={28} className="text-pos"/>
      </div>
      <div className="text-[24px] font-semibold tracking-tight text-ink mb-1">Consegna confermata</div>
      <div className="text-[14px] text-muted mb-8">{delivery.id} · {supplier?.name} → {store?.name}</div>

      <div className="bg-surface rounded-2xl p-6 text-left space-y-3 shadow-soft mb-6">
        <div className="flex items-center justify-between">
          <span className="text-[14px] text-muted">Righe caricate</span>
          <span className="num font-semibold text-ink">{lines.length}</span>
        </div>
        <div className="flex items-center justify-between">
          <span className="text-[14px] text-muted">Giacenze aggiornate</span>
          <span className="num font-semibold text-pos">+{giacenze}</span>
        </div>
        {totalNew > 0 && (
          <div className="flex items-center justify-between">
            <span className="text-[14px] text-muted">Nuovi prodotti creati in catalogo</span>
            <span className="num font-semibold text-ink">{totalNew}</span>
          </div>
        )}
        {newDraft > 0 && (
          <div className="flex items-center justify-between pl-4">
            <span className="text-[13px]" style={{ color: 'var(--warning-700)' }}>di cui in Bozza (da finalizzare)</span>
            <span className="num font-semibold" style={{ color: 'var(--warning-700)' }}>{newDraft}</span>
          </div>
        )}
        {linkedOrder && (
          <div className="flex items-center justify-between pt-2 border-t border-line">
            <span className="text-[14px] text-muted">Ordine collegato aggiornato a</span>
            <Pill tone="pos">Ricevuto</Pill>
          </div>
        )}
        {discrepanze > 0 && (
          <div className="flex items-center justify-between pt-2 border-t border-line">
            <span className="text-[14px]" style={{ color: 'var(--warning-700)' }}>Righe con quantità diversa dall'ordinato</span>
            <span className="num font-semibold" style={{ color: 'var(--warning-700)' }}>{discrepanze}</span>
          </div>
        )}
        {delivery.contoVendita && (
          <div className="flex items-center justify-between pt-2 border-t border-line">
            <span className="text-[14px] text-muted">Tipo consegna</span>
            <Pill tone="warn">Conto vendita</Pill>
          </div>
        )}
      </div>

      <div className="flex items-center justify-center gap-3">
        <Btn variant="outline" size="lg" onClick={onBack}>Torna alla lista</Btn>
        <button type="button" onClick={onCatalog}
          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)] transition-all duration-fast ease-standard shadow-soft">
          <I.Tag size={20}/>
          Apri catalogo
        </button>
      </div>
    </div>
  );
};

// ─── Dettaglio consegna (sola lettura) ───
const ConsegnaDetail = ({ delivery, lines, linkedOrder, onBack }) => {
  const supplier   = SUPPLIERS.find(s => s.id === delivery.supplierId);
  const store      = STORES.find(s => s.id === delivery.storeId);
  const totalCalc  = lines.reduce((s, l) => s + (l.receivedQty || 0) * l.unitPrice, 0);
  const showOrdCol = lines.some(l => l.orderedQty !== null && l.orderedQty !== undefined);

  return (
    <div className="px-7 py-6 max-w-[1400px]">
      <button onClick={onBack}
        className="text-[13px] text-muted hover:text-ink inline-flex items-center gap-1.5 mb-3 focus-ring rounded-md px-2 py-1 -ml-2">
        <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 alle consegne
      </button>

      <div className="flex items-start justify-between gap-4 mb-5">
        <div>
          <div className="text-[11px] uppercase tracking-[0.08em] text-muted font-medium">Consegna fornitore</div>
          <div className="text-[22px] font-semibold tracking-tight text-ink mt-0.5 flex items-center gap-3 flex-wrap">
            {delivery.id}
            {delivery.contoVendita && <Pill tone="warn">Conto vendita</Pill>}
          </div>
        </div>
        <Pill tone={DELIVERY_STATUS_TONE[delivery.status] || 'neutral'}>{delivery.status}</Pill>
      </div>

      <Card className="mb-4">
        <div className="grid gap-5" style={{ gridTemplateColumns: 'repeat(4, 1fr)' }}>
          <KeyVal label="Fornitore"            value={supplier?.name || delivery.supplierId}/>
          <KeyVal label="Negozio destinazione" value={store?.name || delivery.storeId}/>
          <KeyVal label="Data carico"          value={delivery.dateCarico || '—'}/>
          <KeyVal label="N° doc. fornitore"    value={delivery.numDocFornitore || '—'}/>
          {linkedOrder && <KeyVal label="Ordine collegato" value={linkedOrder.id}/>}
          {delivery.note && <KeyVal label="Note" value={delivery.note}/>}
        </div>
      </Card>

      <Card title={`Righe — ${lines.length} prodotti`} padded={false}>
        {showOrdCol ? (
          <>
            <div className="grid grid-cols-[1fr_80px_80px_80px_140px_140px] gap-2 px-5 h-11 items-center text-[11px] uppercase tracking-[0.08em] text-muted font-medium hairline">
              <div>Prodotto</div>
              <div className="text-right">Ordinato</div>
              <div className="text-right">Ricevuto</div>
              <div className="text-right">Diff.</div>
              <div className="text-right">Prezzo unit.</div>
              <div className="text-right">Totale</div>
            </div>
            <div className="divide-y divide-line2">
              {lines.map((l, idx) => {
                const rec    = l.receivedQty || 0;
                const ord    = l.orderedQty;
                const hasOrd = ord !== null && ord !== undefined;
                const delta  = hasOrd ? rec - ord : null;
                const ok     = delta === null || delta === 0;
                const exc    = delta !== null && delta > 0;
                const rowBg  = !hasOrd ? '' : ok ? 'bg-[var(--success-50)]' : exc ? 'bg-[var(--warning-50)]' : 'bg-[var(--danger-50)]';
                return (
                  <div key={idx} className={`grid grid-cols-[1fr_80px_80px_80px_140px_140px] gap-2 px-5 items-center row-h ${rowBg}`}>
                    <div className="flex items-center gap-3 min-w-0">
                      <div className="w-9 h-9 rounded-md stripe-ph shrink-0"/>
                      <div className="min-w-0">
                        <div className="text-[14px] font-medium text-ink truncate">{l.name}</div>
                        <div className="flex items-center gap-1.5 mt-0.5">
                          <span className="num text-[11px] text-muted">{l.sku || l.tmpSku || '—'}</span>
                          {l.isNew && <Pill tone={l.newStatus === 'Bozza' ? 'warn' : 'pos'}>{l.newStatus === 'Bozza' ? 'Bozza' : 'Nuovo'}</Pill>}
                        </div>
                      </div>
                    </div>
                    <div className="num text-[15px] text-ink text-right">{hasOrd ? ord : '—'}</div>
                    <div className="num text-[15px] text-ink text-right">{rec}</div>
                    <div className={`num text-[15px] text-right font-semibold ${ok ? 'text-pos' : exc ? 'text-warn' : 'text-neg'}`}>
                      {delta === null ? '—' : ok ? '0' : exc ? `+${delta}` : String(delta)}
                    </div>
                    <div className="num text-[15px] text-ink text-right">{fmtEur(l.unitPrice)}</div>
                    <div className="num text-[15px] font-semibold text-ink text-right">{fmtEur(rec * l.unitPrice)}</div>
                  </div>
                );
              })}
            </div>
          </>
        ) : (
          <>
            <div className="grid grid-cols-[1fr_80px_140px_140px] gap-2 px-5 h-11 items-center text-[11px] uppercase tracking-[0.08em] text-muted font-medium hairline">
              <div>Prodotto</div>
              <div className="text-right">Ricevuto</div>
              <div className="text-right">Prezzo unit.</div>
              <div className="text-right">Totale</div>
            </div>
            <div className="divide-y divide-line2">
              {lines.map((l, idx) => {
                const rec = l.receivedQty || 0;
                return (
                  <div key={idx} className="grid grid-cols-[1fr_80px_140px_140px] gap-2 px-5 items-center row-h">
                    <div className="flex items-center gap-3 min-w-0">
                      <div className="w-9 h-9 rounded-md stripe-ph shrink-0"/>
                      <div className="min-w-0">
                        <div className="text-[14px] font-medium text-ink truncate">{l.name}</div>
                        <div className="flex items-center gap-1.5 mt-0.5">
                          <span className="num text-[11px] text-muted">{l.sku || l.tmpSku || '—'}</span>
                          {l.isNew && <Pill tone={l.newStatus === 'Bozza' ? 'warn' : 'pos'}>{l.newStatus === 'Bozza' ? 'Bozza' : 'Nuovo'}</Pill>}
                        </div>
                      </div>
                    </div>
                    <div className="num text-[15px] text-ink text-right">{rec}</div>
                    <div className="num text-[15px] text-ink text-right">{fmtEur(l.unitPrice)}</div>
                    <div className="num text-[15px] font-semibold text-ink text-right">{fmtEur(rec * l.unitPrice)}</div>
                  </div>
                );
              })}
            </div>
          </>
        )}
        {lines.length === 0 && (
          <div className="py-10 text-center text-muted text-[13.5px]">Nessuna riga prodotto.</div>
        )}
        <div className="px-5 py-4 border-t border-line flex justify-end items-center gap-6">
          <span className="text-[13px] text-muted">Totale consegna</span>
          <span className="num text-[22px] font-semibold text-ink">{fmtEur(totalCalc)}</span>
        </div>
      </Card>
    </div>
  );
};

// ══════════════════════════════════════════════════════════════════════
//  RESI A FORNITORE
// ══════════════════════════════════════════════════════════════════════

// ─── Lista resi ───
const ResiList = ({ returns, returnLines, deliveries, onNew, onOpen }) => {
  const [q, setQ]                             = useStateAQ('');
  const [filterFornitore, setFilterFornitore] = useStateAQ('Tutti');
  const [filterMotivo, setFilterMotivo]       = useStateAQ('Tutti');
  const [filterStore, setFilterStore]         = useStateAQ('Tutti');

  const fornitori = useMemoAQ(() =>
    ['Tutti', ...Array.from(new Set(returns.map(r =>
      SUPPLIERS.find(s => s.id === r.supplierId)?.name || r.supplierId
    )))],
  [returns]);

  const filtered = useMemoAQ(() => {
    const ql = q.trim().toLowerCase();
    return returns.filter(r => {
      const sName  = SUPPLIERS.find(s => s.id === r.supplierId)?.name || r.supplierId;
      const stName = STORES.find(s => s.id === r.storeId)?.name || r.storeId;
      if (filterFornitore !== 'Tutti' && sName !== filterFornitore) return false;
      if (filterMotivo !== 'Tutti' && r.motivo !== filterMotivo) return false;
      if (filterStore !== 'Tutti' && stName !== filterStore) return false;
      if (ql && !r.id.toLowerCase().includes(ql) && !(r.deliveryId || '').toLowerCase().includes(ql) && !sName.toLowerCase().includes(ql)) return false;
      return true;
    });
  }, [q, filterFornitore, filterMotivo, filterStore, returns]);

  const negozi = ['Tutti', ...STORES.map(s => s.name)];
  const motivi = ['Tutti', ...getMotiviReso()];

  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">Resi a fornitore</h2>
          <p className="text-[13.5px] text-muted mt-0.5">Gestione resi di merce verso i fornitori.</p>
        </div>
        <button onClick={onNew}
          className="h-16 px-6 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)] transition-all duration-fast ease-standard shadow-soft">
          <I.Plus size={20}/>
          Nuovo reso
        </button>
      </div>

      <div className="grid grid-cols-2 gap-4">
        <AcqKpi label="Bozze"      value={returns.filter(r => r.status === 'Bozza').length}      sub="da completare"/>
        <AcqKpi label="Confermati" value={returns.filter(r => r.status === 'Confermato').length} sub="inviati al fornitore" tone="pos"/>
      </div>

      <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-[240px]">
            <I.Search size={16} 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 numero reso o numero consegna…"
              className="w-full h-11 pl-10 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="Fornitore" value={filterFornitore} onChange={setFilterFornitore} options={fornitori}/>
          <FilterSelect label="Motivo"    value={filterMotivo}    onChange={setFilterMotivo}    options={motivi}/>
          <FilterSelect label="Negozio"   value={filterStore}     onChange={setFilterStore}     options={negozi}/>
        </div>
      </div>

      <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">N° Reso</th>
              <th className="px-5 py-3 font-medium">Fornitore</th>
              <th className="px-5 py-3 font-medium">Negozio</th>
              <th className="px-5 py-3 font-medium">Data reso</th>
              <th className="px-5 py-3 font-medium">Consegna rif.</th>
              <th className="px-5 py-3 font-medium">Motivo</th>
              <th className="px-5 py-3 font-medium">Stato</th>
              <th className="px-5 py-3 font-medium text-right">Totale</th>
              <th className="px-5 py-3 font-medium"></th>
            </tr>
          </thead>
          <tbody>
            {filtered.map(r => {
              const supplier = SUPPLIERS.find(s => s.id === r.supplierId);
              const store    = STORES.find(s => s.id === r.storeId);
              return (
                <tr key={r.id} onClick={() => onOpen(r.id)}
                    className="hover:bg-paper border-b border-line2 last:border-0 cursor-pointer">
                  <td className="px-5 py-4 num text-ink font-medium">{r.id}</td>
                  <td className="px-5 py-4 text-ink">{supplier?.name || r.supplierId}</td>
                  <td className="px-5 py-4 text-ink">{store?.name || r.storeId}</td>
                  <td className="px-5 py-4 text-ink">{r.dateReso}</td>
                  <td className="px-5 py-4 num text-muted">{r.deliveryId}</td>
                  <td className="px-5 py-4">
                    <span className={r.motivo === 'Fine conto vendita' ? 'text-[var(--info-700)] font-medium' : 'text-ink'}>
                      {r.motivo}
                    </span>
                  </td>
                  <td className="px-5 py-4">
                    <Pill tone={RETURN_STATUS_TONE[r.status] || 'neutral'}>{r.status}</Pill>
                  </td>
                  <td className="px-5 py-4 num text-ink text-right font-semibold">
                    {r.total > 0 ? fmtEur(r.total) : '—'}
                  </td>
                  <td className="px-5 py-4 text-right">
                    <span className="text-[12.5px] text-[var(--accent-blue)] pointer-events-none">
                      {r.status === 'Bozza' ? 'Modifica' : 'Apri'}
                    </span>
                  </td>
                </tr>
              );
            })}
          </tbody>
        </table>
        {filtered.length === 0 && (
          <div className="py-16 text-center text-muted text-[14px]">Nessun reso corrisponde ai filtri.</div>
        )}
      </Card>
    </div>
  );
};

// ─── Step 1: selezione consegna di origine ───
const ResoPicker = ({ deliveries, returns, returnLines, onPick, onCancel }) => {
  const [q, setQ]                               = useStateAQ('');
  const [filterFornitore, setFilterFornitore]   = useStateAQ('Tutti');
  const [soloCV, setSoloCV]                     = useStateAQ(false);

  const fornitori = useMemoAQ(() =>
    ['Tutti', ...Array.from(new Set(deliveries.map(d =>
      SUPPLIERS.find(s => s.id === d.supplierId)?.name || d.supplierId
    )))],
  [deliveries]);

  const filtered = useMemoAQ(() => {
    const ql = q.trim().toLowerCase();
    return deliveries.filter(d => {
      const sName = SUPPLIERS.find(s => s.id === d.supplierId)?.name || d.supplierId;
      if (filterFornitore !== 'Tutti' && sName !== filterFornitore) return false;
      if (soloCV && !d.contoVendita) return false;
      if (ql && !d.id.toLowerCase().includes(ql) && !sName.toLowerCase().includes(ql)) return false;
      return true;
    });
  }, [q, filterFornitore, soloCV, deliveries]);

  const prevResiByDelivery = useMemoAQ(() => {
    const map = {};
    deliveries.forEach(d => {
      map[d.id] = returns.filter(r => r.deliveryId === d.id && r.status === 'Confermato').length;
    });
    return map;
  }, [deliveries, returns]);

  return (
    <div className="px-7 py-6 max-w-[1400px]">
      <button onClick={onCancel}
        className="text-[13px] text-muted hover:text-ink inline-flex items-center gap-1.5 mb-4 focus-ring rounded-md px-2 py-1 -ml-2">
        <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 alla lista
      </button>

      <div className="mb-5">
        <h2 className="text-[20px] font-semibold tracking-tight text-ink">Nuovo reso — seleziona la consegna di origine</h2>
        <p className="text-[13.5px] text-muted mt-1">Ogni reso deve essere collegato alla consegna da cui proviene la merce.</p>
      </div>

      <div className="bg-surface rounded-2xl p-3.5 shadow-soft mb-4">
        <div className="flex flex-wrap items-center gap-2.5">
          <div className="relative flex-1 min-w-[240px]">
            <I.Search size={16} 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 numero consegna o fornitore…"
              className="w-full h-11 pl-10 pr-4 rounded-md bg-sunken text-[14px] shadow-[inset_0_0_0_0.5px_var(--border-default)] focus:bg-surface transition-all duration-fast ease-standard"/>
          </div>
          <FilterSelect label="Fornitore" value={filterFornitore} onChange={setFilterFornitore} options={fornitori}/>
          {/* Checkbox solo conto vendita */}
          <label className="inline-flex items-center gap-2 h-11 px-3 rounded-md border cursor-pointer select-none transition-all duration-fast ease-standard"
            style={{ borderColor: soloCV ? 'var(--accent-blue)' : 'var(--border-default)', background: soloCV ? 'var(--bg-selected)' : 'transparent' }}>
            <input type="checkbox" checked={soloCV} onChange={e => setSoloCV(e.target.checked)} className="sr-only"/>
            <span style={{
              display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
              width: 18, height: 18, borderRadius: 4, flexShrink: 0,
              border: `2px solid ${soloCV ? 'var(--accent-blue)' : 'var(--border-default)'}`,
              background: soloCV ? 'var(--accent-blue)' : 'transparent',
              transition: 'all 160ms cubic-bezier(0.32,0.72,0,1)',
            }}>
              {soloCV && <I.Check size={10} className="text-white"/>}
            </span>
            <span className="text-[13px] font-medium text-ink">Solo conto vendita</span>
          </label>
        </div>
      </div>

      <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">N° Consegna</th>
              <th className="px-5 py-3 font-medium">Fornitore</th>
              <th className="px-5 py-3 font-medium">Negozio</th>
              <th className="px-5 py-3 font-medium">Data carico</th>
              <th className="px-5 py-3 font-medium">Doc. fornitore</th>
              <th className="px-5 py-3 font-medium">Tipo</th>
              <th className="px-5 py-3 font-medium">Resi prec.</th>
              <th className="px-5 py-3 font-medium text-right">Totale</th>
            </tr>
          </thead>
          <tbody>
            {filtered.map(d => {
              const supplier = SUPPLIERS.find(s => s.id === d.supplierId);
              const store    = STORES.find(s => s.id === d.storeId);
              const nResi    = prevResiByDelivery[d.id] || 0;
              return (
                <tr key={d.id} onClick={() => onPick(d.id)}
                    className="hover:bg-paper border-b border-line2 last:border-0 cursor-pointer">
                  <td className="px-5 py-4 num text-ink font-medium">{d.id}</td>
                  <td className="px-5 py-4 text-ink">{supplier?.name || d.supplierId}</td>
                  <td className="px-5 py-4 text-ink">{store?.name || d.storeId}</td>
                  <td className="px-5 py-4 text-ink">{d.dateCarico}</td>
                  <td className="px-5 py-4 num text-muted">{d.numDocFornitore || '—'}</td>
                  <td className="px-5 py-4">
                    {d.contoVendita
                      ? <Pill tone="info">Conto vendita</Pill>
                      : <Pill tone="neutral">Acquisto</Pill>}
                  </td>
                  <td className="px-5 py-4">
                    {nResi > 0
                      ? <span className="num text-[12.5px] text-muted">{nResi} reso{nResi > 1 ? 'i' : ''}</span>
                      : <span className="text-[12.5px] text-muted">—</span>}
                  </td>
                  <td className="px-5 py-4 num text-ink text-right font-semibold">{fmtEur(d.total)}</td>
                </tr>
              );
            })}
          </tbody>
        </table>
        {filtered.length === 0 && (
          <div className="py-16 text-center text-muted text-[14px]">Nessuna consegna confermata disponibile.</div>
        )}
      </Card>
    </div>
  );
};

// ─── Step 2: quantità, motivo, note ───
const ResoWizard = ({ delivery, deliveryLines, returns, returnLines, existing, existingLines, session, onSave, onCancel }) => {
  const isCV = delivery?.contoVendita || false;

  const [motivo, setMotivo] = useStateAQ(existing?.motivo || (isCV ? 'Fine conto vendita' : ''));
  const [note, setNote]     = useStateAQ(existing?.note || '');
  const [qtys, setQtys]     = useStateAQ(() => {
    if (existing && existingLines.length > 0) {
      const map = {};
      existingLines.forEach(l => { map[l.sku] = l.returnQty; });
      return map;
    }
    const map = {};
    (deliveryLines || []).forEach(l => { map[l.sku] = 0; });
    return map;
  });

  const alreadyMap = useMemoAQ(() => {
    if (!delivery) return {};
    const linkedIds = (returns || [])
      .filter(r => r.deliveryId === delivery.id && r.status === 'Confermato' && r.id !== existing?.id)
      .map(r => r.id);
    const map = {};
    (deliveryLines || []).forEach(l => {
      map[l.sku] = linkedIds.reduce((tot, rId) => {
        const rls = (returnLines || {})[rId] || [];
        const m   = rls.find(rl => rl.sku === l.sku);
        return tot + (m?.returnQty || 0);
      }, 0);
    });
    return map;
  }, [returns, returnLines, delivery, deliveryLines, existing]);

  const total = useMemoAQ(() =>
    (deliveryLines || []).reduce((s, l) => s + (qtys[l.sku] || 0) * l.unitPrice, 0),
  [qtys, deliveryLines]);

  const itemCount  = Object.values(qtys).reduce((a, b) => a + b, 0);
  const canConfirm = !!motivo && itemCount > 0;

  const setQty = (sku, val, max) =>
    setQtys(prev => ({ ...prev, [sku]: Math.max(0, Math.min(max, val)) }));

  const doSave = (conferma) => {
    const months = ['gen','feb','mar','apr','mag','giu','lug','ago','set','ott','nov','dic'];
    const now = new Date();
    const dateReso = `${now.getDate()} ${months[now.getMonth()]} ${now.getFullYear()}`;
    const lines = (deliveryLines || [])
      .filter(l => (qtys[l.sku] || 0) > 0)
      .map(l => ({ articleId: l.articleId, name: l.name, sku: l.sku, returnQty: qtys[l.sku], unitPrice: l.unitPrice }));
    const id = existing?.id || ('RF 2026-' + String(Date.now()).slice(-4));
    onSave({
      id, supplierId: delivery.supplierId, storeId: delivery.storeId,
      dateReso, deliveryId: delivery.id, motivo, note,
      status: conferma ? 'Confermato' : 'Bozza', total,
    }, lines, id, conferma);
  };

  const supplier = delivery ? SUPPLIERS.find(s => s.id === delivery.supplierId) : null;
  const store    = delivery ? STORES.find(s => s.id === delivery.storeId) : null;
  const cls = 'w-full h-11 px-3 rounded-md border border-line bg-surface text-[14px] text-ink focus:border-strong focus:outline-none transition-all duration-fast ease-standard';
  const lbl = 'block text-[12px] font-semibold uppercase tracking-[0.04em] text-muted mb-1.5';

  if (!delivery) return null;

  return (
    <div className="px-7 py-6 space-y-4 max-w-[1400px]">
      <button onClick={onCancel}
        className="text-[13px] text-muted hover:text-ink inline-flex items-center gap-1.5 -ml-2 focus-ring rounded-md px-2 py-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 alla selezione
      </button>

      {/* Header consegna */}
      <Card>
        <div className="flex items-start justify-between gap-4">
          <div>
            <div className="text-[11px] uppercase tracking-[0.08em] text-muted font-medium mb-0.5">Consegna di origine</div>
            <div className="text-[20px] font-semibold text-ink">{delivery.id}</div>
            <div className="text-[13.5px] text-muted mt-0.5">{supplier?.name} · {store?.name} · {delivery.dateCarico}</div>
          </div>
          <div className="flex items-center gap-2 mt-1">
            {isCV && <Pill tone="info">Conto vendita</Pill>}
            <Pill tone="pos">Confermata</Pill>
          </div>
        </div>
        {isCV && (
          <div className="mt-3 p-3 rounded-xl text-[13px]"
            style={{ background: 'var(--info-50)', color: 'var(--info-700)' }}>
            Consegna in <strong>conto vendita</strong> — il motivo "Fine conto vendita" è pre-selezionato.
          </div>
        )}
      </Card>

      {/* Righe */}
      <Card title={`Seleziona prodotti da rendere${itemCount > 0 ? ` — ${itemCount} pezzi` : ''}`} padded={false}>
        <div className="grid grid-cols-[1fr_96px_96px_152px] gap-3 px-5 h-11 items-center text-[11px] uppercase tracking-[0.08em] text-muted font-medium hairline">
          <div>Prodotto</div>
          <div className="text-right">Caricato</div>
          <div className="text-right">Già reso</div>
          <div className="text-right">Da rendere</div>
        </div>
        <div className="divide-y divide-line2">
          {(deliveryLines || []).map((l, idx) => {
            const already  = alreadyMap[l.sku] || 0;
            const maxQty   = (l.receivedQty || 0) - already;
            const qty      = qtys[l.sku] || 0;
            return (
              <div key={idx}
                className={`grid grid-cols-[1fr_96px_96px_152px] gap-3 px-5 items-center row-h transition-colors duration-fast ease-standard ${qty > 0 ? 'bg-[var(--bg-selected)]' : ''}`}>
                <div className="flex items-center gap-3 min-w-0">
                  <div className="w-9 h-9 rounded-md stripe-ph shrink-0"/>
                  <div className="min-w-0">
                    <div className="text-[13.5px] font-medium text-ink truncate">{l.name}</div>
                    <span className="num text-[11px] text-muted">{l.sku}</span>
                  </div>
                </div>
                <div className="num text-[14px] text-muted text-right">{l.receivedQty ?? '—'}</div>
                <div className={`num text-[14px] text-right ${already > 0 ? 'text-warn' : 'text-muted'}`}>
                  {already > 0 ? already : '—'}
                </div>
                <div className="flex justify-end">
                  {maxQty <= 0 ? (
                    <span className="text-[12px] text-muted italic">Tutto reso</span>
                  ) : (
                    <div className="flex items-center gap-1.5">
                      <button type="button" onClick={() => setQty(l.sku, qty - 1, maxQty)}
                        className="w-9 h-9 rounded-md border border-line flex items-center justify-center text-ink hover:bg-paper transition-colors duration-fast ease-standard focus-ring">
                        <I.Minus size={14}/>
                      </button>
                      <input type="number" min="0" max={maxQty} value={qty || ''}
                        onChange={e => setQty(l.sku, parseInt(e.target.value) || 0, maxQty)}
                        placeholder="0"
                        className="w-16 h-9 px-2 rounded-sm border border-line bg-surface num text-[14px] text-center focus:border-strong transition-all"/>
                      <button type="button" onClick={() => setQty(l.sku, qty + 1, maxQty)}
                        className="w-9 h-9 rounded-md border border-line flex items-center justify-center text-ink hover:bg-paper transition-colors duration-fast ease-standard focus-ring">
                        <I.Plus size={14}/>
                      </button>
                    </div>
                  )}
                </div>
              </div>
            );
          })}
        </div>
        {itemCount > 0 && (
          <div className="px-5 py-4 border-t border-line flex justify-end items-center gap-6">
            <span className="text-[13px] text-muted">Totale reso</span>
            <span className="num text-[22px] font-semibold text-ink">{fmtEur(total)}</span>
          </div>
        )}
      </Card>

      {/* Motivazione */}
      <Card title="Motivazione">
        <div className="grid grid-cols-2 gap-5">
          <div>
            <label className={lbl}>Motivo del reso *</label>
            <div className="relative">
              <select value={motivo} onChange={e => setMotivo(e.target.value)}
                className={`${cls} appearance-none pr-8`}>
                <option value="">— Seleziona il motivo —</option>
                {getMotiviReso().map(m => (
                  <option key={m} value={m}>{m}{m === 'Fine conto vendita' && isCV ? ' ★' : ''}</option>
                ))}
              </select>
              <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round" strokeLinejoin="round"
                className="absolute right-2.5 top-1/2 -translate-y-1/2 text-muted pointer-events-none">
                <path d="M6 9l6 6 6-6"/>
              </svg>
            </div>
            {!motivo && (
              <p className="mt-1 text-[12px] text-neg">Il motivo è obbligatorio per confermare il reso.</p>
            )}
          </div>
          <div>
            <label className={lbl}>Note (opzionale)</label>
            <textarea value={note} onChange={e => setNote(e.target.value)}
              placeholder="Ulteriori dettagli sul reso…"
              className="w-full h-11 px-3 py-2.5 rounded-md border border-line bg-surface text-[14px] text-ink focus:border-strong focus:outline-none resize-none transition-all duration-fast ease-standard"/>
          </div>
        </div>
      </Card>

      {/* Footer */}
      <div className="flex items-center justify-between bg-surface rounded-2xl p-4 shadow-soft">
        <Btn variant="outline" size="lg" onClick={onCancel}>Indietro</Btn>
        <div className="flex items-center gap-3">
          <Btn variant="outline" size="lg" onClick={() => doSave(false)}>Salva come bozza</Btn>
          <button type="button" onClick={() => doSave(true)} disabled={!canConfirm}
            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 reso
          </button>
        </div>
      </div>
    </div>
  );
};

// ─── Riepilogo post-conferma ───
const ResoConfermaView = ({ returnData, lines, delivery, onBack, onNew }) => {
  const supplier  = delivery ? SUPPLIERS.find(s => s.id === delivery.supplierId) : null;
  const totalPcs  = lines.reduce((s, l) => s + l.returnQty, 0);

  return (
    <div className="px-7 py-10 flex justify-center">
      <div className="bg-surface rounded-2xl shadow-modal p-8 text-center w-full max-w-[600px]">
        <div className="w-16 h-16 rounded-full flex items-center justify-center mx-auto mb-4"
          style={{ background: 'var(--success-50)' }}>
          <I.Check size={32} className="text-pos"/>
        </div>
        <h2 className="text-[22px] font-semibold text-ink tracking-tight">Reso confermato</h2>
        <p className="num text-[14px] text-muted mt-0.5 mb-6">{returnData.id}</p>

        <div className="grid grid-cols-2 gap-4 text-left mb-6">
          <div className="p-4 bg-paper rounded-xl">
            <div className="text-[11px] uppercase tracking-[0.08em] text-muted font-medium">Righe rese</div>
            <div className="num text-[28px] font-semibold text-ink mt-1">{lines.length}</div>
            <div className="text-[12.5px] text-muted">{totalPcs} pezzi totali</div>
          </div>
          <div className="p-4 bg-paper rounded-xl">
            <div className="text-[11px] uppercase tracking-[0.08em] text-muted font-medium">Totale reso</div>
            <div className="num text-[28px] font-semibold text-ink mt-1">{fmtEur(returnData.total)}</div>
            <div className="text-[12.5px] text-muted">a credito fornitore</div>
          </div>
        </div>

        <div className="text-left space-y-3 p-4 bg-sunken rounded-xl mb-6">
          <div className="flex justify-between text-[13.5px]">
            <span className="text-muted">Motivo</span>
            <span className="text-ink font-medium">{returnData.motivo}</span>
          </div>
          <div className="flex justify-between text-[13.5px]">
            <span className="text-muted">Consegna di origine</span>
            <span className="num text-ink font-medium">{returnData.deliveryId}</span>
          </div>
          {supplier && (
            <div className="flex justify-between text-[13.5px]">
              <span className="text-muted">Fornitore</span>
              <span className="text-ink">{supplier.name}</span>
            </div>
          )}
          {returnData.note && (
            <div className="flex justify-between text-[13.5px] gap-4">
              <span className="text-muted shrink-0">Note</span>
              <span className="text-ink text-right">{returnData.note}</span>
            </div>
          )}
        </div>

        <div className="flex gap-3 justify-center">
          <Btn variant="outline" size="lg" onClick={onBack}>Torna alla lista</Btn>
          <button onClick={onNew}
            className="h-16 px-6 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)] transition-all duration-fast ease-standard shadow-soft">
            <I.Return size={20}/>
            Nuovo reso
          </button>
        </div>
      </div>
    </div>
  );
};

// ─── Vista dettaglio reso (read-only) ───
const ResoDetail = ({ ret, lines, delivery, onBack }) => {
  const supplier = ret ? SUPPLIERS.find(s => s.id === ret.supplierId) : null;
  const store    = ret ? STORES.find(s => s.id === ret.storeId) : null;
  if (!ret) return null;

  return (
    <div className="px-7 py-6 max-w-[1400px]">
      <button onClick={onBack}
        className="text-[13px] text-muted hover:text-ink inline-flex items-center gap-1.5 mb-3 focus-ring rounded-md px-2 py-1 -ml-2">
        <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 resi
      </button>

      <div className="flex items-start justify-between gap-4 mb-5">
        <div>
          <div className="text-[11px] uppercase tracking-[0.08em] text-muted font-medium">Reso a fornitore</div>
          <div className="text-[22px] font-semibold tracking-tight text-ink mt-0.5">{ret.id}</div>
        </div>
        <Pill tone={RETURN_STATUS_TONE[ret.status] || 'neutral'}>{ret.status}</Pill>
      </div>

      <div className="grid grid-cols-2 gap-6 mb-6">
        <Card title="Dettagli reso">
          <div className="grid grid-cols-2 gap-4">
            <KeyVal label="Data reso"     value={ret.dateReso}/>
            <KeyVal label="Consegna rif." value={ret.deliveryId} mono/>
            <KeyVal label="Fornitore"     value={supplier?.name || ret.supplierId}/>
            <KeyVal label="Negozio"       value={store?.name || ret.storeId}/>
            <KeyVal label="Motivo"        value={ret.motivo}/>
            <KeyVal label="Totale"        value={fmtEur(ret.total)} mono/>
          </div>
          {ret.note && <div className="mt-4"><KeyVal label="Note" value={ret.note}/></div>}
        </Card>

        {delivery && (
          <Card title="Consegna di origine">
            <div className="grid grid-cols-2 gap-4">
              <KeyVal label="N° Consegna"    value={delivery.id} mono/>
              <KeyVal label="Data carico"    value={delivery.dateCarico}/>
              <KeyVal label="Doc. fornitore" value={delivery.numDocFornitore || '—'} mono/>
              <KeyVal label="Tipo"           value={delivery.contoVendita ? 'Conto vendita' : 'Acquisto'}/>
            </div>
            {delivery.contoVendita && (
              <div className="mt-4 p-2.5 rounded-md text-[12.5px]"
                style={{ background: 'var(--info-50)', color: 'var(--info-700)' }}>
                Consegna in conto vendita
              </div>
            )}
          </Card>
        )}
      </div>

      <Card title={`Righe rese — ${lines.length} prodotti`} padded={false}>
        <div className="grid grid-cols-[1fr_100px_144px_144px] gap-3 px-5 h-11 items-center text-[11px] uppercase tracking-[0.08em] text-muted font-medium hairline">
          <div>Prodotto</div>
          <div className="text-right">Q.tà resa</div>
          <div className="text-right">Prezzo unit.</div>
          <div className="text-right">Totale riga</div>
        </div>
        <div className="divide-y divide-line2">
          {lines.map((l, idx) => (
            <div key={idx} className="grid grid-cols-[1fr_100px_144px_144px] gap-3 px-5 items-center row-h">
              <div className="flex items-center gap-3 min-w-0">
                <div className="w-9 h-9 rounded-md stripe-ph shrink-0"/>
                <div className="min-w-0">
                  <div className="text-[13.5px] font-medium text-ink truncate">{l.name}</div>
                  <span className="num text-[11px] text-muted">{l.sku}</span>
                </div>
              </div>
              <div className="num text-[14px] text-ink text-right font-medium">{l.returnQty}</div>
              <div className="num text-[14px] text-muted text-right">{fmtEur(l.unitPrice)}</div>
              <div className="num text-[14px] font-semibold text-ink text-right">{fmtEur(l.returnQty * l.unitPrice)}</div>
            </div>
          ))}
        </div>
        <div className="px-5 py-4 border-t border-line flex justify-end items-center gap-6">
          <span className="text-[13px] text-muted">Totale reso</span>
          <span className="num text-[22px] font-semibold text-ink">{fmtEur(ret.total)}</span>
        </div>
      </Card>
    </div>
  );
};

// ══════════════════════════════════════════════════════════════════════
//  TOP-LEVEL WRAPPER
// ══════════════════════════════════════════════════════════════════════

const AcquistiView = ({ activeStoreId = STORE.id, session, onGoToCatalog }) => {
  const [tab, setTab]           = useStateAQ('ordini');

  // Ordini state
  const [orders, setOrders]     = useStateAQ(PURCHASE_ORDERS);
  const [allLines, setAllLines] = useStateAQ(PURCHASE_ORDER_LINES);
  const [view, setView]         = useStateAQ('list');
  const [selectedId, setSelectedId]   = useStateAQ(null);
  const [toast, setToast]             = useStateAQ(null);

  // Resi state
  const [returns, setReturns]                       = useStateAQ(SUPPLIER_RETURNS);
  const [returnLines, setReturnLines]               = useStateAQ(SUPPLIER_RETURN_LINES);
  const [returnView, setReturnView]                 = useStateAQ('list');
  const [returnSelectedId, setReturnSelectedId]     = useStateAQ(null);
  const [returnDeliveryId, setReturnDeliveryId]     = useStateAQ(null);
  const [returnConfermaData, setReturnConfermaData] = useStateAQ(null);
  const [returnToast, setReturnToast]               = useStateAQ(null);

  // Consegne state
  const [deliveries, setDeliveries]               = useStateAQ(DELIVERY_ORDERS);
  const [deliveryLines, setDeliveryLines]         = useStateAQ(DELIVERY_ORDER_LINES);
  const [deliveryView, setDeliveryView]           = useStateAQ('list');
  const [deliverySelectedId, setDeliverySelectedId] = useStateAQ(null);
  const [deliveryMode, setDeliveryMode]           = useStateAQ(null);
  const [deliveryFromOrderId, setDeliveryFromOrderId] = useStateAQ(null);
  const [deliveryConfermaData, setDeliveryConfermaData] = useStateAQ(null);
  const [deliveryToast, setDeliveryToast]         = useStateAQ(null);

  const inviatiOrders = useMemoAQ(() => orders.filter(o => o.status === 'Inviato'), [orders]);

  // ─── Ordini handlers ───
  const openOrder = (id) => {
    const o = orders.find(x => x.id === id);
    if (!o) return;
    setSelectedId(id);
    setView(o.status === 'Bozza' ? 'wizard' : 'detail');
  };

  const handleSave = (orderData, lines, id) => {
    if (window.__API__) window.__API__.mutate('/api/purchase-orders', { header: orderData, lines }).then(()=>{ if (window.__toast) window.__toast('Ordine fornitore salvato', 'success'); }).catch(()=>{});
    setOrders(prev => {
      const idx = prev.findIndex(o => o.id === id);
      return idx >= 0
        ? prev.map((o, i) => i === idx ? orderData : o)
        : [...prev, orderData];
    });
    setAllLines(prev => ({ ...prev, [id]: lines }));
    const msg = orderData.status === 'Inviato'
      ? `Ordine ${id} inviato al fornitore.`
      : `Bozza ${id} salvata.`;
    setView('list');
    setSelectedId(null);
    setToast(msg);
    setTimeout(() => setToast(null), 4000);
  };

  // ─── Consegne handlers ───
  const resetDeliveryNav = () => {
    setDeliveryView('list');
    setDeliverySelectedId(null);
    setDeliveryMode(null);
    setDeliveryFromOrderId(null);
    setDeliveryConfermaData(null);
  };

  const openDelivery = (id) => {
    const d = deliveries.find(x => x.id === id);
    if (!d) return;
    setDeliverySelectedId(id);
    setDeliveryMode(d.linkedOrderId ? 'from-order' : 'free');
    setDeliveryFromOrderId(d.linkedOrderId || null);
    setDeliveryView(d.status === 'Bozza' ? 'wizard' : 'detail');
  };

  const handleDeliverySave = (deliveryData, lines, id, conferma) => {
    if (window.__API__) window.__API__.mutate('/api/deliveries', { header: deliveryData, lines, conferma: !!conferma }).then(()=>{ if (window.__toast) window.__toast(conferma ? 'Consegna confermata · carico effettuato' : 'Bozza consegna salvata', 'success'); }).catch(()=>{});
    setDeliveries(prev => {
      const idx = prev.findIndex(d => d.id === id);
      return idx >= 0
        ? prev.map((d, i) => i === idx ? deliveryData : d)
        : [...prev, deliveryData];
    });
    setDeliveryLines(prev => ({ ...prev, [id]: lines }));
    if (conferma) {
      if (deliveryData.linkedOrderId) {
        setOrders(prev => prev.map(o =>
          o.id === deliveryData.linkedOrderId ? { ...o, status: 'Ricevuto' } : o
        ));
      }
      setDeliveryConfermaData({ delivery: deliveryData, lines });
      setDeliverySelectedId(null);
      setDeliveryView('conferma');
    } else {
      setDeliverySelectedId(null);
      setDeliveryView('list');
      setDeliveryToast(`Bozza ${id} salvata.`);
      setTimeout(() => setDeliveryToast(null), 4000);
    }
  };

  // ─── Resi handlers ───
  const resetReturnNav = () => {
    setReturnView('list');
    setReturnSelectedId(null);
    setReturnDeliveryId(null);
    setReturnConfermaData(null);
  };

  const openReturn = (id) => {
    const r = returns.find(x => x.id === id);
    if (!r) return;
    setReturnSelectedId(id);
    setReturnDeliveryId(r.deliveryId);
    setReturnView(r.status === 'Bozza' ? 'wizard' : 'detail');
  };

  const handleReturnSave = (returnData, rLines, id, conferma) => {
    if (window.__API__) window.__API__.mutate('/api/supplier-returns', { header: returnData, lines: rLines, conferma: !!conferma }).then(()=>{ if (window.__toast) window.__toast(conferma ? 'Reso a fornitore confermato' : 'Bozza reso salvata', 'success'); }).catch(()=>{});
    setReturns(prev => {
      const idx = prev.findIndex(r => r.id === id);
      return idx >= 0
        ? prev.map((r, i) => i === idx ? returnData : r)
        : [...prev, returnData];
    });
    setReturnLines(prev => ({ ...prev, [id]: rLines }));
    if (conferma) {
      setReturnConfermaData({ returnData, lines: rLines });
      setReturnSelectedId(null);
      setReturnDeliveryId(null);
      setReturnView('conferma');
    } else {
      setReturnSelectedId(null);
      setReturnDeliveryId(null);
      setReturnView('list');
      setReturnToast(`Bozza ${id} salvata.`);
      setTimeout(() => setReturnToast(null), 4000);
    }
  };

  const selectedReturn       = returnSelectedId ? returns.find(r => r.id === returnSelectedId) : null;
  const selectedReturnLines  = returnSelectedId ? (returnLines[returnSelectedId] || []) : [];
  const returnDelivery       = returnDeliveryId ? deliveries.find(d => d.id === returnDeliveryId) : null;
  const returnDeliveryLines  = returnDeliveryId ? (deliveryLines[returnDeliveryId] || []) : [];

  const selectedOrder         = selectedId ? orders.find(o => o.id === selectedId) : null;
  const selectedLines         = selectedId ? (allLines[selectedId] || []) : [];
  const selectedDelivery      = deliverySelectedId ? deliveries.find(d => d.id === deliverySelectedId) : null;
  const selectedDeliveryLines = deliverySelectedId ? (deliveryLines[deliverySelectedId] || []) : [];
  const deliveryFromOrder     = deliveryFromOrderId ? orders.find(o => o.id === deliveryFromOrderId) : null;
  const deliveryFromOrderLines = deliveryFromOrderId ? (allLines[deliveryFromOrderId] || null) : null;
  const storeName             = STORES.find(s => s.id === activeStoreId)?.name || STORE.name;

  const onTabChange = (t) => {
    setTab(t);
    setView('list');
    setSelectedId(null);
    resetDeliveryNav();
    resetReturnNav();
  };

  return (
    <>
      <Topbar eyebrow={storeName} title="Acquisti"/>
      <AcqTabs tab={tab} onTab={onTabChange}/>

      {/* ── Ordini ── */}
      {tab === 'ordini' && (
        view === 'list'   ? <OrdiniList orders={orders} onNew={() => { setSelectedId(null); setView('wizard'); }} onOpen={openOrder}/> :
        view === 'detail' ? <OrdineDetail order={selectedOrder} lines={selectedLines} onBack={() => setView('list')}/> :
        view === 'wizard' ? <OrdineWizard existing={selectedOrder} initialLines={selectedLines} onSave={handleSave} onCancel={() => { setView('list'); setSelectedId(null); }}/> :
        null
      )}

      {/* ── Consegne ── */}
      {tab === 'consegne' && (
        deliveryView === 'list' ? (
          <ConsegneList deliveries={deliveries} onNew={() => setDeliveryView('new-select')} onOpen={openDelivery}/>
        ) : deliveryView === 'new-select' ? (
          <ConsegnaNewSelect
            inviatiOrders={inviatiOrders}
            onSelectMode={(mode) => {
              setDeliveryMode(mode);
              if (mode === 'from-order') setDeliveryView('order-pick');
              else { setDeliveryFromOrderId(null); setDeliveryView('wizard'); }
            }}
            onCancel={resetDeliveryNav}
          />
        ) : deliveryView === 'order-pick' ? (
          <ConsegnaOrderPicker
            orders={inviatiOrders}
            onPick={(orderId) => { setDeliveryFromOrderId(orderId); setDeliveryView('wizard'); }}
            onCancel={() => setDeliveryView('new-select')}
          />
        ) : deliveryView === 'wizard' ? (
          <ConsegnaWizard
            existing={selectedDelivery && selectedDelivery.status === 'Bozza' ? selectedDelivery : null}
            existingLines={selectedDelivery ? selectedDeliveryLines : []}
            fromOrderId={deliveryFromOrderId}
            fromOrder={deliveryFromOrder}
            fromOrderLines={deliveryFromOrderLines}
            mode={deliveryMode}
            session={session}
            onSave={handleDeliverySave}
            onCancel={resetDeliveryNav}
          />
        ) : deliveryView === 'detail' ? (
          <ConsegnaDetail
            delivery={selectedDelivery}
            lines={selectedDeliveryLines}
            linkedOrder={selectedDelivery?.linkedOrderId ? orders.find(o => o.id === selectedDelivery.linkedOrderId) : null}
            onBack={resetDeliveryNav}
          />
        ) : deliveryView === 'conferma' && deliveryConfermaData ? (
          <ConsegnaConfermaView
            delivery={deliveryConfermaData.delivery}
            lines={deliveryConfermaData.lines}
            linkedOrder={deliveryConfermaData.delivery.linkedOrderId
              ? orders.find(o => o.id === deliveryConfermaData.delivery.linkedOrderId)
              : null}
            onBack={() => { resetDeliveryNav(); }}
            onCatalog={() => { resetDeliveryNav(); onGoToCatalog && onGoToCatalog(); }}
          />
        ) : null
      )}

      {/* ── Resi ── */}
      {tab === 'resi' && (
        returnView === 'list' ? (
          <ResiList returns={returns} returnLines={returnLines} deliveries={deliveries} onNew={() => setReturnView('picker')} onOpen={openReturn}/>
        ) : returnView === 'picker' ? (
          <ResoPicker
            deliveries={deliveries.filter(d => d.status === 'Confermata')}
            returns={returns} returnLines={returnLines}
            onPick={(deliveryId) => { setReturnDeliveryId(deliveryId); setReturnView('wizard'); }}
            onCancel={resetReturnNav}
          />
        ) : returnView === 'wizard' ? (
          <ResoWizard
            delivery={returnDelivery} deliveryLines={returnDeliveryLines}
            returns={returns} returnLines={returnLines}
            existing={selectedReturn?.status === 'Bozza' ? selectedReturn : null}
            existingLines={selectedReturn ? selectedReturnLines : []}
            session={session}
            onSave={handleReturnSave} onCancel={resetReturnNav}
          />
        ) : returnView === 'detail' ? (
          <ResoDetail ret={selectedReturn} lines={selectedReturnLines} delivery={returnDelivery} onBack={resetReturnNav}/>
        ) : returnView === 'conferma' && returnConfermaData ? (
          <ResoConfermaView
            returnData={returnConfermaData.returnData}
            lines={returnConfermaData.lines}
            delivery={deliveries.find(d => d.id === returnConfermaData.returnData.deliveryId)}
            onBack={resetReturnNav}
            onNew={() => { resetReturnNav(); setReturnView('picker'); }}
          />
        ) : null
      )}

      {/* Toast */}
      {(toast || deliveryToast || returnToast) && (
        <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">{toast || deliveryToast || returnToast}</span>
        </div>
      )}
    </>
  );
};

Object.assign(window, { AcquistiView });
