/* Volaire — /search: results, date ribbon, filters, fare selection */

/* ---------- booking draft store (volaire.booking) ---------- */
const DRAFT_KEY = 'volaire.booking';
const EMPTY_DRAFT = {
  step: 1, tripType: 'round-trip', outbound: null, inbound: null, fareFamily: null,
  passenger: { salutation: 'Mme', firstName: '', lastName: '', dateOfBirth: '', nationality: '', email: '', phone: '', loyaltyNumber: '', createAccount: false },
  seats: [], extras: { checkedBags: 0, extraBags: 0, priority: false, meal: null, sportsEquipment: false },
  protection: null, payment: 'card', termsAccepted: false, privacyAccepted: false, pnr: null,
};
function loadDraft() {
  try {
    const d = JSON.parse(localStorage.getItem(DRAFT_KEY) || 'null');
    if (d && d.outbound) return Object.assign({}, EMPTY_DRAFT, d);
  } catch (e) { /* noop */ }
  return JSON.parse(JSON.stringify(EMPTY_DRAFT));
}
function saveDraft(d) { localStorage.setItem(DRAFT_KEY, JSON.stringify(d)); }
function clearDraft() { localStorage.removeItem(DRAFT_KEY); }
window.VolaireDraft = { loadDraft, saveDraft, clearDraft, EMPTY_DRAFT };

/* ---------- summary bar ---------- */
function SearchSummaryBar({ params, onEdit, editing }) {
  const { t, lang } = useLang();
  return (
    <div className="flex flex-wrap items-center gap-x-4 gap-y-1 rounded-xl border border-line bg-white px-4 py-3">
      <span className="flex items-center gap-2 text-sm font-bold tabular-nums tracking-tight text-ink">
        {params.from}<Icon name="arrowRight" size={14} className="text-muted"></Icon>{params.to}
      </span>
      <span className="text-sm capitalize text-muted">
        {L.fmtDateShort(params.depart, lang)}{params.type === 'round-trip' && params.return ? ' — ' + L.fmtDateShort(params.return, lang) : ''}
      </span>
      <span className="text-sm text-muted">· {t('home.search.onePassenger')} · {t('home.search.cabin.' + params.cabin)}</span>
      <button onClick={onEdit} className="ml-auto text-sm font-semibold text-cobalt hover:underline" aria-expanded={editing}>
        {t('search.summary.edit')}
      </button>
    </div>
  );
}

/* ---------- filters ---------- */
function Filters({ filters, setFilters, maxAvail }) {
  const { t } = useLang();
  const timeRanges = [
    { id: 'morning', label: '06:00 – 12:00', from: 6, to: 12 },
    { id: 'afternoon', label: '12:00 – 18:00', from: 12, to: 18 },
    { id: 'evening', label: '18:00 – 22:00', from: 18, to: 22 },
  ];
  return (
    <div className="flex flex-col gap-5">
      <fieldset>
        <legend className="text-xs font-bold uppercase tracking-wider text-muted">{t('search.filter.departureTime')}</legend>
        <div className="mt-2 flex flex-col gap-1.5">
          {timeRanges.map(function (r) {
            const on = filters.times.includes(r.id);
            return (
              <label key={r.id} className="flex cursor-pointer items-center gap-2 text-sm text-ink">
                <input type="checkbox" checked={on} className="h-4 w-4 rounded border-line text-cobalt focus:ring-cobalt"
                  onChange={function () {
                    setFilters(Object.assign({}, filters, { times: on ? filters.times.filter(function (x) { return x !== r.id; }) : filters.times.concat(r.id) }));
                  }} />
                <span className="tabular-nums">{r.label}</span>
              </label>
            );
          })}
        </div>
      </fieldset>
      <fieldset>
        <legend className="text-xs font-bold uppercase tracking-wider text-muted">{t('search.filter.stops')}</legend>
        <div className="mt-2 flex flex-col gap-1.5">
          {[{ v: 0, l: t('search.results.direct') }, { v: 1, l: t('search.results.oneStop') }].map(function (o) {
            const on = filters.stops.includes(o.v);
            return (
              <label key={o.v} className="flex cursor-pointer items-center gap-2 text-sm text-ink">
                <input type="checkbox" checked={on} className="h-4 w-4 rounded border-line text-cobalt focus:ring-cobalt"
                  onChange={function () {
                    setFilters(Object.assign({}, filters, { stops: on ? filters.stops.filter(function (x) { return x !== o.v; }) : filters.stops.concat(o.v) }));
                  }} />
                {o.l}
              </label>
            );
          })}
        </div>
      </fieldset>
      <fieldset>
        <legend className="text-xs font-bold uppercase tracking-wider text-muted">{t('search.filter.maxPrice')}</legend>
        <input type="range" min={39} max={maxAvail} value={filters.maxPrice}
          aria-label={t('search.filter.maxPrice')}
          className="mt-3 w-full accent-cobalt"
          onChange={function (e) { setFilters(Object.assign({}, filters, { maxPrice: +e.target.value })); }} />
        <p className="mt-1 text-sm font-semibold tabular-nums text-ink">{L.fmtEUR(filters.maxPrice)}</p>
      </fieldset>
    </div>
  );
}

