/* ============================================================
   NOLEGGI IN CORSO — vista catalogo / tabella switcher
   ============================================================ */

function daysUntil(d) {
  if (!d) return null;
  const date = d instanceof Date ? d : new Date(d);
  return Math.ceil((date - new Date()) / (1000*60*60*24));
}

// Badge colorato per i giorni al rientro
function RientroBadge({ data, size }) {
  if (!data) return <span style={{ fontSize:12, color:'var(--ink-4)', fontWeight:600 }}>—</span>;
  const dl = daysUntil(data);
  const isSm = size === 'sm';
  let color, bg, label;
  if (dl < 0)       { color = 'var(--red)'; bg = 'var(--red-tint)';     label = `rientrato da ${-dl} gg`; }
  else if (dl === 0){ color = 'var(--red)'; bg = 'var(--red-tint)';     label = 'rientra oggi'; }
  else if (dl <= 7) { color = 'var(--st-prenotato)'; bg = '#fdf0e0';    label = `tra ${dl} gg`; }
  else              { color = 'var(--st-disponibile)'; bg = '#e8f6f0';  label = `tra ${dl} gg`; }
  return (
    <span style={{ display:'inline-flex', alignItems:'center', gap:5, padding: isSm?'3px 9px':'5px 11px', borderRadius:99,
      background: bg, color: color, fontWeight:700, fontSize: isSm?11.5:12.5 }}>
      <span style={{ width:6, height:6, borderRadius:99, background: color }} />
      {fmtDate(data)} · {label}
    </span>
  );
}

/* ---- Card per vista catalogo ----------------------------- */
function NoleggioCard({ n, role, products, onEditData, onView, nProroghe = 0 }) {
  const product = (products||[]).find(p => p.id === n.prodId);
  if (!product) return null;
  const cat = CATEGORIE.find(c => c.id === product.cat);
  const keyAttrs = Object.entries(product.attr).slice(0,3);
  return (
    <div style={{ background:'var(--surface)', border:'1px solid var(--line)', borderRadius:'var(--r-lg)', overflow:'hidden',
      display:'flex', flexDirection:'column', boxShadow:'var(--sh-1)' }}>
      <div style={{ position:'relative' }}>
        <ProductImage productId={product.id} placeholder="Nessuna foto"
          style={{ width:'100%', height:'158px', display:'block' }} />
        <div style={{ position:'absolute', top:11, left:11, display:'flex', gap:6 }}>
          <span style={{ display:'inline-flex', alignItems:'center', gap:6, padding:'4px 10px', borderRadius:99,
            background:'var(--st-noleggiato, #6c5ce7)', color:'#fff', fontSize:11.5, fontWeight:800, letterSpacing:'.03em' }}>
            <Icon name="clock" size={13} stroke={2.4} /> NOLEGGIATO
          </span>
          {nProroghe > 0 && (
            <span style={{ display:'inline-flex', alignItems:'center', gap:5, padding:'4px 9px', borderRadius:99,
              background:'var(--red)', color:'#fff', fontSize:11.5, fontWeight:800 }}>
              <Icon name="refresh" size={11} />{nProroghe}
            </span>
          )}
        </div>
        <div style={{ position:'absolute', top:11, right:11, background:'rgba(255,255,255,.92)', padding:'4px 9px', borderRadius:99,
          fontSize:11, fontWeight:800, fontFamily:'var(--font-display)', color:'var(--ink-2)', backdropFilter:'blur(4px)' }}>
          {product.matricola || '—'}
        </div>
      </div>
      <div style={{ padding:'15px 17px', display:'flex', flexDirection:'column', flex:1, gap:11 }}>
        <div>
          <div style={{ display:'flex', alignItems:'center', gap:7, marginBottom:5 }}>
            <Icon name={cat?.icon || 'boxes'} size={15} style={{ color:'var(--ink-4)' }} />
            <span style={{ fontSize:11.5, fontWeight:700, color:'var(--ink-3)', textTransform:'uppercase', letterSpacing:'.03em' }}>{cat?.nome}</span>
          </div>
          <h3 style={{ margin:0, fontSize:16.5, fontWeight:800, letterSpacing:'-.01em' }}>{product.marca} {product.modello}</h3>
        </div>

        <div style={{ background:'var(--surface-2)', borderRadius:'var(--r-md)', padding:'10px 12px' }}>
          <div style={{ fontSize:11.5, color:'var(--ink-4)', fontWeight:700, textTransform:'uppercase', letterSpacing:'.03em', marginBottom:3 }}>Cliente</div>
          <div style={{ fontSize:13.5, fontWeight:700, color:'var(--ink)', whiteSpace:'nowrap', overflow:'hidden', textOverflow:'ellipsis' }}>{n.cliente}</div>
          <div style={{ fontSize:12, color:'var(--ink-3)', marginTop:2 }}>{n.commerciale} · {n.tipo}</div>
        </div>

        <div style={{ display:'flex', flexDirection:'column', gap:5 }}>
          <span style={{ fontSize:11.5, fontWeight:700, color:'var(--ink-4)', textTransform:'uppercase', letterSpacing:'.03em' }}>Rientro previsto</span>
          <RientroBadge data={n.dataRientro} />
        </div>

        <div style={{ marginTop:'auto', paddingTop:11, borderTop:'1px solid var(--line-2)', display:'flex', gap:7 }}>
          <Btn size="sm" variant="ghost" icon="calendar" full onClick={()=>onEditData(n)}>Modifica rientro</Btn>
          <button onClick={()=>onView(n)} title="Dettagli archivio" style={{ width:36, height:36, borderRadius:9, flexShrink:0,
            border:'1.5px solid var(--line)', display:'flex', alignItems:'center', justifyContent:'center', color:'var(--ink-2)' }}>
            <Icon name="arrowRight" size={17} />
          </button>
        </div>
      </div>
    </div>
  );
}

