/* FUMO — opening countdown + pre-order reservation form */

// TODO(FUMO): adjust if the opening time changes. Friday 16 Oct 2026, 18:00 Tirana (CEST, +02:00).
const FUMO_OPENING = { at: '2026-10-16T18:00:00+02:00', date: '2026-10-16', timeFrom: 18 };

const R18N = {
  EN: { opens: 'Opening Friday 16 October · 18:00', soon: 'Opening soon', d: 'Days', h: 'Hours', m: 'Min', s: 'Sec',
        cta: 'Pre-order a table', title: 'Reserve your table', sub: 'Be among the first at Fumo Bar Bistro. Leave your details and we will confirm by phone.',
        name: 'Full name', phone: 'Phone number', date: 'Date', time: 'Time', guests: 'Guests', note: 'Note (optional)',
        send: 'Send reservation', sending: 'Sending…', close: 'Close', okTitle: 'Thank you!', ok: 'Your reservation was received successfully. We will call you to confirm.',
        err: 'Could not send — please check your details and try again.', rate: 'Too many requests — please try again later.' },
  SQ: { opens: 'Hapemi të Premten 16 Tetor · 18:00', soon: 'Hapemi së shpejti', d: 'Ditë', h: 'Orë', m: 'Min', s: 'Sek',
        cta: 'Rezervo tavolinën', title: 'Rezervo tavolinën tënde', sub: 'Bëhu mes të parëve te Fumo Bar Bistro. Lër të dhënat dhe do të të konfirmojmë me telefon.',
        name: 'Emri i plotë', phone: 'Numri i telefonit', date: 'Data', time: 'Ora', guests: 'Persona', note: 'Shënim (opsionale)',
        send: 'Dërgo rezervimin', sending: 'Po dërgohet…', close: 'Mbyll', okTitle: 'Faleminderit!', ok: 'Rezervimi u mor me sukses! Do të të telefonojmë për konfirmim.',
        err: 'Nuk u dërgua — kontrollo të dhënat dhe provo përsëri.', rate: 'Shumë kërkesa — provo më vonë.' },
  IT: { opens: 'Apertura venerdì 16 ottobre · 18:00', soon: 'Apertura a breve', d: 'Giorni', h: 'Ore', m: 'Min', s: 'Sec',
        cta: 'Prenota un tavolo', title: 'Prenota il tuo tavolo', sub: 'Sii tra i primi da Fumo Bar Bistro. Lascia i tuoi dati e ti confermeremo per telefono.',
        name: 'Nome e cognome', phone: 'Telefono', date: 'Data', time: 'Ora', guests: 'Persone', note: 'Nota (facoltativa)',
        send: 'Invia prenotazione', sending: 'Invio…', close: 'Chiudi', okTitle: 'Grazie!', ok: 'Prenotazione ricevuta con successo! Ti chiameremo per confermare.',
        err: 'Invio non riuscito — controlla i dati e riprova.', rate: 'Troppe richieste — riprova più tardi.' },
};

function useCountdown() {
  const target = new Date(FUMO_OPENING.at).getTime();
  const [left, setLeft] = React.useState(() => target - Date.now());
  React.useEffect(() => {
    const id = setInterval(() => setLeft(target - Date.now()), 1000);
    return () => clearInterval(id);
  }, [target]);
  return left;
}

