/* ============================================================
   RENTAL — Proroga, Interruzione, Modifica data inizio
   Timeline proroghe + utility
   ============================================================ */

function fmtDateShort(d) {
  if (!d) return '—';
  const date = d instanceof Date ? d : new Date(d);
  if (isNaN(date.getTime())) return '—';
  return date.toLocaleDateString('it-IT', { day:'2-digit', month:'short', year:'numeric' });
}

/* ============================================================
   PROROGA NOLEGGIO
   ============================================================ */
function RentalExtendModal({ booking, lastEndDate, onClose, onSave }) {
  const today = new Date(); today.setHours(0,0,0,0);
  // La proroga inizia dalla data di fine precedente (o oggi se quella è nel passato)
  const startDate = lastEndDate && new Date(lastEndDate) > today ? new Date(lastEndDate) : today;
  const [dataFine, setDataFine] = useState(null);
  const [num, setNum] = useState('');
  const [prezzo, setPrezzo] = useState('');
  const [prezzoTipo, setPrezzoTipo] = useState('totale');
  const [note, setNote] = useState('');
  const [showCalendar, setShowCalendar] = useState(true);

  const prezzoNum = prezzo.trim()==='' ? null : parseFloat(prezzo.replace(/[^\d.,]/g,'').replace(',','.'));
  const calc = (prezzoNum != null && dataFine) ? window.calcRentalPrices(prezzoNum, prezzoTipo, startDate, dataFine) : null;

  const giorni = dataFine ? window.daysBetween(startDate, dataFine) : 0;
  const mesi = dataFine ? window.monthsBetween(startDate, dataFine) : 0;
  const durataLabel = giorni > 0
    ? (giorni < 31 ? `${giorni} giorni` : `${mesi.toFixed(1)} mesi · ${giorni} giorni`)
    : '';

  const submit = () => {
    if (!dataFine) { alert('Seleziona la data di fine proroga'); return; }
    onSave({
      data_inizio_proroga: window.toISODate(startDate),
      data_fine_proroga: window.toISODate(dataFine),
      numero_preventivo: num.trim() || null,
      prezzo_pattuito: prezzoNum,
      prezzo_tipo: prezzoNum != null ? prezzoTipo : null,
      prezzo_giornaliero_calc: calc ? calc.perGiorno : null,
      prezzo_mensile_calc: calc ? calc.perMese : null,
      note: note.trim() || null,
    });
  };

  return (
    <ModalShell onClose={onClose} width={720}
      title="Proroga noleggio"
      subtitle={`${booking.cliente} · ${booking.prodLabel || ''}`}>

      <div style={{ display:'flex', alignItems:'center', gap:10, padding:'11px 14px',
        background:'var(--red-tint)', borderRadius:'var(--r-md)', marginBottom:18 }}>
        <Icon name="refresh" size={17} style={{ color:'var(--red)' }} />
        <span style={{ fontSize:13, color:'var(--ink-2)', fontWeight:600 }}>
          La proroga parte da <b>{fmtDateShort(startDate)}</b> (fine prenotazione attuale).
          Le date originali della prenotazione restano invariate.
        </span>
      </div>

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

        <div style={{ display:'grid', gridTemplateColumns:'1fr 1fr', gap:14 }}>
          <Field label="Prezzo pattuito (€)">
            <input value={prezzo} onChange={e=>setPrezzo(e.target.value.replace(/[^\d.,]/g,''))}
              placeholder="es. 1500" style={inputStyle} />
          </Field>
          <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>

        {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 proroga: {calc.giorni} giorni ({calc.mesi.toFixed(2)} mesi calendario)
            </div>
          </div>
        )}

        <div>
          <div style={{ display:'flex', alignItems:'center', justifyContent:'space-between', marginBottom:8 }}>
            <span style={{ fontSize:12.5, fontWeight:700, color:'var(--ink-2)' }}>Nuova data di rientro <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>
          <DateRangePicker
            start={startDate}
            end={dataFine}
            onChange={(_, b)=>setDataFine(b)}
            minDate={startDate}
            disableStart={true}
          />
        </div>

        <Field label="Note (facoltative)">
          <input value={note} onChange={e=>setNote(e.target.value)} placeholder="es. accordo telefonico cliente" style={inputStyle} />
        </Field>

        <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} disabled={!dataFine}>Conferma proroga</Btn>
      </div>
    </ModalShell>
  );
}

/* ============================================================
   INTERRUZIONE NOLEGGIO (solo admin/backoffice)
   ============================================================ */