/* ---------- leg section (outbound or return) ---------- */
function LegSection({ legKey, title, from, to, date, onDateChange, selection, onSelect, sectionRef }) {
  const { t, lang } = useLang();
  const [expanded, setExpanded] = useState(null);
  const [sort, setSort] = useState('price');
  const [filters, setFilters] = useState({ times: [], stops: [], maxPrice: 250 });
  const [drawer, setDrawer] = useState(false);

  const flights = useMemo(function () { return L.generateFlights(from, to, date); }, [from, to, date]);
  const filtered = useMemo(function () {
    let list = flights.slice();
    if (filters.times.length) {
      list = list.filter(function (f) {
        const h = new Date(f.departTime).getHours();
        return filters.times.some(function (id) {
          if (id === 'morning') return h >= 6 && h < 12;
          if (id === 'afternoon') return h >= 12 && h < 18;
          return h >= 18 && h <= 22;
        });
      });
    }
    if (filters.stops.length) list = list.filter(function (f) { return filters.stops.includes(f.stops); });
    list = list.filter(function (f) { return f.fares.light.price <= filters.maxPrice; });
    if (sort === 'price') list.sort(function (a, b) { return a.fares.light.price - b.fares.light.price; });
    else if (sort === 'earliest') list.sort(function (a, b) { return new Date(a.departTime) - new Date(b.departTime); });
    else list.sort(function (a, b) { return a.durationMin - b.durationMin; });
    return list;
  }, [flights, filters, sort]);

  return (
    <section ref={sectionRef} aria-label={title} className="scroll-mt-24">
      <div className="flex flex-wrap items-baseline justify-between gap-2">
        <h2 className="text-xl font-bold tracking-tight text-ink">{title}
          <span className="ml-2 text-sm font-medium capitalize text-muted">{L.fmtDateLong(date, lang)}</span>
        </h2>
        <div className="flex items-center gap-2">
          <button className="rounded-lg border border-line bg-white px-3 py-1.5 text-sm font-medium text-ink hover:border-cobalt lg:hidden"
            onClick={function () { setDrawer(true); }}>{t('search.filter.title')}</button>
          <label className="flex items-center gap-2 text-sm text-muted">
            <span className="hidden sm:inline">{t('search.sort.label')}</span>
            <select className="rounded-lg border border-line bg-white px-2 py-1.5 text-sm text-ink focus:border-cobalt focus:outline-none"
              value={sort} onChange={function (e) { setSort(e.target.value); }} aria-label={t('search.sort.label')}>
              <option value="price">{t('search.sort.price')}</option>
              <option value="earliest">{t('search.sort.earliest')}</option>
              <option value="duration">{t('search.sort.duration')}</option>
            </select>
          </label>
        </div>
      </div>
      <div className="mt-3"><DateRibbon from={from} to={to} selected={date} onPick={onDateChange}></DateRibbon></div>
      <div className="mt-4 grid gap-6 lg:grid-cols-[200px_1fr]">
        <aside className="hidden lg:block">
          <div className="sticky top-32 rounded-xl border border-line bg-white p-4">
            <Filters filters={filters} setFilters={setFilters} maxAvail={250}></Filters>
          </div>
        </aside>
        <div className="flex flex-col gap-3" aria-live="polite">
          {filtered.length === 0 ? (
            <div className="rounded-xl border border-line bg-white p-8 text-center">
              <p className="font-bold text-ink">{t('search.empty')}</p>
              <p className="mt-2 text-sm text-muted">{t('search.empty.alternatives')}</p>
              <div className="mt-3 flex justify-center gap-2">
                {[-1, 1, 2].map(function (d) {
                  const alt = L.addDays(date, d);
                  if (alt < L.todayISO(0)) return null;
                  return (
                    <button key={d} onClick={function () { onDateChange(alt); }}
                      className="rounded-lg border border-line px-3 py-1.5 text-sm font-medium capitalize text-cobalt hover:border-cobalt">
                      {L.fmtDateShort(alt, lang)}
                    </button>
                  );
                })}
              </div>
            </div>
          ) : filtered.map(function (f) {
            return (
              <FlightCard key={f.id} flight={f}
                expanded={expanded === f.id}
                selectedFare={selection && selection.flight.id === f.id ? selection.fare : null}
                onToggle={function () { setExpanded(expanded === f.id ? null : f.id); }}
                onSelectFare={function (fare) { onSelect(f, fare); setExpanded(null); }}></FlightCard>
            );
          })}
        </div>
      </div>
      {drawer ? (
        <div className="fixed inset-0 z-50 lg:hidden" role="dialog" aria-modal="true" aria-label={t('search.filter.title')}>
          <div className="absolute inset-0 bg-ink/40" onClick={function () { setDrawer(false); }}></div>
          <div className="absolute bottom-0 left-0 right-0 max-h-[80vh] overflow-auto rounded-t-2xl bg-white p-5">
            <div className="flex items-center justify-between">
              <h3 className="text-lg font-bold text-ink">{t('search.filter.title')}</h3>
              <button onClick={function () { setDrawer(false); }} aria-label={t('common.close')} className="rounded-lg p-1.5 text-muted hover:bg-page"><Icon name="cross" size={18}></Icon></button>
            </div>
            <div className="mt-4"><Filters filters={filters} setFilters={setFilters} maxAvail={250}></Filters></div>
            <button className="mt-5 w-full rounded-lg bg-cobalt py-3 text-sm font-bold text-white" onClick={function () { setDrawer(false); }}>{t('common.continue')}</button>
          </div>
        </div>
      ) : null}
    </section>
  );
}

