/* ============================================================
   PRENOTAZIONI — lista + modale prenotazione + modale PDF
   ============================================================ */

const BK_STATI = {
  attiva:      { label:'Attiva',      color:'var(--st-disponibile)', bg:'#e8f6f0' },
  in_scadenza: { label:'In scadenza', color:'var(--st-prenotato)',   bg:'#fdf0e0' },
  scaduta:     { label:'Scaduta',     color:'var(--red)',            bg:'var(--red-tint)' },
};

function daysLeft(d){ return Math.ceil((d - new Date())/(1000*60*60*24)); }
const BK_GRID = 'minmax(0,1.5fr) minmax(0,1.15fr) 92px 130px 116px 250px';

function Prenotazioni({ role, currentUser, users, bookings, onPrenota, onView, onEdit, onAction, canFree, toast }) {
  const vp = useViewport();
  const [stato, setStato] = useState('all');
  const [commFilter, setCommFilter] = useState('all');
  const [q, setQ] = useState('');
  const [sortDir, setSortDir] = useState('asc');
  const items = bookings || PRENOTAZIONI;

  const myName = currentUser ? currentUser.nome : null;
  const commerciali = [...new Set(items.map(b=>b.commerciale))].sort();

  const counts = {
    all: items.length,
    attiva: items.filter(b=>b.stato==='attiva').length,
    in_scadenza: items.filter(b=>b.stato==='in_scadenza').length,
    scaduta: items.filter(b=>b.stato==='scaduta').length,
  };

  let list = items.slice();
  if (stato!=='all') list = list.filter(b=>b.stato===stato);
  if (commFilter!=='all') list = list.filter(b=>b.commerciale===commFilter);
  if (q.trim()) { const s=q.toLowerCase(); list = list.filter(b => (b.cliente+' '+b.prodLabel+' '+b.id).toLowerCase().includes(s)); }
  list.sort((a,b)=> sortDir==='asc' ? a.fine-b.fine : b.fine-a.fine);

  const act = (b, action) => onAction(b, action);
  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' };

  return (
    <div className="scroll" style={{ flex:1, minWidth:0, overflowY:'auto', overflowX:'hidden', display:'flex', flexDirection:'column' }}>
      <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 }}>
        <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','Tutte'],['attiva','Attive'],['in_scadenza','In scadenza'],['scaduta','Scadute']].map(([k,l])=>(
              <button key={k} onClick={()=>setStato(k)} style={{ display:'flex', alignItems:'center', gap:7,
                padding: vp.isMobile?'8px 12px':'9px 15px', borderRadius:99, flexShrink:0,
                fontSize: vp.isMobile?12.5:13.5, fontWeight:700, border:'1.5px solid '+(stato===k?'var(--ink)':'var(--line)'),
                background: stato===k?'var(--ink)':'var(--surface)', color: stato===k?'var(--surface)':'var(--ink-2)' }}>
                {l}
                <span style={{ fontSize:11, fontWeight:800, padding:'1px 6px', borderRadius:99,
                  background: stato===k?'rgba(255,255,255,.22)':'var(--line-2)', color: stato===k?'#fff':'var(--ink-3)' }}>{counts[k]}</span>
              </button>
            ))}
          </div>
          {!vp.isMobile && <Btn icon="plus" onClick={()=>onPrenota(null)}>Nuova prenotazione</Btn>}
        </div>
        <div style={{ display:'flex', alignItems:'center', gap:8, flexWrap:'wrap' }}>
          {!vp.isMobile && (
            <div style={{ position:'relative', flex:'1 1 240px', maxWidth:360 }}>
              <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 o codice…"
                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>
          )}
          <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>
          {!vp.isMobile && (
            <button onClick={()=>setSortDir(d=>d==='asc'?'desc':'asc')} title="Ordina per scadenza"
              style={{ display:'flex', alignItems:'center', gap:7, padding:'9px 14px', fontSize:13, fontWeight:700, borderRadius:'var(--r-md)', border:'1.5px solid var(--line)', background:'var(--surface)', color:'var(--ink-2)' }}>
              <Icon name="clock" size={16} /> Scadenza
              <Icon name={sortDir==='asc'?'arrowUp':'arrowRight'} size={15} style={{ transform: sortDir==='asc'?'none':'rotate(90deg)', color:'var(--red)' }} />
            </button>
          )}
          {role==='commerciale' && !vp.isMobile && (
            <span style={{ display:'inline-flex', alignItems:'center', gap:7, fontSize:12, fontWeight:600, color:'var(--ink-3)', background:'var(--line-2)', padding:'7px 12px', borderRadius:99, whiteSpace:'nowrap' }}>
              <Icon name="lock" size={13} /> Liberi solo le tue
            </span>
          )}
          {!vp.isMobile && <span style={{ marginLeft:'auto', fontSize:13, color:'var(--ink-3)', fontWeight:600, whiteSpace:'nowrap' }}>{list.length} prenotazioni</span>}
        </div>
      </div>

      {vp.isMobile ? (
        /* MOBILE: card list + FAB "Nuova prenotazione" */
        <div style={{ padding:'12px 12px 90px', display:'flex', flexDirection:'column', gap:10 }}>
          {list.length === 0 ? (
            <div style={{ padding:'60px 20px', textAlign:'center', color:'var(--ink-3)', fontSize:14, fontWeight:600 }}>
              Nessuna prenotazione trovata
            </div>
          ) : list.map(b => {
            const dl = daysLeft(b.fine);
            return (
              <button key={b.id} onClick={()=>onView(b)}
                style={{ textAlign:'left', background:'var(--surface)', border:'1px solid var(--line)', borderRadius:'var(--r-lg)',
                  padding:'14px 15px', display:'flex', flexDirection:'column', gap:8, boxShadow:'var(--sh-1)' }}>
                <div style={{ display:'flex', alignItems:'flex-start', justifyContent:'space-between', gap:10 }}>
                  <div style={{ minWidth:0, flex:1 }}>
                    <div style={{ fontSize:14, fontWeight:800, whiteSpace:'nowrap', overflow:'hidden', textOverflow:'ellipsis' }}>{b.cliente}</div>
                    <div style={{ fontSize:12.5, color:'var(--ink-3)', marginTop:1, whiteSpace:'nowrap', overflow:'hidden', textOverflow:'ellipsis' }}>{b.prodLabel}</div>
                  </div>
                  <span style={{ display:'inline-flex', alignItems:'center', gap:5, padding:'4px 9px', borderRadius:99,
                    background:BK_STATI[b.stato].bg, color:BK_STATI[b.stato].color, fontWeight:700, fontSize:11.5, flexShrink:0 }}>
                    <span style={{ width:5, height:5, borderRadius:99, background:BK_STATI[b.stato].color }} />
                    {BK_STATI[b.stato].label}
                  </span>
                </div>
                <div style={{ display:'flex', alignItems:'center', justifyContent:'space-between', gap:8, fontSize:12 }}>
                  <div style={{ display:'flex', alignItems:'center', gap:6, color:'var(--ink-3)', fontWeight:600, minWidth:0 }}>
                    <Avatar name={b.commerciale} size={20} color="var(--role-commerciale)" />
                    <span style={{ whiteSpace:'nowrap', overflow:'hidden', textOverflow:'ellipsis' }}>{b.commerciale}</span>
                  </div>
                  <div style={{ fontWeight:700, color: dl<0?'var(--red)':dl<=2?'var(--st-prenotato)':'var(--ink-3)', whiteSpace:'nowrap' }}>
                    {fmtDate(b.fine)} · {dl<0 ? `${-dl}gg fa` : dl===0 ? 'oggi' : `${dl}gg`}
                    {(b.proroghe||0)>0 && <span title={`Prorogata ${b.proroghe}x`} style={{ marginLeft:5, color:'var(--st-prenotato)' }}>×{b.proroghe}</span>}
                  </div>
                </div>
              </button>
            );
          })}

          {/* FAB Nuova prenotazione */}
          <button onClick={()=>onPrenota(null)}
            style={{ position:'fixed', right:16, bottom:'calc(90px + env(safe-area-inset-bottom, 0))', zIndex:20,
              width:56, height:56, borderRadius:'50%', background:'var(--red)', color:'#fff',
              boxShadow:'0 8px 22px -6px rgba(200,16,46,.55)',
              display:'flex', alignItems:'center', justifyContent:'center' }}>
            <Icon name="plus" size={22} stroke={2.2} />
          </button>
        </div>
      ) : (
        <div style={{ padding:'20px 30px 40px' }}>
        <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:900 }}>
        <div style={{ display:'grid', gridTemplateColumns:BK_GRID, 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>Cliente / Mezzo</span><span>Commerciale</span><span>Tipo</span>
          <button onClick={()=>setSortDir(d=>d==='asc'?'desc':'asc')} style={{ display:'flex', alignItems:'center', gap:5, fontSize:11.5, fontWeight:800, color:'var(--ink-3)', textTransform:'uppercase', letterSpacing:'.04em' }}>
            Scadenza <Icon name="chevDown" size={13} style={{ transform: sortDir==='asc'?'none':'rotate(180deg)' }} />
          </button>
          <span>Stato</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 }}>Nessuna prenotazione trovata</div>
        ) : list.map(b => {
          const dl = daysLeft(b.fine);
          const mine = b.commerciale===myName;
          const freeable = canFree(b);
          const machineBookedByOther = items.some(x=>x.id!==b.id && x.prodId===b.prodId && x.stato==='attiva' && x.commerciale!==b.commerciale);
          return (
            <div key={b.id} style={{ display:'grid', gridTemplateColumns:BK_GRID, gap:14, padding:'15px 22px',
              borderBottom:'1px solid var(--line-2)', alignItems:'center' }}>
              <div style={{ minWidth:0 }}>
                <div style={{ fontSize:14, fontWeight:700, whiteSpace:'nowrap', overflow:'hidden', textOverflow:'ellipsis' }}>{b.cliente}</div>
                <div style={{ fontSize:12.5, color:'var(--ink-3)', marginTop:1, whiteSpace:'nowrap', overflow:'hidden', textOverflow:'ellipsis' }}>{b.prodLabel} · <span style={{ fontFamily:'var(--font-display)', fontWeight:700 }}>{b.id}</span></div>
              </div>
              <div style={{ display:'flex', alignItems:'center', gap:9, minWidth:0 }}>
                <Avatar name={b.commerciale} size={28} color="var(--role-commerciale)" />
                <span style={{ fontSize:13, fontWeight:600, whiteSpace:'nowrap', overflow:'hidden', textOverflow:'ellipsis' }}>
                  {b.commerciale}{mine && role==='commerciale' && <span style={{ color:'var(--role-commerciale)', fontWeight:700 }}> · tu</span>}
                </span>
              </div>
              <span style={{ fontSize:12.5, fontWeight:700, color:'var(--ink-2)', background:'var(--line-2)', padding:'4px 10px', borderRadius:7, justifySelf:'start', whiteSpace:'nowrap' }}>{b.tipo}</span>
              <div>
                <div style={{ fontSize:13, fontWeight:600 }}>{fmtDate(b.fine)}</div>
                <div style={{ fontSize:11.5, color: dl<0?'var(--red)':dl<=2?'var(--st-prenotato)':'var(--ink-4)', fontWeight:700 }}>
                  {dl<0 ? `scaduta da ${-dl} gg` : dl===0 ? 'scade oggi' : `tra ${dl} gg`}
                  {(b.proroghe||0)>0 && <span title={`Prorogata ${b.proroghe} ${b.proroghe===1?'volta':'volte'}`} style={{ marginLeft:6, display:'inline-flex', alignItems:'center', gap:3, color:'var(--st-prenotato)', verticalAlign:'middle' }}><Icon name="refresh" size={11} style={{ display:'inline' }} />×{b.proroghe}</span>}
                </div>
              </div>
              <span style={{ display:'inline-flex', alignItems:'center', gap:6, padding:'5px 11px', borderRadius:99, justifySelf:'start',
                background:BK_STATI[b.stato].bg, color:BK_STATI[b.stato].color, fontWeight:700, fontSize:12.5 }}>
                <span style={{ width:6, height:6, borderRadius:99, background:BK_STATI[b.stato].color }} />{BK_STATI[b.stato].label}
              </span>
              <div style={{ display:'flex', gap:6, justifySelf:'end', alignItems:'center' }}>
                <button onClick={()=>onView(b)} title="Visualizza dettagli" 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="eye" size={16} />
                </button>
                <button onClick={()=>onEdit(b)} title="Modifica" 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="edit" size={15} />
                </button>
                {b.stato==='in_scadenza' && <Btn size="sm" variant="subtle" onClick={()=>act(b,'proroga')}>Proroga</Btn>}
                {b.stato==='scaduta' && !machineBookedByOther && <Btn size="sm" variant="subtle" onClick={()=>act(b,'riprenota')}>Riprenota</Btn>}
                <Btn size="sm" onClick={()=>act(b,'conferma')}>Conferma</Btn>
                {freeable ? (
                  <button onClick={()=>act(b,'libera')} title="Libera il mezzo" 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="unlock" size={16} />
                  </button>
                ) : (
                  <span title="Prenotazione di un altro commerciale — non puoi liberarla" style={{ width:34, height:34, borderRadius:8, border:'1.5px dashed var(--line)', color:'var(--ink-4)', display:'flex', alignItems:'center', justifyContent:'center' }}>
                    <Icon name="lock" size={15} />
                  </span>
                )}
              </div>
            </div>
          );
        })}
        </div>
        </div>
      </div>

      <div style={{ marginTop:16, display:'flex', alignItems:'center', gap:10, fontSize:13, color:'var(--ink-3)', padding:'0 4px' }}>
        <Icon name="clock" size={16} /> Le prenotazioni hanno <b style={{ color:'var(--ink-2)' }}>&nbsp;scadenza automatica a 2 settimane</b>. Alla scadenza puoi confermare, prorogare o liberare il mezzo.
      </div>
      </div>
      )}
    </div>
  );
}