function RentalInterruptModal({ booking, reasons, onClose, onSave }) {
  const today = new Date(); today.setHours(0,0,0,0);
  const [dataInt, setDataInt] = useState(today);
  const [reasonId, setReasonId] = useState('');
  const [note, setNote] = useState('');

  const activeReasons = (reasons || []).filter(r => r.attivo !== false).sort((a,b) => (a.ordine||0) - (b.ordine||0));
  const submit = () => {
    if (!reasonId) { alert('Seleziona un motivo'); return; }
    onSave({
      data_interruzione: window.toISODate(dataInt),
      interruzione_reason_id: reasonId,
      interruzione_note: note.trim() || null,
    });
  };

  return (
    <ModalShell onClose={onClose} width={520}
      title="Interrompi noleggio"
      subtitle={`${booking.cliente} · ${booking.prodLabel || ''}`}>

      <div style={{ display:'flex', alignItems:'center', gap:10, padding:'11px 14px',
        background:'#fdeef0', borderRadius:'var(--r-md)', marginBottom:18 }}>
        <Icon name="alertCircle" size={17} style={{ color:'var(--red)' }} />
        <span style={{ fontSize:13, color:'#7a1828', fontWeight:600 }}>
          Il mezzo passerà a stato <b>IN_ARRIVO</b>. La cronologia del noleggio resta visibile in archivio.
        </span>
      </div>

      <div style={{ display:'flex', flexDirection:'column', gap:16 }}>
        <Field label="Data interruzione" required>
          <input type="date" value={window.toISODate(dataInt)}
            onChange={e=>setDataInt(new Date(e.target.value))}
            style={inputStyle} />
        </Field>

        <Field label="Motivo dell'interruzione" required>
          {activeReasons.length === 0 ? (
            <div style={{ padding:'12px 14px', background:'var(--surface-2)', borderRadius:'var(--r-md)', fontSize:13, color:'var(--ink-3)' }}>
              Nessun motivo configurato. L'admin può aggiungerli da Console Admin → Motivi interruzione.
            </div>
          ) : (
            <div style={{ display:'flex', flexDirection:'column', gap:6 }}>
              {activeReasons.map(r => {
                const active = reasonId === r.id;
                return (
                  <button key={r.id} onClick={()=>setReasonId(r.id)}
                    style={{ display:'flex', alignItems:'flex-start', gap:11, padding:'12px 14px', borderRadius:'var(--r-md)',
                      border:'1.5px solid '+(active?'var(--red)':'var(--line)'),
                      background: active?'var(--red-tint)':'var(--surface)', textAlign:'left', cursor:'pointer' }}>
                    <span style={{ width:18, height:18, borderRadius:99, flexShrink:0, marginTop:2,
                      border:'2px solid '+(active?'var(--red)':'var(--line)'),
                      background: active?'var(--red)':'transparent' }} />
                    <div style={{ flex:1 }}>
                      <div style={{ fontSize:14, fontWeight:700, color: active?'var(--red)':'var(--ink)' }}>{r.label}</div>
                      {r.descrizione && <div style={{ fontSize:12, color:'var(--ink-3)', marginTop:2 }}>{r.descrizione}</div>}
                    </div>
                  </button>
                );
              })}
            </div>
          )}
        </Field>

        <Field label="Note aggiuntive">
          <textarea value={note} onChange={e=>setNote(e.target.value)}
            placeholder="Dettagli, contesto, accordi presi…"
            rows={3}
            style={{ ...inputStyle, minHeight:80, resize:'vertical', fontFamily:'inherit' }} />
        </Field>
      </div>

      <div style={{ display:'flex', gap:12, marginTop:22 }}>
        <Btn variant="ghost" full onClick={onClose}>Annulla</Btn>
        <Btn full icon="alertCircle" onClick={submit} disabled={!reasonId}>Interrompi noleggio</Btn>
      </div>
    </ModalShell>
  );
}

/* ============================================================
   MODIFICA DATA INIZIO (solo se non ancora iniziato)
   ============================================================ */
function RentalEditStartModal({ booking, onClose, onSave }) {
  const today = new Date(); today.setHours(0,0,0,0);
  const currentStart = booking.dataConsegna ? new Date(booking.dataConsegna) : new Date();
  const [dataInizio, setDataInizio] = useState(currentStart);

  const submit = () => {
    if (!dataInizio) return;
    onSave({ data_consegna: window.toISODate(dataInizio) });
  };

  return (
    <ModalShell onClose={onClose} width={480}
      title="Modifica data inizio noleggio"
      subtitle={`${booking.cliente} · ${booking.prodLabel || ''}`}>

      <div style={{ display:'flex', alignItems:'center', gap:10, padding:'11px 14px',
        background:'var(--red-tint)', borderRadius:'var(--r-md)', marginBottom:18 }}>
        <Icon name="calendar" size={17} style={{ color:'var(--red)' }} />
        <span style={{ fontSize:13, color:'var(--ink-2)', fontWeight:600 }}>
          Modificabile solo perché il noleggio non è ancora iniziato.
        </span>
      </div>

      <Field label="Nuova data di consegna" required>
        <input type="date" value={window.toISODate(dataInizio)}
          min={window.toISODate(today)}
          onChange={e=>setDataInizio(new Date(e.target.value))}
          style={inputStyle} autoFocus />
      </Field>

      <div style={{ display:'flex', gap:12, marginTop:22 }}>
        <Btn variant="ghost" full onClick={onClose}>Annulla</Btn>
        <Btn full icon="check" onClick={submit} disabled={!dataInizio}>Salva nuova data</Btn>
      </div>
    </ModalShell>
  );
}