/* ---------- search page ---------- */
function SearchPage() {
  const { t } = useLang();
  const route = useRoute();
  const q = route.query;
  const [editing, setEditing] = useState(false);
  const [dates, setDates] = useState({ depart: q.depart || L.todayISO(14), ret: q['return'] || L.todayISO(18) });
  const [outSel, setOutSel] = useState(null);   // { flight, fare }
  const [inSel, setInSel] = useState(null);
  const returnRef = useRef(null);
  const isRT = (q.type || 'round-trip') === 'round-trip';
  const params = { from: q.from || 'CDG', to: q.to || 'BCN', depart: dates.depart, 'return': dates.ret, cabin: q.cabin || 'economy', type: q.type || 'round-trip' };

  useEffect(function () {
    setDates({ depart: q.depart || L.todayISO(14), ret: q['return'] || L.todayISO(18) });
    setOutSel(null); setInSel(null);
  }, [q.from, q.to, q.depart, q['return'], q.type]);

  useEffect(function () {
    if (outSel && isRT && returnRef.current) {
      const top = returnRef.current.getBoundingClientRect().top + window.pageYOffset - 96;
      window.scrollTo({ top: top, behavior: 'smooth' });
    }
  }, [outSel != null]);

  const complete = outSel && (!isRT || inSel);
  const total = (outSel ? outSel.flight.fares[outSel.fare].price : 0) + (inSel ? inSel.flight.fares[inSel.fare].price : 0);

  function continueToBooking() {
    const d = JSON.parse(JSON.stringify(window.VolaireDraft.EMPTY_DRAFT));
    d.tripType = isRT ? 'round-trip' : 'one-way';
    d.outbound = outSel.flight;
    d.inbound = isRT ? inSel.flight : null;
    d.fareFamily = outSel.fare;
    d.step = 1;
    const s = L.getSession();
    if (s) d.passenger = Object.assign({}, d.passenger, L.MOCK_CUSTOMER, { createAccount: false });
    window.VolaireDraft.saveDraft(d);
    navigate('/booking');
  }

  return (
    <main className="mx-auto max-w-6xl px-4 pb-28 pt-6">
      <div className="sticky top-[105px] z-30 -mx-1 bg-page/95 px-1 py-2 backdrop-blur md:top-[118px]">
        <SearchSummaryBar params={params} editing={editing} onEdit={function () { setEditing(!editing); }}></SearchSummaryBar>
      </div>
      {editing ? (
        <div className="mt-3"><SearchWidget compact={true} initial={{ tripType: params.type, from: params.from, to: params.to, depart: params.depart, ret: params['return'], cabin: params.cabin }} onSearch={function () { setEditing(false); }}></SearchWidget></div>
      ) : null}
      <div className="mt-6 flex flex-col gap-10">
        <LegSection legKey="out" title={t('search.outbound')} from={params.from} to={params.to} date={dates.depart}
          onDateChange={function (d) { setDates(Object.assign({}, dates, { depart: d })); setOutSel(null); }}
          selection={outSel}
          onSelect={function (f, fare) { setOutSel({ flight: f, fare: fare }); }}></LegSection>
        {isRT && outSel ? (
          <LegSection legKey="in" sectionRef={returnRef} title={t('search.return')} from={params.to} to={params.from} date={dates.ret}
            onDateChange={function (d) { setDates(Object.assign({}, dates, { ret: d })); setInSel(null); }}
            selection={inSel}
            onSelect={function (f, fare) { setInSel({ flight: f, fare: fare }); }}></LegSection>
        ) : null}
      </div>
      {complete ? (
        <div className="fixed bottom-0 left-0 right-0 z-40 border-t border-line bg-white shadow-[0_-8px_30px_rgba(14,18,32,0.08)]">
          <div className="mx-auto flex max-w-6xl items-center justify-between gap-4 px-4 py-3">
            <div>
              <p className="text-xs font-semibold uppercase tracking-wide text-muted">{t('search.total')} · {t('home.search.onePassenger')}</p>
              <p className="text-2xl font-bold tabular-nums tracking-tight text-ink" aria-live="polite">{L.fmtEUR(total)}</p>
            </div>
            <button onClick={continueToBooking} className="rounded-lg bg-cobalt px-8 py-3 text-sm font-bold text-white hover:bg-cobaltDark">
              {t('search.continue')}
            </button>
          </div>
        </div>
      ) : null}
    </main>
  );
}

Object.assign(window, { SearchPage, SearchSummaryBar });