/* ---- Booking modal ---------------------------------------- */
function Field({ label, required, children }) {
  return (
    <label style={{ display:'block' }}>
      <span style={{ display:'block', fontSize:12.5, fontWeight:700, color:'var(--ink-2)', marginBottom:6 }}>
        {label}{required && <span style={{ color:'var(--red)' }}> *</span>}
      </span>
      {children}
    </label>
  );
}
const inputStyle = { width:'100%', padding:'11px 13px', fontSize:14, borderRadius:'var(--r-md)', border:'1.5px solid var(--line)', background:'var(--surface-2)', outline:'none' };

/* ---- Cliente search component ----------------------------- */
function ClienteSearchField({ clienti, selectedCliente, onSelect, onCreateNew, zone, clienteCat }) {
  const [search, setSearch] = useState(selectedCliente?.ragione_sociale || '');
  const [results, setResults] = useState([]);
  const [showResults, setShowResults] = useState(false);
  const [searching, setSearching] = useState(false);
  const searchTimer = useRef(null);

  useEffect(() => {
    if (selectedCliente) setSearch(selectedCliente.ragione_sociale);
  }, [selectedCliente?.id]);

  const handleChange = (val) => {
    setSearch(val);
    if (selectedCliente && val !== selectedCliente.ragione_sociale) {
      onSelect(null);
    }
    if (!val.trim() || val.trim().length < 2) {
      setResults([]);
      setShowResults(false);
      return;
    }
    setShowResults(true);
    setSearching(true);
    // Ricerca su TUTTO il database (non solo le prime 1000 righe in memoria), debounced
    if (searchTimer.current) clearTimeout(searchTimer.current);
    searchTimer.current = setTimeout(async () => {
      try {
        const found = window.DataAPI.searchClienti
          ? await window.DataAPI.searchClienti(val)
          : fuzzySearchClienti(clienti, val);
        setResults(found);
      } catch (e) {
        console.error('searchClienti (booking)', e);
        setResults(fuzzySearchClienti(clienti, val)); // fallback locale
      } finally {
        setSearching(false);
      }
    }, 280);
  };

  const selectResult = (c) => {
    onSelect(c);
    setSearch(c.ragione_sociale);
    setShowResults(false);
  };

  const clearSelection = () => {
    onSelect(null);
    setSearch('');
    setResults([]);
    setShowResults(false);
  };

  const showCreateBtn = search.trim().length >= 2 && !selectedCliente;

  return (
    <div style={{ position:'relative' }}>
      <div style={{ position:'relative' }}>
        <Icon name="search" size={17} style={{ position:'absolute', left:13, top:'50%', transform:'translateY(-50%)', color: selectedCliente?'var(--st-disponibile)':'var(--ink-4)' }} />
        <input value={search} onChange={e=>handleChange(e.target.value)}
          onFocus={()=>search.length >= 2 && setShowResults(true)}
          placeholder="Cerca cliente…"
          style={{ ...inputStyle, paddingLeft:40, paddingRight: selectedCliente?40:13,
            borderColor: selectedCliente?'var(--st-disponibile)':'var(--line)' }} />
        {selectedCliente && (
          <button onClick={clearSelection} title="Deseleziona"
            style={{ position:'absolute', right:8, top:'50%', transform:'translateY(-50%)', padding:6, color:'var(--ink-3)' }}>
            <Icon name="x" size={16} />
          </button>
        )}
      </div>

      {/* Risultati + bottone crea nuovo SOTTO i risultati */}
      {showResults && !selectedCliente && (
        <div style={{ position:'absolute', top:'100%', left:0, right:0, marginTop:5, zIndex:10,
          background:'var(--surface)', border:'1.5px solid var(--line)', borderRadius:'var(--r-md)',
          boxShadow:'var(--sh-2)', maxHeight:340, overflowY:'auto' }}>
          {searching && results.length===0 && (
            <div style={{ padding:'12px 14px', fontSize:13, color:'var(--ink-3)', fontWeight:600 }}>Ricerca in corso…</div>
          )}
          {results.map(c => {
            const zona = zone.find(z=>z.id===c.zona_id);
            const cat = clienteCat.find(cc=>cc.id===c.client_category_id);
            return (
              <button key={c.id} onClick={()=>selectResult(c)}
                style={{ width:'100%', textAlign:'left', padding:'10px 14px',
                  borderBottom:'1px solid var(--line-2)', display:'flex', flexDirection:'column', gap:2, background:'var(--surface)' }}
                onMouseEnter={e=>e.currentTarget.style.background='var(--surface-2)'}
                onMouseLeave={e=>e.currentTarget.style.background='var(--surface)'}>
                <span style={{ fontSize:14, fontWeight:700 }}>{c.ragione_sociale}</span>
                <span style={{ fontSize:12, color:'var(--ink-3)' }}>
                  {zona ? zona.nome : '—'} · {cat ? cat.nome : '—'}
                </span>
              </button>
            );
          })}
          {/* Crea nuovo cliente — sempre alla fine */}
          {showCreateBtn && (
            <button onClick={()=>onCreateNew(search.trim())}
              style={{ width:'100%', padding:'12px 14px', display:'flex', alignItems:'center', justifyContent:'center', gap:8,
                background:'var(--red-tint)', color:'var(--red)', fontSize:13.5, fontWeight:700,
                borderTop: results.length>0 ? '1px solid var(--line-2)' : 'none' }}
              onMouseEnter={e=>e.currentTarget.style.background='color-mix(in srgb, var(--red) 18%, var(--surface))'}
              onMouseLeave={e=>e.currentTarget.style.background='var(--red-tint)'}>
              <Icon name="plus" size={16} /> Crea nuovo cliente "{search.trim()}"
            </button>
          )}
        </div>
      )}
    </div>
  );
}

