'use client';

import dynamic from 'next/dynamic';
import { parseLayoverKey } from '@/services/flights/layoverScope';
import { closeLayoverDrawer, useLayoverDrawerState } from './useLayoverDrawer';

/**
 * The one place the layover drawer is rendered.
 *
 * Mounted once in the root layout, deliberately outside every card, modal and
 * tooltip on the site. The panel used to be rendered by the link that opened
 * it, which worked everywhere except the one place it mattered: the "Know more"
 * link inside the results tooltip. Radix unmounts tooltip content as soon as
 * the pointer leaves it, and that took the open drawer down with it — the panel
 * disappeared mid-read, and the page was left with whatever the interrupted
 * teardown had not finished restoring.
 *
 * Rendering from here also means exactly one drawer can exist at a time, which
 * matches the fragment: `#layover=` holds one value.
 *
 * Costs nothing until used — it renders null while closed, and the panel itself
 * is a separate chunk fetched on first open.
 */
const LayoverAirportDrawer = dynamic(() => import('./LayoverAirportDrawer'), { ssr: false });

export default function LayoverDrawerHost() {
  const { key, context } = useLayoverDrawerState();
  if (!key) return null;

  // A key arriving by URL rather than by click (a shared link, or Back onto an
  // entry we no longer hold a trip for) still names the airport, which is
  // enough for everything except the "your layover" chip.
  const parsed = parseLayoverKey(key);
  const iataCode = context?.airportCode ?? parsed?.iataCode;
  if (!iataCode) return null;

  return (
    <LayoverAirportDrawer
      key={key}
      iataCode={iataCode}
      layover={context}
      isOpen
      onClose={closeLayoverDrawer}
    />
  );
}