/* ---- Tabella per vista list ------------------------------ */
function NoleggioTable({ list, products, role, onEditData, onView, extensionsByArchive }) {
  const G = 'minmax(0,1.6fr) minmax(0,1.3fr) minmax(0,1.1fr) minmax(0,1.2fr) 90px 200px 92px';
  return (
    <div style={{ background:'var(--surface)', border:'1px solid var(--line)', borderRadius:'var(--r-lg)', overflow:'hidden', boxShadow:'var(--sh-1)' }}>
      <div className="scroll" style={{ overflowX:'auto' }}>
      <div style={{ minWidth:1010 }}>
        <div style={{ display:'grid', gridTemplateColumns:G, gap:14, padding:'13px 22px', borderBottom:'1px solid var(--line)',
          background:'var(--surface-2)', fontSize:11.5, fontWeight:800, color:'var(--ink-3)', textTransform:'uppercase', letterSpacing:'.04em', alignItems:'center' }}>
          <span>Mezzo</span><span>Cliente</span><span>Matricola</span><span>Commerciale</span><span style={{ textAlign:'center' }}>Proroghe</span><span>Rientro previsto</span><span style={{ textAlign:'right' }}>Azioni</span>
        </div>
        {list.length === 0 ? (
          <div style={{ padding:'60px 0', textAlign:'center', color:'var(--ink-3)', fontSize:14.5, fontWeight:600 }}>Nessun noleggio in corso</div>
        ) : list.map((n,i) => {
          const product = (products||[]).find(p => p.id === n.prodId);
          const cat = product && CATEGORIE.find(c => c.id === product.cat);
          const nProroghe = (extensionsByArchive && extensionsByArchive[n.id]) ? extensionsByArchive[n.id].length : 0;
          return (
            <div key={n.id} style={{ display:'grid', gridTemplateColumns:G, gap:14, padding:'13px 22px',
              borderBottom: i<list.length-1?'1px solid var(--line-2)':'none', alignItems:'center' }}>
              <div style={{ display:'flex', alignItems:'center', gap:10, minWidth:0 }}>
                <span style={{ width:32, height:32, borderRadius:7, flexShrink:0, background:'var(--line-2)', color:'var(--ink-4)', display:'flex', alignItems:'center', justifyContent:'center' }}>
                  <Icon name={cat?.icon || 'boxes'} size={17} stroke={1.6} />
                </span>
                <div style={{ minWidth:0 }}>
                  <div style={{ fontSize:13.5, fontWeight:700, whiteSpace:'nowrap', overflow:'hidden', textOverflow:'ellipsis' }}>
                    {product ? prodLabel(product) : n.prodLabel}
                  </div>
                  <div style={{ fontSize:11.5, color:'var(--ink-4)', fontWeight:600 }}>{n.tipo}</div>
                </div>
              </div>
              <span style={{ fontSize:13, fontWeight:600, color:'var(--ink-2)', whiteSpace:'nowrap', overflow:'hidden', textOverflow:'ellipsis' }}>{n.cliente}</span>
              <span style={{ fontFamily:'var(--font-display)', fontSize:13, fontWeight:800, color:'var(--ink-2)' }}>{product?.matricola || n.prodId}</span>
              <span style={{ fontSize:13, fontWeight:600, color:'var(--ink-2)', whiteSpace:'nowrap', overflow:'hidden', textOverflow:'ellipsis' }}>{n.commerciale}</span>
              <div style={{ textAlign:'center' }}>
                {nProroghe > 0 ? (
                  <span style={{ display:'inline-flex', alignItems:'center', gap:5, padding:'3px 9px', borderRadius:99, fontSize:12, fontWeight:800,
                    background:'var(--red-tint)', color:'var(--red)' }}>
                    <Icon name="refresh" size={11} />{nProroghe}
                  </span>
                ) : <span style={{ color:'var(--ink-4)', fontSize:13 }}>—</span>}
              </div>
              <div><RientroBadge data={n.dataRientro} size="sm" /></div>
              <div style={{ display:'flex', gap:6, justifySelf:'end' }}>
                <button onClick={()=>onEditData(n)} title="Modifica data rientro" style={{ width:34, height:34, borderRadius:8, border:'1.5px solid var(--line)', color:'var(--ink-3)', display:'flex', alignItems:'center', justifyContent:'center' }}
                  onMouseEnter={e=>{ e.currentTarget.style.color='var(--red)'; e.currentTarget.style.borderColor='var(--red-tint-2)'; }}
                  onMouseLeave={e=>{ e.currentTarget.style.color='var(--ink-3)'; e.currentTarget.style.borderColor='var(--line)'; }}>
                  <Icon name="calendar" size={16} />
                </button>
                <button onClick={()=>onView(n)} title="Apri scheda noleggio" style={{ width:34, height:34, borderRadius:8, border:'1.5px solid var(--line)', color:'var(--ink-3)', display:'flex', alignItems:'center', justifyContent:'center' }}
                  onMouseEnter={e=>{ e.currentTarget.style.color='var(--red)'; e.currentTarget.style.borderColor='var(--red-tint-2)'; }}
                  onMouseLeave={e=>{ e.currentTarget.style.color='var(--ink-3)'; e.currentTarget.style.borderColor='var(--line)'; }}>
                  <Icon name="arrowRight" size={16} />
                </button>
              </div>
            </div>
          );
        })}
      </div>
      </div>
    </div>
  );
}