function BookingModal({ product, booking, role, currentUser, users, products, zone, listino, clienteCat, coeff, clienti, setClienti, onClose, onSave, toast }) {
  const isEdit = !!booking;
  const today = new Date().toISOString().slice(0,10);
  const in14 = daysFromNow(14).toISOString().slice(0,10);
  const toISO = (d)=> (d instanceof Date ? d : new Date(d)).toISOString().slice(0,10);

  const allProducts = (products||PRODOTTI);
  const [prodId, setProdId] = useState(booking?.prodId || product?.id || '');

  const initialCliente = booking?.cliente_id
    ? (clienti||[]).find(c => c.id === booking.cliente_id)
    : null;
  const [selectedCliente, setSelectedCliente] = useState(initialCliente);
  const [clienteText, setClienteText] = useState(booking?.cliente || '');

  const [tipo, setTipo] = useState(booking?.tipo || 'Vendita');
  const [inizio, setInizio] = useState(booking?booking.inizio?toISO(booking.inizio):today : today);
  const [fine, setFine] = useState(booking?booking.fine?toISO(booking.fine):in14 : in14);
  const [note, setNote] = useState(booking?.note || '');
  const [prob, setProb] = useState(booking?.prob ?? 60);
  const [zonaId, setZonaId] = useState(booking?.zonaId || '');
  const [catId, setCatId] = useState(booking?.catClienteId || '');
  const [batteria, setBatteria] = useState(booking?.batteria || false);
  const [showCreateModal, setShowCreateModal] = useState(false);
  const [createPrefillName, setCreatePrefillName] = useState('');

  // Checkbox "aggiorna anagrafica"
  const [updateAnagrafica, setUpdateAnagrafica] = useState(false);

  // Snapshot zona/categoria del cliente al momento della selezione — per rilevare modifiche
  const clienteSnapshotRef = useRef({ zonaId: '', catId: '' });

  useEffect(() => {
    if (selectedCliente) {
      setClienteText(selectedCliente.ragione_sociale);
      const z = selectedCliente.zona_id || '';
      const c = selectedCliente.client_category_id || '';
      setZonaId(z);
      setCatId(c);
      clienteSnapshotRef.current = { zonaId: z, catId: c };
      setUpdateAnagrafica(false);
    } else {
      clienteSnapshotRef.current = { zonaId: '', catId: '' };
      setUpdateAnagrafica(false);
    }
  }, [selectedCliente?.id]);

  // Quando l'utente cambia zona o categoria a mano e c'è un cliente selezionato → mostra checkbox
  const zonaModificata = selectedCliente && zonaId !== clienteSnapshotRef.current.zonaId;
  const catModificata = selectedCliente && catId !== clienteSnapshotRef.current.catId;
  const showUpdateCheckbox = selectedCliente && (zonaModificata || catModificata);

  // Se la checkbox era spuntata ma poi torno ai valori originali → la nascondo e deseleziono
  useEffect(() => {
    if (!showUpdateCheckbox && updateAnagrafica) setUpdateAnagrafica(false);
  }, [showUpdateCheckbox]);

  const handleSelectCliente = (c) => {
    setSelectedCliente(c);
    if (c) setClienteText(c.ragione_sociale);
  };

  const handleCreateNew = (name) => {
    setCreatePrefillName(name);
    setShowCreateModal(true);
  };

  const handleSaveNewCliente = async (c) => {
    if (window.SF_CONFIG.useSupabase) {
      try {
        const row = await window.DataAPI.insert('clienti', {
          ragione_sociale: c.ragione_sociale,
          zona_id: c.zona_id || null,
          client_category_id: c.client_category_id || null,
        });
        c = { ...c, id: row.id, ragione_sociale_norm: row.ragione_sociale_norm };
      } catch(e) { toast('Errore creazione cliente'); console.error(e); return; }
    }
    setClienti(prev => [...prev, c]);
    setSelectedCliente(c);
    setClienteText(c.ragione_sociale);
    setShowCreateModal(false);
    toast('Cliente aggiunto in anagrafica');
    window.LogAPI?.logEvent('client.created', {
      entity_type: 'client', entity_id: c.id,
      title: 'Nuovo cliente in anagrafica',
      description: `${c.ragione_sociale} · creato durante prenotazione`,
      metadata: { ragione_sociale: c.ragione_sociale, zona_id: c.zona_id, client_category_id: c.client_category_id },
    });
  };

  const defaultComm = booking?.commerciale || (currentUser ? currentUser.nome : (role==='admin'?'Omar Menabue':role==='backoffice'?'Sara Ferrari':'Marco Bianchi'));
  const [commerciale, setCommerciale] = useState(defaultComm);
  const canPickComm = role==='admin' || role==='backoffice';
  const commOptions = (()=>{ const names = (users||[]).map(u=>u.nome); if(!names.includes(defaultComm)) names.unshift(defaultComm); return [...new Set(names)]; })();
  const user = canPickComm ? commerciale : defaultComm;
  const zonaList = (zone||[]).slice().sort((a,b)=>a.nome.localeCompare(b.nome));
  const prod = allProducts.find(p=>p.id===prodId) || null;
  const bt = prod ? (window.battFromProduct ? window.battFromProduct(prod.attr) : parseBatt(prod.attr && prod.attr['Batteria'])) : null;
  const battPrice = (bt && (listino||LISTINO_BATTERIE_INIT)[battKey(bt.volt, bt.amp)]) || null;
  const battSr = bt && (battPrice===SR || battPrice==null);
  const isVendita = tipo==='Vendita';

  const econ = prod ? computeBooking({
    booking:{ tipo, zonaId, batteria, catClienteId:catId }, product:prod, zone, listino, clienteCat, coeff
  }) : null;

  const submit = async () => {
    if(!prodId){ toast('Seleziona una macchina'); return; }
    const finalCliente = selectedCliente?.ragione_sociale || clienteText.trim();
    if(!finalCliente){ toast('Inserisci o seleziona il cliente'); return; }

    // Se richiesto, aggiorna anagrafica cliente con la zona/categoria modificate
    if (updateAnagrafica && selectedCliente) {
      const patch = {};
      if (zonaModificata) patch.zona_id = zonaId || null;
      if (catModificata) patch.client_category_id = catId || null;
      if (Object.keys(patch).length > 0) {
        if (window.SF_CONFIG.useSupabase) {
          try { await window.DataAPI.update('clienti', selectedCliente.id, patch); }
          catch(e) { console.error('Errore update anagrafica', e); toast('Errore aggiornamento anagrafica'); }
        }
        const updated = { ...selectedCliente, ...patch };
        setClienti(prev => prev.map(c => c.id===updated.id ? updated : c));
        toast('Anagrafica cliente aggiornata');
        const changed = [zonaModificata && 'zona', catModificata && 'categoria'].filter(Boolean).join(' + ');
        window.LogAPI?.logEvent('client.updated', {
          entity_type: 'client', entity_id: selectedCliente.id,
          title: 'Cliente modificato',
          description: `${selectedCliente.ragione_sociale} · aggiornato ${changed} da prenotazione`,
          metadata: { ragione_sociale: selectedCliente.ragione_sociale, changed_fields: changed, ...patch },
        });
      }
    }

    const data = {
      id: booking?.id || ('PR-'+Math.floor(1000+Math.random()*9000)),
      prodId, prodLabel: prod ? prodLabel(prod) : '',
      cliente: finalCliente,
      cliente_id: selectedCliente?.id || null,
      commerciale: user, tipo,
      inizio: new Date(inizio), fine: new Date(fine), note: note.trim(), prob,
      stato: booking?.stato || 'attiva', zonaId, batteria, catClienteId: catId,
    };
    onSave(data, isEdit);
  };

  const fieldGap = { display:'grid', gridTemplateColumns:'1fr 1fr', gap:14 };

  return (
    <>
    <ModalShell onClose={onClose} width={580} title={isEdit?'Modifica prenotazione':'Nuova prenotazione'} subtitle={isEdit?booking.id:'Seleziona macchina, cliente e periodo'}>
      <div style={{ marginBottom:18 }}>
        <Field label="Macchina" required>
          {product && !isEdit ? (
            <div style={{ display:'flex', alignItems:'center', gap:13, padding:'12px 14px', background:'var(--surface-2)', borderRadius:'var(--r-md)' }}>
              <span style={{ width:42, height:42, borderRadius:9, background:'var(--red-tint)', color:'var(--red)', display:'flex', alignItems:'center', justifyContent:'center' }}>
                <Icon name={CAT_ICON[product.cat]} size={22} />
              </span>
              <div style={{ flex:1 }}>
                <div style={{ fontSize:14, fontWeight:700 }}>{prodLabel(product)}</div>
                <div style={{ fontSize:12, color:'var(--ink-3)' }}>Matricola {product.matricola || '—'} · {product.posizione}</div>
              </div>
              <StatoBadge stato={product.stato} size="sm" />
            </div>
          ) : (
            <div style={{ position:'relative' }}>
              <select value={prodId} onChange={e=>setProdId(e.target.value)} style={{ ...inputStyle, appearance:'none', paddingRight:34 }}>
                <option value="">— Seleziona macchina —</option>
                {allProducts.filter(p=>p.stato!=='ARCHIVIATO').map(p=>(
                  <option key={p.id} value={p.id}>{prodSlug(p)}</option>
                ))}
              </select>
              <Icon name="chevDown" size={16} style={{ position:'absolute', right:12, top:'50%', transform:'translateY(-50%)', color:'var(--ink-3)', pointerEvents:'none' }} />
            </div>
          )}
        </Field>
      </div>

      <div style={fieldGap}>
        <div style={{ gridColumn:'1 / -1' }}>
          <Field label="Cliente" required>
            <ClienteSearchField
              clienti={clienti||[]}
              selectedCliente={selectedCliente}
              onSelect={handleSelectCliente}
              onCreateNew={handleCreateNew}
              zone={zone}
              clienteCat={clienteCat}
            />
          </Field>
        </div>
        <Field label="Commerciale">
          {canPickComm ? (
            <div style={{ position:'relative' }}>
              <select value={commerciale} onChange={e=>setCommerciale(e.target.value)} style={{ ...inputStyle, appearance:'none', paddingRight:34 }}>
                {commOptions.map(n=><option key={n} value={n}>{n}</option>)}
              </select>
              <Icon name="chevDown" size={16} style={{ position:'absolute', right:12, top:'50%', transform:'translateY(-50%)', color:'var(--ink-3)', pointerEvents:'none' }} />
            </div>
          ) : (
          <div style={{ display:'flex', alignItems:'center', gap:9, padding:'9px 12px', background:'var(--line-2)', borderRadius:'var(--r-md)' }}>
            <Avatar name={user} size={26} color={RUOLI[role].color} />
            <span style={{ fontSize:13.5, fontWeight:600 }}>{user}</span>
          </div>
          )}
        </Field>
        <Field label="Tipo esigenza" required>
          <select value={tipo} onChange={e=>setTipo(e.target.value)} style={{ ...inputStyle, appearance:'none' }}>
            {['Vendita','STR','LTR','Prova'].map(t=><option key={t}>{t}</option>)}
          </select>
        </Field>
        <Field label={tipo==='Vendita'?'Data':'Data inizio'} required>
          <input type="date" value={inizio} onChange={e=>setInizio(e.target.value)} style={inputStyle} />
        </Field>
        {tipo!=='Vendita' && (
        <Field label="Data fine" required>
          <input type="date" value={fine} onChange={e=>setFine(e.target.value)} style={inputStyle} />
        </Field>
        )}
        <div style={{ gridColumn:'1 / -1' }}>
          <Field label="Categoria cliente">
            <div style={{ position:'relative' }}>
              <select value={catId} onChange={e=>setCatId(e.target.value)} style={{ ...inputStyle, appearance:'none', paddingRight:34 }}>
                <option value="">— Seleziona categoria —</option>
                {(clienteCat||[]).map(c=><option key={c.id} value={c.id}>{c.nome} (usura {c.usura}%)</option>)}
              </select>
              <Icon name="chevDown" size={16} style={{ position:'absolute', right:12, top:'50%', transform:'translateY(-50%)', color:'var(--ink-3)', pointerEvents:'none' }} />
            </div>
          </Field>
        </div>
        <div style={{ gridColumn:'1 / -1' }}>
          <Field label="Zona di consegna">
            <div style={{ position:'relative' }}>
              <select value={zonaId} onChange={e=>setZonaId(e.target.value)} style={{ ...inputStyle, appearance:'none', paddingRight:34 }}>
                <option value="">— Seleziona zona / ritiro in sede —</option>
                {zonaList.map(z=><option key={z.id} value={z.id}>{z.nome} — {z.tariffa===SR?'Su richiesta':fmtEur(z.tariffa)}{z.km!=null?` (${z.km} km)`:''}</option>)}
              </select>
              <Icon name="chevDown" size={16} style={{ position:'absolute', right:12, top:'50%', transform:'translateY(-50%)', color:'var(--ink-3)', pointerEvents:'none' }} />
            </div>
          </Field>
        </div>

        {/* Checkbox aggiorna anagrafica — appare solo se c'è un cliente selezionato e si modifica zona/categoria a mano */}
        {showUpdateCheckbox && (
          <div style={{ gridColumn:'1 / -1' }}>
            <label onClick={()=>setUpdateAnagrafica(v=>!v)} style={{
              display:'flex', alignItems:'center', gap:10, padding:'11px 13px',
              borderRadius:'var(--r-md)', cursor:'pointer',
              border:'1.5px solid '+(updateAnagrafica?'var(--st-prenotato)':'var(--line)'),
              background: updateAnagrafica?'#fdf0e0':'var(--surface-2)',
              transition:'.13s'
            }}>
              <span style={{ width:18, height:18, borderRadius:5, flexShrink:0,
                border:'1.5px solid '+(updateAnagrafica?'var(--st-prenotato)':'var(--line)'),
                background: updateAnagrafica?'var(--st-prenotato)':'#fff',
                display:'flex', alignItems:'center', justifyContent:'center' }}>
                {updateAnagrafica && <Icon name="check" size={13} stroke={3} style={{ color:'#fff' }} />}
              </span>
              <span style={{ fontSize:13.5, fontWeight:700, color: updateAnagrafica?'#9a5800':'var(--ink-2)' }}>
                Aggiorna informazioni per questo cliente
              </span>
              <span style={{ marginLeft:'auto', fontSize:11.5, color:'var(--ink-4)', fontWeight:600 }}>
                {zonaModificata && catModificata ? 'zona + categoria' : zonaModificata ? 'zona' : 'categoria'}
              </span>
            </label>
          </div>
        )}

        {isVendita && bt && !battSr && (
          <div style={{ gridColumn:'1 / -1' }}>
            <label style={{ display:'flex', alignItems:'center', justifyContent:'space-between', padding:'11px 14px', border:'1.5px solid '+(batteria?'var(--red)':'var(--line)'), background:batteria?'var(--red-tint)':'var(--surface-2)', borderRadius:'var(--r-md)', cursor:'pointer' }} onClick={()=>setBatteria(b=>!b)}>
              <span style={{ display:'flex', alignItems:'center', gap:9, fontSize:13.5, fontWeight:600, color:batteria?'var(--red)':'var(--ink-2)' }}>
                <Icon name="battery" size={17} /> Includi batteria nuova (+{fmtEur(battPrice)})
              </span>
              <span style={{ width:42, height:24, borderRadius:99, background:batteria?'var(--red)':'var(--line)', position:'relative', transition:'.2s', flexShrink:0 }}>
                <span style={{ position:'absolute', top:3, left:batteria?21:3, width:18, height:18, borderRadius:99, background:'#fff', transition:'.2s' }} />
              </span>
            </label>
          </div>
        )}
        <div style={{ gridColumn:'1 / -1' }}>
          <Field label={`Probabilità di chiusura — ${prob}%`}>
            <input type="range" min="0" max="100" step="5" value={prob} onChange={e=>setProb(+e.target.value)} style={{ width:'100%', accentColor:'var(--red)' }} />
          </Field>
        </div>
        <div style={{ gridColumn:'1 / -1' }}>
          <Field label="Note">
            <textarea value={note} onChange={e=>setNote(e.target.value)} rows={2} placeholder="Facoltativo" style={{ ...inputStyle, resize:'vertical' }} />
          </Field>
        </div>
      </div>

      {econ && (
        <div style={{ marginTop:18, border:'1px solid var(--line)', borderRadius:'var(--r-md)', overflow:'hidden' }}>
          {econ.kind==='vendita' ? (
            <>
              <div style={{ display:'flex', justifyContent:'space-between', padding:'11px 15px', fontSize:13.5 }}>
                <span style={{ color:'var(--ink-2)', fontWeight:600 }}>Prezzo di listino (IVA escl.)</span>
                <span style={{ fontWeight:700 }}>{fmtEur(econ.listinoPrice)}</span>
              </div>
              {econ.withBatt && <div style={{ display:'flex', justifyContent:'space-between', padding:'11px 15px', fontSize:13.5, borderTop:'1px solid var(--line-2)' }}>
                <span style={{ color:'var(--ink-2)', fontWeight:600, display:'flex', alignItems:'center', gap:7 }}><Icon name="battery" size={15} style={{ color:'var(--red)' }} /> Batteria nuova</span>
                <span style={{ fontWeight:700 }}>{fmtEur(econ.battCost)}</span>
              </div>}
              <div style={{ display:'flex', justifyContent:'space-between', padding:'11px 15px', fontSize:13.5, borderTop:'1px solid var(--line-2)' }}>
                <span style={{ color:'var(--ink-2)', fontWeight:600, display:'flex', alignItems:'center', gap:7 }}><Icon name="pin" size={15} style={{ color:'var(--red)' }} /> Trasporto {econ.zona?`— ${econ.zona.nome}`:''}</span>
                <span style={{ fontWeight:700, color:econ.zona?'var(--ink)':'var(--ink-4)' }}>{econ.zona?(econ.trasportoSr?'Su richiesta':fmtEur(econ.trasporto)):'—'}</span>
              </div>
              <div style={{ display:'flex', justifyContent:'space-between', alignItems:'baseline', padding:'13px 15px', background:'var(--red-tint)', borderTop:'1px solid var(--line)' }}>
                <span style={{ fontWeight:800, color:'var(--red)' }}>Totale stimato</span>
                <span style={{ fontFamily:'var(--font-display)', fontSize:21, fontWeight:800, color:'var(--red)' }}>{fmtEur(econ.totaleConTrasporto)}</span>
              </div>
            </>
          ) : (
            <>
              <div style={{ display:'flex', justifyContent:'space-between', padding:'11px 15px', fontSize:13.5 }}>
                <span style={{ color:'var(--ink-2)', fontWeight:600 }}>Tariffa base (g / mese)</span>
                <span style={{ fontWeight:700 }}>{fmtEur(econ.baseGiorno)}/g · {fmtEur(econ.baseMese)}/m</span>
              </div>
              <div style={{ display:'flex', justifyContent:'space-between', padding:'11px 15px', fontSize:13.5, borderTop:'1px solid var(--line-2)' }}>
                <span style={{ color:'var(--ink-2)', fontWeight:600 }}>Maggiorazione usura{econ.cat?` (${econ.cat.nome})`:''}</span>
                <span style={{ fontWeight:700, color: econ.magg.aumento>0?'var(--red)':'var(--ink-3)' }}>{pct(econ.magg.aumento)}</span>
              </div>
              <div style={{ display:'flex', justifyContent:'space-between', alignItems:'baseline', padding:'13px 15px', background:'var(--red-tint)', borderTop:'1px solid var(--line)' }}>
                <span style={{ fontWeight:800, color:'var(--red)' }}>Tariffa finale</span>
                <span style={{ fontFamily:'var(--font-display)', fontSize:19, fontWeight:800, color:'var(--red)' }}>{fmtEur(econ.giornoFin)}/g · {fmtEur(econ.meseFin)}/m</span>
              </div>
            </>
          )}
        </div>
      )}

      <div style={{ display:'flex', alignItems:'center', gap:9, marginTop:16, padding:'10px 13px', background:'#fdf0e0', borderRadius:'var(--r-md)', fontSize:12.5, color:'#9a5800', fontWeight:600 }}>
        <Icon name="clock" size={16} /> Scadenza automatica fra 2 settimane. Riceverai un promemoria 24h prima.
      </div>
      <div style={{ display:'flex', gap:12, marginTop:22 }}>
        <Btn variant="ghost" full onClick={onClose}>Annulla</Btn>
        <Btn full icon="check" onClick={submit}>{isEdit?'Salva modifiche':'Conferma prenotazione'}</Btn>
      </div>
    </ModalShell>

    {showCreateModal && (
      <ClienteEditModal cliente={null} zone={zone} clienteCat={clienteCat}
        prefillName={createPrefillName}
        onClose={()=>setShowCreateModal(false)}
        onSave={handleSaveNewCliente} />
    )}
    </>
  );
}

