'use client';

import type { LayoverDrawerContext } from '@/services/flights/layoverDisplay';
import { layoverKey } from '@/services/flights/layoverScope';
import { useLayoverDrawer } from './useLayoverDrawer';
import { usePrefetchLayoverAirport } from './useLayoverAirport';
import { useLayoverAvailability } from './useLayoverAvailability';
import './layover-drawer.css';

export interface KnowYourLayoverLinkProps {
  layover: LayoverDrawerContext;
  /**
   * `FlightData.sliceKeys[legIndex]`, falling back to the offer id. Scopes the
   * fragment to this exact stop so Back closes this drawer and not another
   * card's — see services/flights/layoverScope.
   */
  sliceKey: string;
  /** Index into the leg's `layovers`. */
  layoverIndex: number;
  /** Where this link sits, for analytics and for the compact tooltip variant. */
  variant?: 'inline' | 'compact';
  className?: string;
}

/**
 * "Know your layover airport ›" — the drawer's entry point.
 *
 * A button rather than an anchor. It looks like a link and it does put a
 * fragment in the address bar, but an `<a href="#…">` would hand the browser a
 * fragment that matches no element, and browsers disagree about whether that
 * scrolls the page. The button pushes the same history entry deliberately.
 *
 * It does **not** render the drawer. One host in the root layout does that, so
 * the panel survives its trigger being unmounted — which the results tooltip
 * does to this link the instant the pointer leaves it.
 *
 * It removes itself once the airport is *known* to have nothing to show — from
 * the batched, cache-only availability lookup that coalesces every link on the
 * page into one request, or from a full summary once one has been fetched.
 * "Unknown" keeps the link, because a missing link that should be there is
 * worse than a link that opens onto an honest "no information" state.
 */
export default function KnowYourLayoverLink({
  layover,
  sliceKey,
  layoverIndex,
  variant = 'inline',
  className = '',
}: KnowYourLayoverLinkProps) {
  const iataCode = layover.airportCode;
  const key = layoverKey(iataCode, { sliceKey, layoverIndex });
  const { isOpen, open } = useLayoverDrawer(key, layover);
  const prefetch = usePrefetchLayoverAirport();

  // One reactive source of truth. The batched cache-only lookup answers for the
  // whole page; a full summary that comes back unavailable writes its verdict
  // back into the same store (see LayoverAirportDrawer), so both paths converge
  // here and both re-render the link.
  const availability = useLayoverAvailability(iataCode);
  const knownUnavailable = availability === false;

  const warm = () => prefetch(iataCode);

  // Hidden, but only once we actually know. Never hidden while the drawer it
  // opened is showing — the panel is rendered by LayoverDrawerHost and would
  // survive, but the link's aria-expanded would start lying.
  if (knownUnavailable && !isOpen) return null;

  const label = variant === 'compact' ? 'Know more' : 'Know your layover airport';

  return (
    <button
      type="button"
      className={`layover-link layover-link--${variant} ${className}`.trim()}
      onClick={open}
      onMouseEnter={warm}
      onFocus={warm}
      aria-haspopup="dialog"
      aria-expanded={isOpen}
    >
      <span>{label}</span>
      <svg width={14} height={14} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth={2.5} strokeLinecap="round" strokeLinejoin="round" aria-hidden="true">
        <path d="m9 18 6-6-6-6" />
      </svg>
    </button>
  );
}