/* ---- Vista principale Noleggi in corso ------------------- */
function NoleggiInCorso({ role, archive, setArchive, products, setProducts, attributi, toast, onOpenBooking, rentalExtensions }) {
  const vp = useViewport();
  // Default: catalogo per commerciale, tabella per backoffice/admin. Su mobile sempre catalog.
  const defaultView = vp.isMobile ? 'catalog' : (role === 'commerciale' ? 'catalog' : 'table');
  const [viewMode, setViewMode] = useState(defaultView);
  const [q, setQ] = useState('');
  const [tipo, setTipo] = useState('all');
  const [commFilter, setCommFilter] = useState('all');
  const [cat, setCat] = useState('all');
  const [rientroDa, setRientroDa] = useState('');
  const [rientroA, setRientroA] = useState('');
  const [editingDate, setEditingDate] = useState(null);

  // Estrai i noleggi attivi dall'archivio (esito confermata + tipo STR/LTR + non rientrati)
  const noleggi = (archive || [])
    .filter(b => b.esito === 'confermata' && (b.tipo === 'STR' || b.tipo === 'LTR') && !b.rientrato && !b.interrotto)
    .map(b => ({
      ...b,
      dataRientro: b.dataRientro || b.data_rientro || b.fine,
      dataConsegna: b.dataConsegna || b.data_consegna || b.inizio,
    }));

  // Raggruppa proroghe per archive_id
  const extensionsByArchive = {};
  (rentalExtensions || []).forEach(e => {
    if (!extensionsByArchive[e.archive_id]) extensionsByArchive[e.archive_id] = [];
    extensionsByArchive[e.archive_id].push(e);
  });

  const commerciali = [...new Set(noleggi.map(n => n.commerciale))].sort();

  let list = noleggi.slice();
  if (tipo !== 'all') list = list.filter(n => n.tipo === tipo);
  if (commFilter !== 'all') list = list.filter(n => n.commerciale === commFilter);
  if (cat !== 'all') {
    list = list.filter(n => {
      const p = products.find(x => x.id === n.prodId);
      return p && p.cat === cat;
    });
  }
  if (rientroDa) { const d = new Date(rientroDa); list = list.filter(n => new Date(n.dataRientro) >= d); }
  if (rientroA)  { const d = new Date(rientroA); d.setHours(23,59,59); list = list.filter(n => new Date(n.dataRientro) <= d); }
  if (q.trim()) {
    const s = q.toLowerCase();
    list = list.filter(n => (n.cliente + ' ' + n.prodLabel + ' ' + n.id).toLowerCase().includes(s));
  }
  list.sort((a,b) => new Date(a.dataRientro) - new Date(b.dataRientro));

  const counts = {
    all: noleggi.length,
    STR: noleggi.filter(n => n.tipo === 'STR').length,
    LTR: noleggi.filter(n => n.tipo === 'LTR').length,
    settimana: noleggi.filter(n => { const dl = daysUntil(n.dataRientro); return dl !== null && dl <= 7 && dl >= 0; }).length,
  };

  const saveNewDate = async (newDate) => {
    if (!editingDate) return;
    const oldDate = editingDate.dataRientro;
    if (window.SF_CONFIG.useSupabase) {
      try {
        await window.DataAPI.update('bookings_archive', editingDate.id, { data_rientro: newDate });
      } catch(e) { console.error(e); toast('Errore aggiornamento data'); return; }
    }
    setArchive(prev => prev.map(b => b.id === editingDate.id ? { ...b, dataRientro: new Date(newDate), data_rientro: newDate, fine: new Date(newDate) } : b));
    window.LogAPI?.logEvent('rental.return_date_changed', {
      entity_type: 'booking', entity_id: editingDate.id,
      title: 'Data rientro modificata',
      description: `${editingDate.prodLabel} → ${editingDate.cliente} · nuovo rientro ${new Date(newDate).toLocaleDateString('it-IT')}`,
      metadata: {
        commerciale_nome: editingDate.commerciale,
        cliente: editingDate.cliente,
        prod_label: editingDate.prodLabel,
        old_date: oldDate ? new Date(oldDate).toISOString() : null,
        new_date: newDate,
      },
    });
    setEditingDate(null);
    toast('Data di rientro aggiornata');
  };

  const handleView = (n) => {
    if (onOpenBooking) onOpenBooking(n);
    else toast(`Apri archivio per ${n.cliente}`);
  };

  const selStyle = { appearance:'none', padding:'9px 32px 9px 13px', fontSize:13, fontWeight:600, borderRadius:'var(--r-md)', border:'1.5px solid var(--line)', background:'var(--surface)', color:'var(--ink-2)', cursor:'pointer' };
  const cats = [{id:'all',nome:'Tutte',icon:'grid'}, ...CATEGORIE];
  const seeAllComm = role === 'admin' || role === 'backoffice';

  return (
    <div className="scroll" style={{ flex:1, minWidth:0, overflowY:'auto', overflowX:'hidden', display:'flex', flexDirection:'column' }}>
      {/* Toolbar sticky */}
      <div style={{ padding: vp.isMobile?'12px 12px 10px':'18px 30px 14px', borderBottom:'1px solid var(--line)', background:'var(--surface)', position:'sticky', top:0, zIndex:10 }}>
        {/* Tabs tipo + switcher view */}
        <div style={{ display:'flex', alignItems:'center', justifyContent:'space-between', gap:10, flexWrap:'wrap', marginBottom:10 }}>
          <div className={vp.isMobile?'scroll-x':''} style={{ display:'flex', gap:8,
            flexWrap: vp.isMobile?'nowrap':'wrap',
            margin: vp.isMobile?'0 -12px':'0',
            padding: vp.isMobile?'0 12px 4px':'0',
            width: vp.isMobile?'calc(100% + 24px)':'auto' }}>
            {[['all','Tutti'],['STR','Noleggio breve'],['LTR','Noleggio lungo'],['settimana','Rientro in 7 gg']].map(([k,l])=>{
              const active = k==='settimana' ? false : tipo===k;
              const isWeek = k==='settimana';
              const handle = () => {
                if (isWeek) {
                  const today = new Date();
                  const in7 = new Date(); in7.setDate(today.getDate()+7);
                  setRientroDa(today.toISOString().slice(0,10));
                  setRientroA(in7.toISOString().slice(0,10));
                  setTipo('all');
                } else setTipo(k);
              };
              const shortLbl = vp.isMobile ? (k==='STR'?'STR':k==='LTR'?'LTR':k==='settimana'?'7 gg':l) : l;
              return (
                <button key={k} onClick={handle} style={{ display:'flex', alignItems:'center', gap:7, padding: vp.isMobile?'8px 12px':'9px 15px', borderRadius:99, fontSize: vp.isMobile?12.5:13.5, fontWeight:700, flexShrink:0,
                  border:'1.5px solid '+(active?'var(--ink)':'var(--line)'), background: active?'var(--ink)':'var(--surface)', color: active?'var(--surface)':'var(--ink-2)' }}>
                  {shortLbl}
                  <span style={{ fontSize:11, fontWeight:800, padding:'1px 6px', borderRadius:99,
                    background: active?'rgba(255,255,255,.22)':'var(--line-2)', color: active?'#fff':'var(--ink-3)' }}>{counts[k]}</span>
                </button>
              );
            })}
          </div>
          {/* Switcher view: nascosto su mobile */}
          {!vp.isMobile && (
            <div style={{ display:'flex', gap:0, padding:3, borderRadius:'var(--r-md)', background:'var(--line-2)' }}>
              <button onClick={()=>setViewMode('catalog')} title="Vista catalogo" style={{
                display:'flex', alignItems:'center', gap:6, padding:'7px 12px', borderRadius:7, fontSize:13, fontWeight:700,
                background: viewMode==='catalog'?'#fff':'transparent', color: viewMode==='catalog'?'var(--red)':'var(--ink-3)',
                boxShadow: viewMode==='catalog'?'var(--sh-1)':'none', transition:'.14s' }}>
                <Icon name="grid" size={16} /> Catalogo
              </button>
              <button onClick={()=>setViewMode('table')} title="Vista tabella" style={{
                display:'flex', alignItems:'center', gap:6, padding:'7px 12px', borderRadius:7, fontSize:13, fontWeight:700,
                background: viewMode==='table'?'#fff':'transparent', color: viewMode==='table'?'var(--red)':'var(--ink-3)',
                boxShadow: viewMode==='table'?'var(--sh-1)':'none', transition:'.14s' }}>
                <Icon name="log" size={16} /> Tabella
              </button>
            </div>
          )}
        </div>

        {/* Filtri categoria (solo in vista catalogo) */}
        {viewMode === 'catalog' && (
          <div className={vp.isMobile?'scroll-x':''} style={{ display:'flex', gap:8,
            flexWrap: vp.isMobile?'nowrap':'wrap', marginBottom:10,
            margin: vp.isMobile?'0 -12px 10px':'0 0 11px',
            padding: vp.isMobile?'0 12px 4px':'0',
            width: vp.isMobile?'calc(100% + 24px)':'auto' }}>
            {cats.map(c => {
              const active = cat===c.id;
              return (
                <button key={c.id} onClick={()=>setCat(c.id)}
                  style={{ display:'flex', alignItems:'center', gap:7, padding: vp.isMobile?'7px 12px':'8px 13px', borderRadius:99,
                    fontSize: vp.isMobile?12:13, fontWeight:700, flexShrink:0,
                    border:'1.5px solid '+(active?'var(--red)':'var(--line)'), background: active?'var(--red)':'var(--surface)', color: active?'#fff':'var(--ink-2)', transition:'.14s' }}>
                  <Icon name={c.icon} size={vp.isMobile?13:15} /> {c.nome}
                </button>
              );
            })}
          </div>
        )}

        {/* Search + filtri secondari */}
        <div style={{ display:'flex', alignItems:'center', gap:8, flexWrap:'wrap' }}>
          {!vp.isMobile && (
            <div style={{ position:'relative', flex:'1 1 220px', maxWidth:320 }}>
              <Icon name="search" size={18} style={{ position:'absolute', left:13, top:'50%', transform:'translateY(-50%)', color:'var(--ink-4)' }} />
              <input value={q} onChange={e=>setQ(e.target.value)} placeholder="Cerca cliente, mezzo, matricola…"
                style={{ width:'100%', padding:'10px 14px 10px 40px', fontSize:13.5, borderRadius:'var(--r-md)', border:'1.5px solid var(--line)', background:'var(--surface-2)', outline:'none' }}
                onFocus={e=>e.target.style.borderColor='var(--red)'} onBlur={e=>e.target.style.borderColor='var(--line)'} />
            </div>
          )}
          {seeAllComm && (
            <div style={{ position:'relative', flex: vp.isMobile?1:'none' }}>
              <select value={commFilter} onChange={e=>setCommFilter(e.target.value)} style={{...selStyle, width: vp.isMobile?'100%':'auto'}}>
                <option value="all">Tutti i commerciali</option>
                {commerciali.map(c=><option key={c} value={c}>{c}</option>)}
              </select>
              <Icon name="chevDown" size={15} style={{ position:'absolute', right:11, top:'50%', transform:'translateY(-50%)', color:'var(--ink-3)', pointerEvents:'none' }} />
            </div>
          )}
          {viewMode === 'table' && !vp.isMobile && (
            <div style={{ position:'relative' }}>
              <select value={cat} onChange={e=>setCat(e.target.value)} style={selStyle}>
                <option value="all">Tutte le categorie</option>
                {CATEGORIE.map(c=><option key={c.id} value={c.id}>{c.nome}</option>)}
              </select>
              <Icon name="chevDown" size={15} style={{ position:'absolute', right:11, top:'50%', transform:'translateY(-50%)', color:'var(--ink-3)', pointerEvents:'none' }} />
            </div>
          )}
          {!vp.isMobile && (
            <div style={{ display:'flex', alignItems:'center', gap:7, padding:'5px 12px', border:'1.5px solid var(--line)', borderRadius:'var(--r-md)', background:'var(--surface)' }}>
              <Icon name="calendar" size={15} style={{ color:'var(--ink-3)' }} />
              <span style={{ fontSize:12, fontWeight:700, color:'var(--ink-4)' }}>Rientro dal</span>
              <input type="date" value={rientroDa} onChange={e=>setRientroDa(e.target.value)} style={{ border:'none', outline:'none', background:'transparent', fontSize:13, fontWeight:600, color:'var(--ink-2)' }} />
              <span style={{ fontSize:12, fontWeight:700, color:'var(--ink-4)' }}>al</span>
              <input type="date" value={rientroA} onChange={e=>setRientroA(e.target.value)} style={{ border:'none', outline:'none', background:'transparent', fontSize:13, fontWeight:600, color:'var(--ink-2)' }} />
              {(rientroDa||rientroA) && <button onClick={()=>{ setRientroDa(''); setRientroA(''); }} title="Azzera" style={{ display:'flex', color:'var(--red)' }}><Icon name="x" size={14} /></button>}
            </div>
          )}
          {!vp.isMobile && <span style={{ marginLeft:'auto', fontSize:13, color:'var(--ink-3)', fontWeight:600, whiteSpace:'nowrap' }}>{list.length} in corso</span>}
        </div>
      </div>

      {/* Contenuto */}
      <div style={{ padding: vp.isMobile?'14px 12px 30px':'22px 30px 40px' }}>
        {viewMode === 'catalog' ? (
          list.length === 0 ? (
            <div style={{ textAlign:'center', padding:'80px 0', color:'var(--ink-3)' }}>
              <Icon name="clock" size={36} style={{ margin:'0 auto 12px', opacity:.5 }} />
              <div style={{ fontSize:15, fontWeight:600 }}>Nessun noleggio in corso</div>
            </div>
          ) : (
            <div style={{ display:'grid',
              gridTemplateColumns: vp.isMobile ? '1fr' : 'repeat(auto-fill, minmax(290px, 1fr))',
              gap: vp.isMobile?14:20 }}>
              {list.map(n => <NoleggioCard key={n.id} n={n} role={role} products={products} onEditData={setEditingDate} onView={handleView} nProroghe={(extensionsByArchive[n.id]||[]).length} />)}
            </div>
          )
        ) : (
          <NoleggioTable list={list} products={products} role={role} onEditData={setEditingDate} onView={handleView} extensionsByArchive={extensionsByArchive} />
        )}
      </div>

      {/* Modal modifica data rientro */}
      {editingDate && (
        <DatePickerModal
          title="Modifica data di rientro"
          subtitle={`${editingDate.cliente} · ${editingDate.prodLabel}`}
          currentDate={editingDate.dataRientro}
          minDate={editingDate.dataConsegna}
          onClose={()=>setEditingDate(null)}
          onSave={saveNewDate}
        />
      )}
    </div>
  );
}

Object.assign(window, { NoleggiInCorso, NoleggioCard, NoleggioTable, RientroBadge, daysUntil });