function ModalShell({ onClose, width=520, title, subtitle, children, dark }) {
  const vp = useViewport();
  const isMobile = vp.isMobile;
  return (
    <div className="no-print" style={{ position:'fixed', inset:0, zIndex:100, display:'flex',
      alignItems: isMobile?'flex-end':'center', justifyContent:'center',
      padding: isMobile?0:24,
      background:'rgba(15,17,21,.5)', backdropFilter:'blur(3px)', animation:'fadeIn .15s ease' }} onClick={onClose}>
      <div onClick={e=>e.stopPropagation()} className={"scroll" + (isMobile?' modal-mobile':'')} style={{
        width:'100%', maxWidth: isMobile?'100%':width,
        maxHeight: isMobile?'92vh':'90vh', overflowY:'auto', overflowX:'hidden',
        background:'var(--surface)',
        borderRadius: isMobile?'18px 18px 0 0':'var(--r-xl)',
        boxShadow:'var(--sh-3)',
        animation: (isMobile?'bsSlideUp':'scaleIn') + ' .2s cubic-bezier(.2,.7,.3,1)' }}>
        {isMobile && <div style={{ width:38, height:4, background:'var(--line)', borderRadius:99, margin:'10px auto 0', flexShrink:0 }} />}
        <div style={{ padding: isMobile?'12px 18px 14px':'22px 26px 18px', borderBottom:'1px solid var(--line)', display:'flex', alignItems:'flex-start', justifyContent:'space-between', gap:14, position:'sticky', top:0, background:'var(--surface)', zIndex:1 }}>
          <div style={{ minWidth:0, flex:1 }}>
            <h2 style={{ margin:0, fontFamily:'var(--font-display)', fontSize: isMobile?17:20, fontWeight:800, letterSpacing:'-.01em' }}>{title}</h2>
            {subtitle && <div style={{ fontSize: isMobile?12:13, color:'var(--ink-3)', marginTop:3, whiteSpace:'nowrap', overflow:'hidden', textOverflow:'ellipsis' }}>{subtitle}</div>}
          </div>
          <button onClick={onClose} style={{ width: isMobile?34:36, height: isMobile?34:36, borderRadius:9, border:'1.5px solid var(--line)', color:'var(--ink-3)', display:'flex', alignItems:'center', justifyContent:'center', flexShrink:0 }}>
            <Icon name="x" size={17} />
          </button>
        </div>
        <div style={{ padding: isMobile?'16px 16px 22px':'22px 26px 26px' }}>{children}</div>
      </div>
    </div>
  );
}

