'use client';

import { useCallback, useEffect, useRef, useState } from 'react';
import { useSearchParams } from 'next/navigation';
import FlightSearchFormV3 from './v3/FlightSearchFormV3';
import FlightSearchSummaryBar from './FlightSearchSummaryBar';
import { parseItinerary } from '@/services/flights/searchUrl';
import { OPEN_SEARCH_EDIT_EVENT, type OpenSearchEditDetail } from './searchEditEvents';
import './flight-sticky-bar.css';

/**
 * Fallback only — the real offsets are measured at runtime below.
 *
 * A hardcoded 62 was wrong twice over: `.wrapper { padding-top }` is 62px on
 * desktop but 50px and 47px at two narrower breakpoints, and the header's own
 * rendered height is not exactly its wrapper's padding — which is where the
 * thin gap between the header and this bar came from.
 */
const FALLBACK_HEADER_PX = 62;

interface FlightSearchStickyBarProps {
  /** Server-resolved code -> {city, country}, so fields show real names on first paint. */
  initialLocationNames?: Record<string, { city: string; country: string }>;
}

/**
 * The flight search form, pinned under the site header once the hero panel has
 * scrolled away.
 *
 * It renders the real `FlightSearchFormV3` in its compact variant rather than a
 * summary with a Modify button: every field stays editable, which is the whole
 * point of keeping the search on screen while reading results. The hero panel
 * is untouched and still renders the default variant.
 *
 * Fixed rather than sticky, so it costs no layout space while the hero panel is
 * still on screen.
 */
export default function FlightSearchStickyBar({ initialLocationNames }: FlightSearchStickyBarProps) {
  const searchParams = useSearchParams();
  const sentinelRef = useRef<HTMLDivElement>(null);
  const rowRef = useRef<HTMLDivElement>(null);
  const [pinned, setPinned] = useState(false);
  /**
   * Below lg this bar is the only search UI on the page — the hero panel is
   * hidden there — so it is always on screen rather than waiting for a scroll.
   * Tracked in JS as well as CSS because `inert` below has to agree with what
   * the media query is showing; a bar that is visible but inert is worse than
   * one that is simply absent.
   */
  const [isCompactViewport, setIsCompactViewport] = useState(false);
  const [editOpen, setEditOpen] = useState(false);
  /** Smart Filters' best guess at a destination/date change, shown as a
   *  suggestion banner inside the sheet — never applied without the
   *  traveller confirming it through the real form. */
  const [editSeed, setEditSeed] = useState<OpenSearchEditDetail | null>(null);

  // Lets Smart Filters (a sibling, not an ancestor — see searchEditEvents.ts)
  // open this same sheet a manual Edit tap opens.
  useEffect(() => {
    const onOpenEdit = (event: Event) => {
      const detail = (event as CustomEvent<OpenSearchEditDetail>).detail;
      setEditSeed(detail ?? null);
      setEditOpen(true);
    };
    window.addEventListener(OPEN_SEARCH_EDIT_EVENT, onOpenEdit);
    return () => window.removeEventListener(OPEN_SEARCH_EDIT_EVENT, onOpenEdit);
  }, []);

  useEffect(() => {
    const query = window.matchMedia('(max-width: 991.98px)');
    const sync = () => setIsCompactViewport(query.matches);
    sync();
    query.addEventListener('change', sync);
    return () => query.removeEventListener('change', sync);
  }, []);

  /**
   * Measure the fixed chrome and publish it, so nothing else has to guess.
   *
   * `--flight-header-h` is where this bar pins; `--flight-chrome-h` is header +
   * this bar, which is where anything below it must start. The filter sidebar
   * was pinned at a hardcoded 68px and ended up underneath this bar, hiding its
   * own "Filters" heading.
   *
   * Both site headers are in the DOM at once and CSS hides one per breakpoint,
   * so the visible one is whichever measures non-zero.
   *
   * The ROW is measured, not the whole bar: a multi-city leg editor opening
   * underneath must overlay the results, not shove the sidebar down and back.
   */
  useEffect(() => {
    const root = document.documentElement;
    const headers = Array.from(document.querySelectorAll<HTMLElement>('header.fixed-top'));

    const measure = () => {
      const headerH =
        headers.reduce((max, el) => Math.max(max, el.getBoundingClientRect().height), 0) ||
        FALLBACK_HEADER_PX;
      const rowH = rowRef.current?.getBoundingClientRect().height ?? 0;
      root.style.setProperty('--flight-header-h', `${Math.round(headerH)}px`);
      root.style.setProperty('--flight-chrome-h', `${Math.round(headerH + rowH)}px`);
    };

    measure();
    const observer = new ResizeObserver(measure);
    if (rowRef.current) observer.observe(rowRef.current);
    headers.forEach((el) => observer.observe(el));
    window.addEventListener('resize', measure);

    return () => {
      observer.disconnect();
      window.removeEventListener('resize', measure);
      root.style.removeProperty('--flight-header-h');
      root.style.removeProperty('--flight-chrome-h');
    };
  }, []);

  /**
   * A zero-height sentinel left where the hero panel ends. Once it crosses
   * above the header line the panel is gone and this bar takes over.
   *
   * IntersectionObserver rather than a scroll listener: this fires twice per
   * page, where a listener would run every frame to answer the same question.
   * The margin is read from the published variable so it tracks the real header
   * height at every breakpoint.
   */
  useEffect(() => {
    const el = sentinelRef.current;
    if (!el) return;
    const headerH =
      parseFloat(getComputedStyle(document.documentElement).getPropertyValue('--flight-header-h')) ||
      FALLBACK_HEADER_PX;
    const observer = new IntersectionObserver(
      ([entry]) => setPinned(!entry.isIntersecting),
      { rootMargin: `-${headerH}px 0px 0px 0px`, threshold: 0 },
    );
    observer.observe(el);
    return () => observer.disconnect();
  }, []);

  // Nothing searched for yet — there is no journey for the bar to be about.
  if (parseItinerary(searchParams.get('itinerary')).length === 0) return null;

  const active = isCompactViewport || pinned;

  return (
    <>
      <div ref={sentinelRef} aria-hidden="true" className="flight-sticky-sentinel" />

      <div
        className={`flight-sticky-bar${active ? ' is-pinned' : ''}`}
        /*
         * `inert`, not `hidden`. The bar has to stay measurable so its height
         * can be published for the sidebar below it, and a display:none element
         * measures zero. inert takes it out of the tab order and the
         * accessibility tree just as effectively.
         */
        inert={!active}
        aria-hidden={!active}
      >
        <div ref={rowRef} className="container webNewContent flight-sticky-bar__inner">
          {/* Both are in the DOM and CSS shows one, so `rowRef` always measures
              whichever is visible — the hidden one contributes no height, and
              `--flight-chrome-h` stays correct at every breakpoint without this
              component having to know which layout won. */}
          <div className="flight-sticky-bar__wide">
            <FlightSearchFormV3 variant="compact" initialLocationNames={initialLocationNames} />
          </div>
          <div className="flight-sticky-bar__narrow">
            <FlightSearchSummaryBar
              initialLocationNames={initialLocationNames}
              onEdit={() => setEditOpen(true)}
            />
          </div>
        </div>
      </div>

      {/* A drawer over the results, not a page: the traveller is amending a
          search, not leaving the list, and the dimmed results behind say so.
          Mounted only while open so the form does not run two instances of its
          own state at once. */}
      {editOpen ? (
        <FlightSearchEditSheet
          initialLocationNames={initialLocationNames}
          seed={editSeed}
          onClose={() => {
            setEditOpen(false);
            setEditSeed(null);
          }}
        />
      ) : null}
    </>
  );
}

