/* ============================================================
   DATE PICKER — Calendario inline stile Booking
   ============================================================ */

const MONTHS_IT = ['Gennaio','Febbraio','Marzo','Aprile','Maggio','Giugno','Luglio','Agosto','Settembre','Ottobre','Novembre','Dicembre'];
const DAYS_IT = ['Lu','Ma','Me','Gi','Ve','Sa','Do'];

function startOfMonth(d) {
  return new Date(d.getFullYear(), d.getMonth(), 1);
}
function sameDay(a, b) {
  if (!a || !b) return false;
  return a.getFullYear()===b.getFullYear() && a.getMonth()===b.getMonth() && a.getDate()===b.getDate();
}
function toISODate(d) {
  const y = d.getFullYear();
  const m = String(d.getMonth()+1).padStart(2,'0');
  const day = String(d.getDate()).padStart(2,'0');
  return `${y}-${m}-${day}`;
}

function CalendarMonth({ month, selected, minDate, maxDate, rangeStart, rangeEnd, onSelect, accent }) {
  const first = startOfMonth(month);
  const lastDay = new Date(first.getFullYear(), first.getMonth()+1, 0).getDate();
  const firstWeekday = (first.getDay() + 6) % 7; // lun=0
  const today = new Date(); today.setHours(0,0,0,0);
  const cells = [];
  for (let i=0; i<firstWeekday; i++) cells.push(null);
  for (let d=1; d<=lastDay; d++) cells.push(new Date(first.getFullYear(), first.getMonth(), d));
  while (cells.length % 7 !== 0) cells.push(null);

  const isInRange = (d) => {
    if (!rangeStart || !rangeEnd) return false;
    return d > rangeStart && d < rangeEnd;
  };

  return (
    <div>
      <div style={{ textAlign:'center', fontSize:14, fontWeight:800, marginBottom:14, fontFamily:'var(--font-display)' }}>
        {MONTHS_IT[month.getMonth()]} {month.getFullYear()}
      </div>
      <div style={{ display:'grid', gridTemplateColumns:'repeat(7, 1fr)', gap:4, marginBottom:6 }}>
        {DAYS_IT.map(d => <div key={d} style={{ textAlign:'center', fontSize:11, fontWeight:700, color:'var(--ink-4)', textTransform:'uppercase' }}>{d}</div>)}
      </div>
      <div style={{ display:'grid', gridTemplateColumns:'repeat(7, 1fr)', gap:4 }}>
        {cells.map((d, i) => {
          if (!d) return <div key={i} />;
          const disabled = (minDate && d < minDate) || (maxDate && d > maxDate);
          const isSelected = sameDay(d, selected) || sameDay(d, rangeStart) || sameDay(d, rangeEnd);
          const inRange = isInRange(d);
          const isToday = sameDay(d, today);
          let bg = 'transparent', color = 'var(--ink-2)', border = '1px solid transparent';
          if (disabled) { color = 'var(--ink-4)'; }
          else if (isSelected) { bg = accent || 'var(--red)'; color = '#fff'; }
          else if (inRange) { bg = 'var(--red-tint)'; color = 'var(--red)'; }
          else if (isToday) { border = '1px solid var(--line)'; color = 'var(--red)'; }
          return (
            <button key={i} onClick={()=>!disabled && onSelect(d)} disabled={disabled}
              style={{ height:36, borderRadius:8, background:bg, color, border, fontSize:13, fontWeight: isSelected?700:600,
                cursor: disabled?'not-allowed':'pointer', transition:'.1s' }}
              onMouseEnter={e=>{ if (!disabled && !isSelected) e.currentTarget.style.background='var(--line-2)'; }}
              onMouseLeave={e=>{ if (!disabled && !isSelected) e.currentTarget.style.background = inRange?'var(--red-tint)':'transparent'; }}>
              {d.getDate()}
            </button>
          );
        })}
      </div>
    </div>
  );
}

/* ---- Date picker INLINE (singolo) ------------------------ */
function DatePickerInline({ value, onChange, minDate, maxDate, accent }) {
  const [month, setMonth] = useState(value ? startOfMonth(value) : startOfMonth(new Date()));
  const selected = value;
  const min = minDate ? new Date(minDate) : null;
  if (min) min.setHours(0,0,0,0);
  const max = maxDate ? new Date(maxDate) : null;
  if (max) max.setHours(23,59,59);

  return (
    <div style={{ background:'var(--surface)', border:'1.5px solid var(--line)', borderRadius:'var(--r-md)', padding:'14px 16px' }}>
      <div style={{ display:'flex', alignItems:'center', justifyContent:'space-between', marginBottom:10 }}>
        <button onClick={()=>setMonth(m => new Date(m.getFullYear(), m.getMonth()-1, 1))}
          style={{ width:32, height:32, borderRadius:8, border:'1px solid var(--line)', display:'flex', alignItems:'center', justifyContent:'center', color:'var(--ink-2)' }}>
          <Icon name="chevLeft" size={16} />
        </button>
        <span style={{ fontSize:13.5, fontWeight:700, color:'var(--ink-2)' }}></span>
        <button onClick={()=>setMonth(m => new Date(m.getFullYear(), m.getMonth()+1, 1))}
          style={{ width:32, height:32, borderRadius:8, border:'1px solid var(--line)', display:'flex', alignItems:'center', justifyContent:'center', color:'var(--ink-2)' }}>
          <Icon name="chevRight" size={16} />
        </button>
      </div>
      <CalendarMonth month={month} selected={selected} minDate={min} maxDate={max} onSelect={onChange} accent={accent} />
    </div>
  );
}