/* ============================================================
   Utility: calcolo durata e prezzi noleggio
   monthsBetween: calendario reale, con frazioni
   ============================================================ */
function daysBetween(start, end) {
  if (!start || !end) return 0;
  const s = new Date(start.getFullYear(), start.getMonth(), start.getDate());
  const e = new Date(end.getFullYear(), end.getMonth(), end.getDate());
  return Math.max(0, Math.round((e - s) / (1000*60*60*24)));
}
function monthsBetween(start, end) {
  if (!start || !end) return 0;
  const s = new Date(start.getFullYear(), start.getMonth(), start.getDate());
  const e = new Date(end.getFullYear(), end.getMonth(), end.getDate());
  if (e <= s) return 0;
  let full = (e.getFullYear() - s.getFullYear()) * 12 + (e.getMonth() - s.getMonth());
  const sShift = new Date(s.getFullYear(), s.getMonth() + full, s.getDate());
  if (sShift > e) full--;
  const sFull = new Date(s.getFullYear(), s.getMonth() + full, s.getDate());
  const days = Math.round((e - sFull) / (1000*60*60*24));
  const nextMonth = new Date(sFull.getFullYear(), sFull.getMonth() + 1, sFull.getDate());
  const daysOfNextMonth = Math.round((nextMonth - sFull) / (1000*60*60*24));
  return full + (days / daysOfNextMonth);
}
function calcRentalPrices(prezzo, prezzoTipo, dataInizio, dataFine) {
  // Restituisce { perGiorno, perMese, totale } in base a prezzo+tipo+durata
  if (prezzo == null || isNaN(prezzo) || prezzo <= 0 || !dataInizio || !dataFine) return null;
  const giorni = daysBetween(dataInizio, dataFine);
  const mesi = monthsBetween(dataInizio, dataFine);
  if (giorni <= 0 || mesi <= 0) return null;
  let totale, perGiorno, perMese;
  if (prezzoTipo === 'totale') {
    totale = prezzo;
    perGiorno = totale / giorni;
    perMese = totale / mesi;
  } else if (prezzoTipo === 'giornaliero') {
    perGiorno = prezzo;
    totale = perGiorno * giorni;
    perMese = totale / mesi;
  } else if (prezzoTipo === 'mensile') {
    perMese = prezzo;
    totale = perMese * mesi;
    perGiorno = totale / giorni;
  } else return null;
  return {
    perGiorno: Math.round(perGiorno * 100) / 100,
    perMese: Math.round(perMese * 100) / 100,
    totale: Math.round(totale * 100) / 100,
    giorni, mesi,
  };
}

