/* global React, LOT_HOURS, Eyebrow */
/* American Dream Motors — appointment booking.
   Hotel/airline-style picker: day strip → color-coded time grid → phone → done.
   Colors reflect TYPICAL lot traffic (deterministic by weekday+hour) so the
   customer can pick a quiet time — never fabricated scarcity. */
const { useState, useMemo, useEffect } = React;

const BK_DAYNAMES = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'];
const BK_MONTHS = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
const BK_LEAD_MINUTES = 90; // soonest bookable slot — gives the desk time to pull it up front

const BK_DEMAND = {
  quiet:  { label: 'No wait',  cls: 'bk-quiet'  },
  steady: { label: 'Steady',   cls: 'bk-steady' },
  busy:   { label: 'Busiest',  cls: 'bk-busy'   },
};

/* Typical traffic at the lot — Saturdays and weekday evenings run hot,
   weekday mornings are wide open. */
function bkDemand(dow, h) {
  if (dow === 6) return h >= 13 && h < 15 ? 'steady' : 'busy';
  if (h >= 16) return 'busy';
  if (h === 12 || h === 13) return 'steady';
  return 'quiet';
}

function bkFmtHour(h) {
  if (h === 12) return '12 PM';
  return h > 12 ? (h - 12) + ' PM' : h + ' AM';
}

function bkBuildDays(now = new Date()) {
  const days = [];
  const openHours = [];
  for (let h = LOT_HOURS.open; h < LOT_HOURS.close; h++) openHours.push(h);
  for (let i = 0; i < 7; i++) {
    const d = new Date(now);
    d.setDate(now.getDate() + i);
    d.setHours(0, 0, 0, 0);
    const dow = d.getDay();
    const closed = LOT_HOURS.closedDays.includes(dow);
    const slots = closed ? [] : openHours.map(h => {
      const t = new Date(d);
      t.setHours(h, 0, 0, 0);
      const gone = t.getTime() < now.getTime() + BK_LEAD_MINUTES * 60000;
      return { h, iso: t.toISOString(), time: bkFmtHour(h), demand: bkDemand(dow, h), gone };
    });
    days.push({
      date: d,
      dow,
      closed,
      name: i === 0 ? 'Today' : i === 1 ? 'Tmrw' : BK_DAYNAMES[dow],
      num: d.getDate(),
      month: BK_MONTHS[d.getMonth()],
      full: `${BK_DAYNAMES[dow]} ${BK_MONTHS[d.getMonth()]} ${d.getDate()}`,
      open: slots.some(s => !s.gone),
      slots,
    });
  }
  return days;
}

function bkFormatPhone(raw) {
  const d = raw.replace(/\D/g, '').slice(0, 10);
  if (d.length < 4) return d;
  if (d.length < 7) return `(${d.slice(0, 3)}) ${d.slice(3)}`;
  return `(${d.slice(0, 3)}) ${d.slice(3, 6)}-${d.slice(6)}`;
}

function BookingLegend() {
  return (
    <div className="bk-legend" aria-hidden="true">
      <span><i className="bk-dot bk-dot-quiet"></i>No wait</span>
      <span><i className="bk-dot bk-dot-steady"></i>Steady</span>
      <span><i className="bk-dot bk-dot-busy"></i>Busiest</span>
    </div>
  );
}