/* ---- Date RANGE picker (inizio + fine) ------------------- */
function DateRangePicker({ start, end, onChange, minDate, accent }) {
  const vp = useViewport();
  const [month, setMonth] = useState(start ? startOfMonth(start) : startOfMonth(new Date()));
  const [phase, setPhase] = useState(start && !end ? 'end' : 'start'); // start | end
  const min = minDate ? new Date(minDate) : null;
  if (min) min.setHours(0,0,0,0);

  const handleSelect = (d) => {
    if (phase === 'start') {
      onChange(d, null);
      setPhase('end');
    } else {
      if (start && d < start) {
        onChange(d, start);
      } else {
        onChange(start, d);
      }
      setPhase('start');
    }
  };

  // Mostro DUE mesi affiancati (su desktop) o 1 solo (su mobile)
  const monthA = month;
  const monthB = new Date(month.getFullYear(), month.getMonth()+1, 1);

  return (
    <div style={{ background:'var(--surface)', border:'1.5px solid var(--line)', borderRadius:'var(--r-md)', padding: vp.isMobile?'12px 14px':'14px 16px' }}>
      <div style={{ display:'flex', alignItems:'center', justifyContent:'space-between', marginBottom:10, gap:8, flexWrap:'wrap' }}>
        <button onClick={()=>setMonth(m => new Date(m.getFullYear(), m.getMonth()-1, 1))}
          style={{ width:32, height:32, borderRadius:8, border:'1px solid var(--line)', display:'flex', alignItems:'center', justifyContent:'center', color:'var(--ink-2)' }}>
          <Icon name="chevLeft" size={16} />
        </button>
        <div style={{ display:'flex', gap:6, alignItems:'center', fontSize: vp.isMobile?11.5:12, fontWeight:700, flex: vp.isMobile?1:'none', justifyContent:'center', flexWrap:'wrap' }}>
          <span style={{ padding:'5px 10px', borderRadius:99, background: phase==='start'?(accent||'var(--red)'):'var(--line-2)', color: phase==='start'?'#fff':'var(--ink-3)' }}>
            {start ? fmtDate(start) : 'Inizio'}
          </span>
          <Icon name="arrowRight" size={13} style={{ color:'var(--ink-4)' }} />
          <span style={{ padding:'5px 10px', borderRadius:99, background: phase==='end'?(accent||'var(--red)'):'var(--line-2)', color: phase==='end'?'#fff':'var(--ink-3)' }}>
            {end ? fmtDate(end) : 'Fine'}
          </span>
        </div>
        <button onClick={()=>setMonth(m => new Date(m.getFullYear(), m.getMonth()+1, 1))}
          style={{ width:32, height:32, borderRadius:8, border:'1px solid var(--line)', display:'flex', alignItems:'center', justifyContent:'center', color:'var(--ink-2)' }}>
          <Icon name="chevRight" size={16} />
        </button>
      </div>
      <div style={{ display:'grid', gridTemplateColumns: vp.isMobile?'1fr':'1fr 1fr', gap: vp.isMobile?16:20 }}>
        <CalendarMonth month={monthA} rangeStart={start} rangeEnd={end} minDate={min} onSelect={handleSelect} accent={accent} />
        {!vp.isMobile && <CalendarMonth month={monthB} rangeStart={start} rangeEnd={end} minDate={min} onSelect={handleSelect} accent={accent} />}
      </div>
    </div>
  );
}

/* ---- DatePickerModal (per modifiche rapide) -------------- */
function DatePickerModal({ title, subtitle, currentDate, minDate, onClose, onSave }) {
  const [date, setDate] = useState(currentDate ? new Date(currentDate) : new Date());
  return (
    <ModalShell onClose={onClose} width={420} title={title} subtitle={subtitle}>
      <DatePickerInline value={date} onChange={setDate} minDate={minDate} />
      <div style={{ display:'flex', gap:12, marginTop:18 }}>
        <Btn variant="ghost" full onClick={onClose}>Annulla</Btn>
        <Btn full icon="check" onClick={()=>onSave(toISODate(date))}>Salva data</Btn>
      </div>
    </ModalShell>
  );
}

Object.assign(window, { DatePickerInline, DateRangePicker, DatePickerModal, toISODate, MONTHS_IT, DAYS_IT, CalendarMonth });