/* ============================================================
   TIMELINE proroghe + interruzione (visibile in BookingDetail)
   ============================================================ */
function RentalTimeline({ booking, extensions, reasons }) {
  const vp = useViewport();
  const sorted = (extensions || []).slice().sort((a,b) => (a.numero||0) - (b.numero||0));
  const isInterrupted = !!booking.interrotto;
  // Niente da mostrare se non c'è cronologia e non è interrotto
  if (sorted.length === 0 && !isInterrupted) return null;

  const reason = isInterrupted ? (reasons || []).find(r => r.id === booking.interruzione_reason_id) : null;
  const totalEvents = sorted.length + (isInterrupted ? 1 : 0);

  return (
    <div style={{ marginTop:16, padding: vp.isMobile?'14px 14px':'18px 20px', background:'var(--surface)', border:'1px solid var(--line)', borderRadius:'var(--r-lg)' }}>
      <div style={{ display:'flex', alignItems:'center', gap:8, marginBottom:12, flexWrap:'wrap' }}>
        <Icon name={isInterrupted?'alertCircle':'refresh'} size={17} style={{ color:'var(--red)' }} />
        <h3 style={{ margin:0, fontFamily:'var(--font-display)', fontSize: vp.isMobile?14:15, fontWeight:800 }}>
          Cronologia noleggio
          <span style={{ marginLeft:8, fontSize:12, fontWeight:600, color:'var(--ink-3)' }}>
            ({sorted.length} {sorted.length===1?'proroga':'proroghe'}{isInterrupted?' · interrotto':''})
          </span>
        </h3>
      </div>

      <div style={{ position:'relative', paddingLeft:24 }}>
        {/* Linea verticale */}
        <div style={{ position:'absolute', left:7, top:6, bottom:6, width:2, background:'var(--line)' }} />

        {/* Prenotazione originale */}
        <div style={{ position:'relative', marginBottom:18 }}>
          <span style={{ position:'absolute', left:-21, top:4, width:14, height:14, borderRadius:99, background:'var(--ink)', border:'3px solid var(--surface)', boxShadow:'0 0 0 2px var(--ink)' }} />
          <div style={{ fontSize:11, fontWeight:800, color:'var(--ink-3)', textTransform:'uppercase', letterSpacing:'.05em' }}>Prenotazione originale</div>
          <div style={{ fontSize:13.5, fontWeight:700, marginTop:3 }}>
            {fmtDateShort(booking.dataConsegna || booking.inizio)} → {fmtDateShort(booking.dataRientro || booking.fine)}
          </div>
          {booking.numeroPreventivo && (
            <div style={{ fontSize:12, color:'var(--ink-3)', marginTop:2 }}>
              Preventivo: <b>{booking.numeroPreventivo}</b> · {booking.prezzoPattuito != null ? fmtEur(booking.prezzoPattuito) : '—'}
              {booking.prezzo_tipo && booking.prezzo_tipo !== 'totale' ? ` (${booking.prezzo_tipo})` : ''}
            </div>
          )}
        </div>

        {/* Proroghe */}
        {sorted.map((ext, i) => {
          const isLast = i === sorted.length - 1 && !isInterrupted;
          return (
            <div key={ext.id} style={{ position:'relative', marginBottom: isLast ? 0 : 18 }}>
              <span style={{ position:'absolute', left:-21, top:4, width:14, height:14, borderRadius:99, background:'var(--red)', border:'3px solid var(--surface)', boxShadow:'0 0 0 2px var(--red)' }} />
              <div style={{ fontSize:11, fontWeight:800, color:'var(--red)', textTransform:'uppercase', letterSpacing:'.05em' }}>
                Proroga #{ext.numero}
              </div>
              <div style={{ fontSize:13.5, fontWeight:700, marginTop:3 }}>
                {fmtDateShort(ext.data_inizio_proroga)} → {fmtDateShort(ext.data_fine_proroga)}
              </div>
              <div style={{ display:'flex', flexWrap:'wrap', gap:14, marginTop:6, fontSize:12, color:'var(--ink-3)' }}>
                {ext.numero_preventivo && <span>Preventivo: <b>{ext.numero_preventivo}</b></span>}
                {ext.prezzo_pattuito != null && (
                  <span>Prezzo: <b>{fmtEur(ext.prezzo_pattuito)}</b>
                    {ext.prezzo_tipo && ext.prezzo_tipo !== 'totale' ? ` (${ext.prezzo_tipo})` : ''}
                  </span>
                )}
                {ext.prezzo_giornaliero_calc != null && <span>€/giorno: <b>{fmtEur(ext.prezzo_giornaliero_calc)}</b></span>}
                {ext.prezzo_mensile_calc != null && <span>€/mese: <b>{fmtEur(ext.prezzo_mensile_calc)}</b></span>}
                {ext.created_by_nome && <span style={{ color:'var(--ink-4)' }}>· da {ext.created_by_nome}</span>}
              </div>
              {ext.note && (
                <div style={{ fontSize:12, color:'var(--ink-3)', marginTop:4, fontStyle:'italic' }}>"{ext.note}"</div>
              )}
            </div>
          );
        })}

        {/* Interruzione anticipata — ultimo nodo se interrotto */}
        {isInterrupted && (
          <div style={{ position:'relative' }}>
            <span style={{ position:'absolute', left:-23, top:2, width:18, height:18, borderRadius:99,
              background:'var(--red)', border:'3px solid var(--surface)', boxShadow:'0 0 0 2px var(--red)',
              display:'flex', alignItems:'center', justifyContent:'center', color:'#fff' }}>
              <Icon name="x" size={11} stroke={3} />
            </span>
            <div style={{ marginLeft:0, padding:'12px 14px', background:'#fdeef0', borderRadius:'var(--r-md)', border:'1px solid #f5c6cb' }}>
              <div style={{ display:'flex', alignItems:'center', justifyContent:'space-between', gap:10 }}>
                <div style={{ fontSize:11, fontWeight:800, color:'#7a1828', textTransform:'uppercase', letterSpacing:'.05em' }}>
                  Noleggio interrotto
                </div>
                <div style={{ fontSize:12, fontWeight:700, color:'#7a1828' }}>
                  {fmtDateShort(booking.data_interruzione)}
                </div>
              </div>
              {reason && (
                <div style={{ fontSize:13.5, fontWeight:700, color:'#7a1828', marginTop:6 }}>
                  Motivo: {reason.label}
                </div>
              )}
              {reason && reason.descrizione && (
                <div style={{ fontSize:12, color:'#7a1828', opacity:.75, marginTop:2 }}>{reason.descrizione}</div>
              )}
              {booking.interruzione_note && (
                <div style={{ fontSize:12.5, color:'#7a1828', marginTop:6, fontStyle:'italic' }}>"{booking.interruzione_note}"</div>
              )}
            </div>
          </div>
        )}
      </div>
    </div>
  );
}