function ConfermaModal({ booking, onClose, onSave }) {
  const isEditData = !!booking.esito;
  const isVendita = booking.tipo === 'Vendita';
  const isNoleggio = booking.tipo === 'STR' || booking.tipo === 'LTR';
  const today = new Date(); today.setHours(0,0,0,0);

  const [num, setNum] = useState(booking.numeroPreventivo || '');
  const [prezzo, setPrezzo] = useState(booking.prezzoPattuito!=null?String(booking.prezzoPattuito):'');
  const [prezzoTipo, setPrezzoTipo] = useState(booking.prezzo_tipo || booking.prezzoTipo || (isNoleggio ? 'totale' : 'totale'));

  const initStart = booking.dataConsegna ? new Date(booking.dataConsegna)
                  : booking.data_consegna ? new Date(booking.data_consegna)
                  : booking.inizio ? new Date(booking.inizio) : today;
  const initEnd = booking.dataRientro ? new Date(booking.dataRientro)
                : booking.data_rientro ? new Date(booking.data_rientro)
                : booking.fine ? new Date(booking.fine) : null;
  const [dataConsegna, setDataConsegna] = useState(initStart);
  const [dataRientro, setDataRientro] = useState(initEnd);
  const [showCalendar, setShowCalendar] = useState(false);

  const handleRange = (a, b) => {
    if (a) setDataConsegna(a);
    setDataRientro(b);
  };

  // Calcolo prezzi automatico
  const prezzoNum = prezzo.trim()==='' ? null : parseFloat(prezzo.replace(/[^\d.,]/g,'').replace(',','.'));
  const calc = isNoleggio ? calcRentalPrices(prezzoNum, prezzoTipo, dataConsegna, dataRientro) : null;

  const submit = () => {
    if (isNoleggio && (!dataConsegna || !dataRientro)) {
      alert('Seleziona data di consegna e rientro');
      return;
    }
    const payload = {
      numeroPreventivo: num.trim() || null,
      prezzoPattuito: prezzoNum,
    };
    if (isNoleggio) {
      payload.dataConsegna = toISODate(dataConsegna);
      payload.dataRientro = toISODate(dataRientro);
      payload.inizio = dataConsegna;
      payload.fine = dataRientro;
      payload.prezzoTipo = prezzoNum != null ? prezzoTipo : null;
      payload.prezzoGiornalieroCalc = calc ? calc.perGiorno : null;
      payload.prezzoMensileCalc = calc ? calc.perMese : null;
    }
    onSave(booking, payload);
  };

  const durataNol = daysBetween(dataConsegna, dataRientro);
  const mesiNol = monthsBetween(dataConsegna, dataRientro);
  const durataLabel = durataNol > 0
    ? (durataNol < 31 ? `${durataNol} giorni` : `${mesiNol.toFixed(1)} mesi · ${durataNol} giorni`)
    : '';

  return (
    <ModalShell onClose={onClose} width={isNoleggio?720:480}
      title={isEditData?'Dati contratto':'Conferma prenotazione'}
      subtitle={isEditData?`${booking.cliente} · ${booking.id}`:`${booking.cliente} · ${booking.tipo}`}>
      {!isEditData && (
        <div style={{ display:'flex', alignItems:'center', gap:10, padding:'11px 14px',
          background: isVendita?'#fdeef0':'#ede9fe', borderRadius:'var(--r-md)', marginBottom:18 }}>
          <Icon name={isVendita?'tag':'clock'} size={17} style={{ color: isVendita?'var(--red)':'#6c5ce7' }} />
          <span style={{ fontSize:13, color: isVendita?'#7a1828':'#4c3c9e', fontWeight:600 }}>
            {isVendita
              ? 'Vendita: il mezzo passerà a stato VENDUTO e uscirà dal catalogo.'
              : 'Noleggio: il mezzo passerà a stato NOLEGGIATO e finirà nella vista "Noleggi in corso".'}
          </span>
        </div>
      )}

      <div style={{ display:'flex', flexDirection:'column', gap:16 }}>
        <Field label="Numero preventivo">
          <input value={num} onChange={e=>setNum(e.target.value)} placeholder="es. PREV-2026-0142" style={inputStyle} autoFocus />
        </Field>

        <div style={{ display:'grid', gridTemplateColumns: isNoleggio?'1fr 1fr':'1fr', gap:14 }}>
          <Field label="Prezzo pattuito (€)">
            <input value={prezzo} onChange={e=>setPrezzo(e.target.value.replace(/[^\d.,]/g,''))}
              placeholder={isVendita?'es. 13500':'es. 3000'} style={inputStyle} />
          </Field>

          {isNoleggio && (
            <Field label="Tipo prezzo">
              <div style={{ display:'flex', gap:0, border:'1.5px solid var(--line)', borderRadius:'var(--r-md)', overflow:'hidden' }}>
                {[
                  ['totale', 'Totale'],
                  ['giornaliero', '€/giorno'],
                  ['mensile', '€/mese'],
                ].map(([k, l], i) => {
                  const active = prezzoTipo === k;
                  return (
                    <button key={k} onClick={()=>setPrezzoTipo(k)}
                      style={{ flex:1, padding:'10px 8px', fontSize:13, fontWeight:700,
                        background: active?'var(--red)':'var(--surface-2)',
                        color: active?'#fff':'var(--ink-2)',
                        borderLeft: i>0?'1.5px solid var(--line)':'none', cursor:'pointer' }}>
                      {l}
                    </button>
                  );
                })}
              </div>
            </Field>
          )}
        </div>

        {/* Riepilogo calcolo */}
        {isNoleggio && calc && (
          <div style={{ padding:'14px 16px', background:'var(--red-tint)', borderLeft:'3px solid var(--red)', borderRadius:6 }}>
            <div style={{ fontSize:11, fontWeight:800, color:'var(--red)', textTransform:'uppercase', letterSpacing:'.05em', marginBottom:8 }}>Calcolo automatico</div>
            <div style={{ display:'grid', gridTemplateColumns:'repeat(3, 1fr)', gap:14 }}>
              <div>
                <div style={{ fontSize:11, color:'var(--ink-3)', marginBottom:2 }}>Totale</div>
                <div style={{ fontFamily:'var(--font-display)', fontSize:18, fontWeight:800 }}>{fmtEur(calc.totale)}</div>
              </div>
              <div>
                <div style={{ fontSize:11, color:'var(--ink-3)', marginBottom:2 }}>Al giorno</div>
                <div style={{ fontFamily:'var(--font-display)', fontSize:18, fontWeight:800 }}>{fmtEur(calc.perGiorno)}</div>
              </div>
              <div>
                <div style={{ fontSize:11, color:'var(--ink-3)', marginBottom:2 }}>Al mese</div>
                <div style={{ fontFamily:'var(--font-display)', fontSize:18, fontWeight:800 }}>{fmtEur(calc.perMese)}</div>
              </div>
            </div>
            <div style={{ marginTop:10, fontSize:11.5, color:'var(--ink-3)' }}>
              Durata: {calc.giorni} giorni ({calc.mesi.toFixed(2)} mesi calendario)
            </div>
          </div>
        )}

        {/* Periodo noleggio */}
        {isNoleggio && (
          <div>
            <div style={{ display:'flex', alignItems:'center', justifyContent:'space-between', marginBottom:8 }}>
              <span style={{ fontSize:12.5, fontWeight:700, color:'var(--ink-2)' }}>Periodo noleggio <span style={{ color:'var(--red)' }}>*</span></span>
              {durataLabel && <span style={{ fontSize:12, fontWeight:700, color:'var(--red)', background:'var(--red-tint)', padding:'3px 10px', borderRadius:99 }}>{durataLabel}</span>}
            </div>

            <div style={{ display:'grid', gridTemplateColumns:'1fr 1fr', gap:10, marginBottom:10 }}>
              <button onClick={()=>setShowCalendar(s=>!s)} style={{
                display:'flex', alignItems:'center', gap:10, padding:'11px 13px', borderRadius:'var(--r-md)',
                border:'1.5px solid '+(showCalendar?'var(--red)':'var(--line)'), background:'var(--surface-2)', textAlign:'left' }}>
                <Icon name="calendar" size={17} style={{ color: dataConsegna?'var(--red)':'var(--ink-4)' }} />
                <div style={{ flex:1 }}>
                  <div style={{ fontSize:11, fontWeight:700, color:'var(--ink-4)', textTransform:'uppercase', letterSpacing:'.03em' }}>Consegna</div>
                  <div style={{ fontSize:13.5, fontWeight:700, color:'var(--ink)' }}>
                    {dataConsegna ? fmtDate(dataConsegna) : 'Seleziona'}
                  </div>
                </div>
              </button>
              <button onClick={()=>setShowCalendar(s=>!s)} style={{
                display:'flex', alignItems:'center', gap:10, padding:'11px 13px', borderRadius:'var(--r-md)',
                border:'1.5px solid '+(showCalendar?'var(--red)':'var(--line)'), background:'var(--surface-2)', textAlign:'left' }}>
                <Icon name="calendar" size={17} style={{ color: dataRientro?'var(--red)':'var(--ink-4)' }} />
                <div style={{ flex:1 }}>
                  <div style={{ fontSize:11, fontWeight:700, color:'var(--ink-4)', textTransform:'uppercase', letterSpacing:'.03em' }}>Rientro previsto</div>
                  <div style={{ fontSize:13.5, fontWeight:700, color:'var(--ink)' }}>
                    {dataRientro ? fmtDate(dataRientro) : 'Seleziona'}
                  </div>
                </div>
              </button>
            </div>

            <DateRangePicker
              start={dataConsegna}
              end={dataRientro}
              onChange={handleRange}
              minDate={today}
            />

            <div style={{ marginTop:8, fontSize:11.5, color:'var(--ink-4)', display:'flex', alignItems:'center', gap:6 }}>
              <Icon name="clock" size={13} />
              Clicca prima la data di consegna, poi quella di rientro. Potrai modificare le date in seguito da "Noleggi in corso".
            </div>
          </div>
        )}

        <div style={{ fontSize:12, color:'var(--ink-4)', display:'flex', alignItems:'center', gap:7 }}>
          <Icon name="lock" size={13} /> Numero preventivo e prezzo sono facoltativi e potranno essere completati in seguito.
        </div>
      </div>
      <div style={{ display:'flex', gap:12, marginTop:22 }}>
        <Btn variant="ghost" full onClick={onClose}>Annulla</Btn>
        <Btn full icon="check" onClick={submit}>{isEditData?'Salva dati':'Conferma e archivia'}</Btn>
      </div>
    </ModalShell>
  );
}

Object.assign(window, { daysBetween, monthsBetween, calcRentalPrices });

Object.assign(window, { Prenotazioni, BookingModal, ConfermaModal, ModalShell, Field, inputStyle, BK_STATI });