function Countdown({ lang, onReserve }) {
  const r = R18N[lang];
  const left = useCountdown();
  const narrow = useIsNarrow(680);
  if (left <= 0) return null;
  const sec = Math.floor(left / 1000);
  const parts = [[Math.floor(sec / 86400), r.d], [Math.floor(sec / 3600) % 24, r.h], [Math.floor(sec / 60) % 60, r.m], [sec % 60, r.s]];
  return (
    <section style={{ background: 'var(--sand-100)', borderBottom: '1px solid var(--line-200)', padding: narrow ? '26px 64px 30px 14px' : '34px 24px 38px', display: 'flex', flexDirection: 'column', alignItems: 'center', gap: narrow ? 16 : 20 }}>
      <div style={{ font: 'var(--weight-semibold) ' + (narrow ? 10.5 : 12) + 'px/1.5 var(--font-body)', letterSpacing: narrow ? '0.14em' : '0.22em', textTransform: 'uppercase', color: 'var(--gold-600)', textAlign: 'center' }}>{r.opens}</div>
      <div style={{ display: 'flex', gap: narrow ? 8 : 14 }}>
        {parts.map(([n, l]) => (
          <div key={l} style={{ minWidth: narrow ? 62 : 88, padding: narrow ? '12px 6px' : '16px 10px', borderRadius: 'var(--radius-lg)', border: '1px solid var(--line-300)', background: 'var(--sand-50)', boxShadow: 'none', textAlign: 'center' }}>
            <div style={{ font: 'var(--weight-semibold) ' + (narrow ? 28 : 38) + 'px/1 var(--font-display)', fontVariantNumeric: 'tabular-nums', color: 'var(--ink-900)' }}>{String(n).padStart(2, '0')}</div>
            <div style={{ marginTop: 6, font: 'var(--weight-semibold) 10px/1 var(--font-body)', letterSpacing: '0.18em', textTransform: 'uppercase', color: 'var(--slate-500)' }}>{l}</div>
          </div>
        ))}
      </div>
      <button type="button" onClick={onReserve} style={{ appearance: 'none', cursor: 'pointer', border: 0, borderRadius: 'var(--radius-pill)', padding: '14px 28px', background: 'var(--navy-800)', color: 'var(--ink-900)', font: 'var(--weight-semibold) 12px/1 var(--font-body)', letterSpacing: '0.14em', textTransform: 'uppercase' }}>{r.cta}</button>
    </section>
  );
}