/* ============================================================
   BANDIERA noleggio interrotto
   ============================================================ */
function InterruptionBanner({ booking, reasons }) {
  const vp = useViewport();
  if (!booking.interrotto) return null;
  const reason = (reasons || []).find(r => r.id === booking.interruzione_reason_id);
  return (
    <div style={{ marginTop:16, padding: vp.isMobile?'12px 14px':'14px 18px', background:'#fdeef0', borderLeft:'3px solid var(--red)', borderRadius:6 }}>
      <div style={{ display:'flex', alignItems:'center', gap:8, flexWrap:'wrap' }}>
        <Icon name="alertCircle" size={17} style={{ color:'var(--red)' }} />
        <span style={{ fontSize: vp.isMobile?13:13.5, fontWeight:800, color:'#7a1828' }}>
          NOLEGGIO INTERROTTO
        </span>
        <span style={{ fontSize:12, color:'#7a1828', marginLeft: vp.isMobile?0:'auto' }}>
          {fmtDateShort(booking.data_interruzione)}
        </span>
      </div>
      {reason && (
        <div style={{ marginTop:6, fontSize:13, color:'#7a1828' }}>
          Motivo: <b>{reason.label}</b>
        </div>
      )}
      {booking.interruzione_note && (
        <div style={{ marginTop:4, fontSize:12.5, color:'#7a1828', fontStyle:'italic' }}>
          "{booking.interruzione_note}"
        </div>
      )}
    </div>
  );
}

Object.assign(window, { RentalExtendModal, RentalInterruptModal, RentalEditStartModal, RentalTimeline, InterruptionBanner, fmtDateShort });