/* ============ BOOKING WIDGET ============ */
function BookVisit({ vehicle = null, title = 'Pick a time. We’ll have it ready.' }) {
  const days = useMemo(() => bkBuildDays(), []);
  const firstOpen = Math.max(0, days.findIndex(d => d.open));
  const [dayIdx, setDayIdx] = useState(firstOpen);
  const [slot, setSlot] = useState(null);
  const [phone, setPhone] = useState('');
  const [state, setState] = useState('idle'); // idle | sending | done
  const day = days[dayIdx];
  const valid = slot && phone.replace(/\D/g, '').length >= 10;
  const vehicleLabel = vehicle ? `${vehicle.year} ${vehicle.make} ${vehicle.model} ${vehicle.trim}` : null;

  function pickDay(i) {
    if (days[i].closed || !days[i].open) return;
    setDayIdx(i);
    setSlot(null);
    window.dd && window.dd.track('booking_day_pick', { day: days[i].full });
  }

  function pickSlot(s) {
    if (s.gone) return;
    setSlot(s);
    window.dd && window.dd.track('booking_slot_pick', { day: day.full, time: s.time, demand: s.demand });
  }

  async function submit(e) {
    e.preventDefault();
    if (!valid || state !== 'idle') return;
    setState('sending');
    await window.adm.submitLead({
      intent: vehicle ? 'testdrive' : 'visit',
      channel: 'booking',
      phone,
      name: '',
      slot: `${day.full} · ${slot.time}`,
      slotIso: slot.iso,
      slotDemand: slot.demand,
      vehicleId: vehicle ? vehicle.id : null,
      vehicleLabel,
      vehicleStock: vehicle ? vehicle.stock : null,
      message: vehicleLabel
        ? `Booked ${day.full} at ${slot.time} to see the ${vehicleLabel} (stock ${vehicle.stock}).`
        : `Booked a lot visit for ${day.full} at ${slot.time}.`,
    });
    setTimeout(() => setState('done'), 450);
  }

  if (state === 'done') {
    return (
      <div className="bk bk-done-wrap">
        <div className="bk-done">
          <span className="bk-done-check" aria-hidden="true">✓</span>
          <div className="bk-done-t">{day.full} · {slot.time} — locked in.</div>
          <p className="bk-done-d">
            We&apos;ll text you to confirm{vehicleLabel ? ` and have the ${vehicle.year} ${vehicle.make} pulled up front, keys in it` : ' and meet you out front'}.
            If anything changes, you&apos;ll hear from us first.
          </p>
          <div className="bk-done-row">
            <a className="btn btn-sm" href="tel:540-450-5373">Call the lot</a>
            <a className="btn btn-sm btn-ghost" href="https://maps.google.com/?q=691+N+Loudoun+St,+Winchester,+VA+22601" target="_blank" rel="noopener noreferrer">Directions</a>
          </div>
        </div>
      </div>
    );
  }

  return (
    <form className="bk" onSubmit={submit}>
      <div className="bk-head">
        <span className="bk-t">{title}</span>
        <span className="bk-sub">20 seconds · no account</span>
      </div>

      {vehicleLabel && (
        <div className="lf-vehicle" style={{ marginTop: 2 }}>
          <span className="lf-vehicle-dot"></span>
          <span>{vehicleLabel}</span>
        </div>
      )}

      <div className="bk-days" role="tablist" aria-label="Pick a day">
        {days.map((d, i) => (
          <button type="button" key={d.full} role="tab" aria-selected={i === dayIdx}
            className={'bk-day' + (i === dayIdx ? ' active' : '') + (d.closed || !d.open ? ' closed' : '')}
            onClick={() => pickDay(i)} disabled={d.closed || !d.open}>
            <span className="bk-day-dow">{d.name}</span>
            <span className="bk-day-num">{d.num}</span>
            <span className="bk-day-tag">{d.closed ? 'Closed' : !d.open ? 'Done' : d.dow === 6 ? 'Busy' : 'Open'}</span>
          </button>
        ))}
      </div>

      <div className="bk-slots">
        {day.slots.map(s => {
          const dm = BK_DEMAND[s.demand];
          const active = slot && slot.iso === s.iso;
          return (
            <button type="button" key={s.iso}
              className={'bk-slot ' + dm.cls + (active ? ' active' : '') + (s.gone ? ' gone' : '')}
              onClick={() => pickSlot(s)} disabled={s.gone}
              aria-label={s.gone ? `${s.time} unavailable` : `${s.time}, usually ${dm.label.toLowerCase()}`}>
              <span className="bk-slot-time">{s.time}</span>
              <span className="bk-slot-tag">{s.gone ? '—' : dm.label}</span>
            </button>
          );
        })}
      </div>
      <BookingLegend />

      <div className={'bk-go' + (slot ? ' ready' : '')}>
        <input className="bk-phone" type="tel" inputMode="tel" autoComplete="tel"
          placeholder="Phone — we text the confirmation"
          value={phone} onChange={e => setPhone(bkFormatPhone(e.target.value))} />
        <button type="submit" className={'btn btn-primary bk-btn' + (valid ? '' : ' bk-off')} disabled={state === 'sending'}>
          {state === 'sending' ? '…' : slot ? `Lock in ${slot.time} →` : 'Pick a time above'}
        </button>
      </div>
      <p className="bk-fine">No spam. One text or call from a real person at the lot.</p>
    </form>
  );
}

/* ============ BOOK PAGE ============ */
function BookPage({ setPage }) {
  return (
    <div className="container" style={{ padding: '48px 0 110px' }}>
      <div className="book-grid">
        <div className="book-head">
          <Eyebrow num={1}>Book a visit</Eyebrow>
          <h1 className="display" style={{ fontSize: 'clamp(44px, 6.4vw, 92px)', lineHeight: 0.93, marginTop: 20, letterSpacing: '-0.025em' }}>
            Pick a time.<br/>We&apos;ll have it <em style={{ color: 'var(--accent)' }}>out front.</em>
          </h1>
          <p style={{ fontSize: 17, lineHeight: 1.65, color: 'var(--fg-mute)', marginTop: 22, maxWidth: 540 }}>
            Green means a quiet hour — you&apos;ll get the whole lot to yourself.
            Tell us when you&apos;re coming and the vehicle will be pulled up, keys in it,
            ready to drive. Bring your mechanic if you want. We&apos;ll wait.
          </p>
        </div>
        <div className="book-more">
          <div className="book-steps">
            {[
              ['01', 'Pick a day and time', 'Quiet, steady, or busy — your call.'],
              ['02', 'Drop your number', 'We text to confirm. That’s the whole form.'],
              ['03', 'Pull in', '691 N. Loudoun St. Your vehicle is out front.'],
            ].map(([n, t, d]) => (
              <div className="book-step" key={n}>
                <span className="process-num">/ {n}</span>
                <strong>{t}</strong>
                <span>{d}</span>
              </div>
            ))}
          </div>
          <div style={{ display: 'flex', gap: 10, marginTop: 26, flexWrap: 'wrap' }}>
            <a href="tel:540-450-5373" className="btn">Rather call? (540) 450-5373</a>
            <button type="button" className="btn btn-ghost" onClick={() => setPage('inventory')}>Browse first</button>
          </div>
        </div>
        <aside className="book-side">
          <BookVisit />
          <div className="book-hours mono">
            MON–SAT 10–6 · SUN CLOSED · 691 N. LOUDOUN ST, WINCHESTER, VA
          </div>
        </aside>
      </div>
    </div>
  );
}

Object.assign(window, { BookVisit, BookPage });