function ReserveModal({ lang, onClose }) {
  const r = R18N[lang];
  const narrow = useIsNarrow(680);
  const times = [];
  for (let h = FUMO_OPENING.timeFrom; h <= 24; h++) for (const m of [0, 30]) { if (h === 24 && m) continue; times.push(String(h % 24).padStart(2, '0') + ':' + (m ? '30' : '00')); }
  const [f, setF] = React.useState({ name: '', phone: '', date: FUMO_OPENING.date, time: times[0], guests: 2, note: '' });
  const [state, setState] = React.useState('idle'); // idle | sending | done | err | rate
  const set = (k) => (e) => setF({ ...f, [k]: e.target.value });
  const submit = async (e) => {
    e.preventDefault();
    setState('sending');
    try {
      const res = await fetch('../../api/reserve', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ ...f, lang: lang.toLowerCase() }) });
      setState(res.ok ? 'done' : res.status === 429 ? 'rate' : 'err');
    } catch (x) { setState('err'); }
  };
  const inp = { width: '100%', boxSizing: 'border-box', padding: '12px 14px', borderRadius: 10, border: '1px solid var(--line-300)', background: '#fff', color: 'var(--ink-900)', WebkitTextFillColor: 'var(--ink-900)', colorScheme: 'light', appearance: 'auto', font: '15px/1.2 var(--font-body)' };
  const lab = { display: 'block', marginBottom: 6, font: 'var(--weight-semibold) 11px/1 var(--font-body)', letterSpacing: '0.12em', textTransform: 'uppercase', color: 'var(--text-muted)' };
  return (
    <div onClick={onClose} style={{ position: 'fixed', inset: 0, zIndex: 60, background: 'rgba(58,51,43,0.55)', display: 'flex', alignItems: 'center', justifyContent: 'center', padding: 16, overflowY: 'auto' }}>
      <div onClick={(e) => e.stopPropagation()} role="dialog" aria-modal="true" style={{ width: '100%', maxWidth: 440, background: 'var(--surface-page)', borderRadius: 'var(--radius-lg)', padding: '28px 24px', boxShadow: 'var(--shadow-lg)', margin: 'auto' }}>
        {state === 'done' ? (
          <div style={{ textAlign: 'center', padding: '12px 0' }}>
            <h2 style={{ margin: '0 0 10px', font: 'var(--weight-semibold) 28px/1.1 var(--font-display)', color: 'var(--text-heading)' }}>{r.okTitle}</h2>
            <p style={{ margin: '0 0 22px', color: 'var(--text-muted)', lineHeight: 1.6 }}>{r.ok}</p>
            <button type="button" onClick={onClose} style={{ cursor: 'pointer', border: 0, borderRadius: 'var(--radius-pill)', padding: '12px 26px', background: 'var(--navy-800)', color: '#fff', font: 'var(--weight-semibold) 12px/1 var(--font-body)', letterSpacing: '0.1em', textTransform: 'uppercase' }}>{r.close}</button>
          </div>
        ) : (
          <form onSubmit={submit}>
            <h2 style={{ margin: '0 0 8px', font: 'var(--weight-semibold) 28px/1.1 var(--font-display)', color: 'var(--text-heading)' }}>{r.title}</h2>
            <p style={{ margin: '0 0 20px', color: 'var(--text-muted)', fontSize: 14, lineHeight: 1.55 }}>{r.sub}</p>
            <div style={{ display: 'grid', gap: 14 }}>
              <div><label style={lab}>{r.name}</label><input style={inp} required maxLength={80} value={f.name} onChange={set('name')} autoComplete="name" /></div>
              <div><label style={lab}>{r.phone}</label><input style={inp} required type="tel" maxLength={30} value={f.phone} onChange={set('phone')} autoComplete="tel" placeholder="+355 …" /></div>
              <div style={{ display: 'grid', gridTemplateColumns: narrow ? '1fr 1fr' : '1.3fr 1fr 0.8fr', gap: 10 }}>
                <div style={narrow ? { gridColumn: '1 / -1' } : undefined}><label style={lab}>{r.date}</label><input style={inp} required type="date" min={FUMO_OPENING.date} value={f.date} onChange={set('date')} /></div>
                <div><label style={lab}>{r.time}</label><select style={inp} value={f.time} onChange={set('time')}>{times.map((x) => <option key={x}>{x}</option>)}</select></div>
                <div><label style={lab}>{r.guests}</label><select style={inp} value={f.guests} onChange={set('guests')}>{Array.from({ length: 12 }, (_, i) => i + 1).map((x) => <option key={x}>{x}</option>)}</select></div>
              </div>
              <div><label style={lab}>{r.note}</label><textarea style={{ ...inp, minHeight: 70, resize: 'vertical' }} maxLength={300} value={f.note} onChange={set('note')} /></div>
            </div>
            {(state === 'err' || state === 'rate') ? <p style={{ margin: '14px 0 0', color: '#b3261e', fontSize: 13 }}>{state === 'rate' ? r.rate : r.err}</p> : null}
            <div style={{ display: 'flex', gap: 10, marginTop: 20 }}>
              <button type="submit" disabled={state === 'sending'} style={{ flex: 1, cursor: 'pointer', border: 0, borderRadius: 'var(--radius-pill)', padding: '14px 18px', background: 'var(--gold-500)', color: 'var(--navy-900)', font: 'var(--weight-semibold) 12px/1 var(--font-body)', letterSpacing: '0.1em', textTransform: 'uppercase', opacity: state === 'sending' ? 0.6 : 1 }}>{state === 'sending' ? r.sending : r.send}</button>
              <button type="button" onClick={onClose} style={{ cursor: 'pointer', borderRadius: 'var(--radius-pill)', padding: '14px 18px', border: '1px solid var(--line-300)', background: 'transparent', color: 'var(--text-muted)', font: 'var(--weight-semibold) 12px/1 var(--font-body)', letterSpacing: '0.1em', textTransform: 'uppercase' }}>{r.close}</button>
            </div>
          </form>
        )}
      </div>
    </div>
  );
}

Object.assign(window, { Countdown, ReserveModal });