/** Must match the transition duration in flight-sticky-bar.css. */
const SHEET_ANIMATION_MS = 260;

/**
 * The mobile edit drawer: the ordinary search form, slid down from the top.
 *
 * Down from the top rather than up from the bottom, and only as tall as the
 * form needs, because the results stay visible underneath it — dimmed, but
 * there. That is the difference between amending a search and being taken to a
 * different page, and it is what the traveller is actually doing.
 *
 * Deliberately the default form variant, not the compact one: the compact
 * layout exists to fit a desktop row, while the default is the layout every
 * traveller already used to get here.
 */
function FlightSearchEditSheet({
  initialLocationNames,
  seed,
  onClose,
}: {
  initialLocationNames?: Record<string, { city: string; country: string }>;
  /** Smart Filters' best guess, if that's what opened this sheet — shown as a
   *  banner, never applied to the form directly (see searchEditEvents.ts). */
  seed?: OpenSearchEditDetail | null;
  onClose: () => void;
}) {
  /**
   * Two states, because a drawer has to animate both ways.
   *
   * `entered` flips on one frame after mount so the browser has a starting
   * position to transition *from* — set in the same paint and it simply appears
   * at its destination. `leaving` plays the reverse before the parent unmounts
   * it, which is the half every dismissable panel forgets.
   */
  const [entered, setEntered] = useState(false);
  const [leaving, setLeaving] = useState(false);
  /**
   * Set once the slide has finished, to drop the transform.
   *
   * A transformed element is the containing block for its `position: fixed`
   * descendants, and mobile browsers anchor a native <select> popup against it
   * — which is what put the Cabin Class menu somewhere other than beside its
   * own field. An identity transform still does it, so the transform has to
   * actually go once it has stopped being needed.
   */
  const [settled, setSettled] = useState(false);

  useEffect(() => {
    const frame = requestAnimationFrame(() => setEntered(true));
    const timer = setTimeout(() => setSettled(true), SHEET_ANIMATION_MS);
    return () => {
      cancelAnimationFrame(frame);
      clearTimeout(timer);
    };
  }, []);

  // Held in a ref and cleared on unmount: a drawer closed by submitting the
  // form navigates away mid-animation, and a timer still pointing at the old
  // page's setState is the kind of thing that only shows up as a stray warning
  // weeks later. Guarded against a double-tap on close, too.
  const closeTimer = useRef<ReturnType<typeof setTimeout> | null>(null);
  useEffect(() => () => {
    if (closeTimer.current) clearTimeout(closeTimer.current);
  }, []);

  const startClose = useCallback(() => {
    if (closeTimer.current) return;
    setLeaving(true);
    closeTimer.current = setTimeout(onClose, SHEET_ANIMATION_MS);
  }, [onClose]);

  /**
   * Bring a panel into view when it opens.
   *
   * The panels expand in flow now rather than floating (see the note on
   * `.fs-dropdown` in flight-sticky-bar.css), which fixes them being clipped —
   * but a field near the bottom of the drawer then opens its list below the
   * fold, which looks like nothing happened. Scrolling the opened field to the
   * top of the drawer puts the field and its list on screen together.
   *
   * Watched via the `open` class the form already toggles, so the form needs
   * no knowledge of the drawer it happens to be rendered in.
   */
  const bodyRef = useRef<HTMLDivElement>(null);
  useEffect(() => {
    const body = bodyRef.current;
    if (!body) return;

    const observer = new MutationObserver((records) => {
      for (const record of records) {
        const el = record.target as HTMLElement;
        if (!el.classList?.contains('fs-field') || !el.classList.contains('open')) continue;
        // After the panel has been laid out, or it scrolls to the field's
        // old height and stops short of the list underneath it.
        requestAnimationFrame(() => el.scrollIntoView({ block: 'start', behavior: 'smooth' }));
        return;
      }
    });

    observer.observe(body, { attributes: true, attributeFilter: ['class'], subtree: true });
    return () => observer.disconnect();
  }, []);

  // The page behind must not scroll while the drawer is over it — on iOS that
  // reads as the drawer itself refusing to scroll.
  useEffect(() => {
    const previous = document.body.style.overflow;
    document.body.style.overflow = 'hidden';
    return () => {
      document.body.style.overflow = previous;
    };
  }, []);

  useEffect(() => {
    const onKey = (event: KeyboardEvent) => {
      if (event.key === 'Escape') startClose();
    };
    document.addEventListener('keydown', onKey);
    return () => document.removeEventListener('keydown', onKey);
  }, [startClose]);

  const openClass = entered && !leaving ? ' is-open' : '';
  const settledClass = settled && !leaving ? ' is-settled' : '';

  return (
    <>
      {/* Dismisses on tap, like every drawer — but not a <button>: it wraps no
          label, and the same action is on the close control in the header,
          which is where a keyboard or screen reader will find it. */}
      <div
        className={`flight-edit-backdrop${openClass}`}
        onClick={startClose}
        aria-hidden="true"
      />
      <div
        className={`flight-edit-sheet${openClass}${settledClass}`}
        role="dialog"
        aria-modal="true"
        aria-label="Edit search"
      >
        <div className="flight-edit-sheet__head">
          <span className="flight-edit-sheet__title">Edit search</span>
          <button
            type="button"
            className="flight-edit-sheet__close"
            onClick={startClose}
            aria-label="Close edit search"
          >
          <svg width={20} height={20} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth={2} strokeLinecap="round" aria-hidden="true">
              <path d="M18 6 6 18" />
              <path d="m6 6 12 12" />
            </svg>
          </button>
        </div>
        <div className="flight-edit-sheet__body" ref={bodyRef}>
          {seed && (seed.destination || seed.departDate || seed.returnDate) ? (
            <div className="flight-edit-sheet__seed-banner" role="status">
              Smart Filters suggests
              {seed.destination ? <> flying to <strong>{seed.destination}</strong></> : null}
              {seed.departDate ? <> on <strong>{seed.departDate}</strong></> : null}
              {seed.returnDate ? <> back <strong>{seed.returnDate}</strong></> : null}
              — update the fields below to confirm.
            </div>
          ) : null}
          {/* Submitting navigates to the new results, which unmounts this
              drawer with the page it belongs to — so there is no "close on
              search" to wire up, and none that could fire before the
              navigation. */}
          <FlightSearchFormV3 initialLocationNames={initialLocationNames} />
        </div>
      </div>
    </>
  );
}
