'use client';

import { createPortal } from 'react-dom';
import { Minus, X } from 'lucide-react';
import { useIsClient } from '@/lib/useIsClient';
import AirlineLogo from './AirlineLogo';
import { formatFlightMoney } from '@/services/flights/formatPrice';
import { MAX_COMPARE, MIN_COMPARE, type CompareEntry } from '@/store/slices/flightCompare.slice';
import './flight-compare.css';

/**
 * The flights set aside to compare, and the way into the comparison.
 *
 * One component for both layouts. Below `md` it is a bar pinned to the bottom
 * of the viewport that expands upward; above it, a panel docked bottom-right.
 * The difference is CSS — the markup, the state and the actions are identical,
 * because two implementations of "the tray" is how the two would come to
 * disagree about what is in it.
 *
 * It appears with the first flight and leaves with the last: an empty tray is
 * furniture explaining a feature nobody has started using.
 *
 * WHY IT IS PORTALLED
 * It is rendered from inside the results column, which is a Bootstrap `.row`.
 * `.row > *` sets `width: 100%; max-width: 100%` — the same specificity as
 * this component's own rule, and Bootstrap's stylesheet wins the tie on order,
 * so a fixed panel meant to be 23rem wide was being stretched across the
 * viewport. Winning that fight with a more specific selector would have been a
 * fix that lasted until the next layout change; a viewport-fixed overlay simply
 * does not belong inside a grid row. In `document.body` it is subject to no
 * grid, no overflow and no stacking context but its own.
 */
export default function CompareTray({
  entries,
  minimised,
  onToggleMinimised,
  onRemove,
  onClear,
  onCompare,
}: {
  entries: CompareEntry[];
  minimised: boolean;
  onToggleMinimised: (next: boolean) => void;
  onRemove: (sliceKey: string) => void;
  onClear: () => void;
  onCompare: () => void;
}) {
  // Portals need a DOM: there is none on the server, nor during hydration.
  const mounted = useIsClient();

  if (!mounted || entries.length === 0) return null;

  const canCompare = entries.length >= MIN_COMPARE;

  if (minimised) {
    return createPortal(
      <div className="compare-tray compare-tray--pill">
        <button
          type="button"
          className="compare-tray__pill-btn"
          onClick={() => onToggleMinimised(false)}
          aria-expanded={false}
        >
          Compare ({entries.length})
        </button>
      </div>,
      document.body,
    );
  }

  return createPortal(
    <section
      className="compare-tray"
      // Named, not just labelled "region": there may be other live furniture on
      // this page and "Selected flights" is what the traveller is looking for.
      aria-label={`Selected flights, ${entries.length} of ${MAX_COMPARE}`}
    >
      {/*
        A div, not <header>/<footer>. The global stylesheet owns those element
        names — custom-fixes.css paints every <footer> with a background image
        and lays an absolutely-positioned teal ::before over it, which both hid
        this tray's buttons and swallowed their clicks. The <section> and its
        <h2> already carry the structure; the landmark elements bought nothing
        and cost the CTAs.
      */}
      <div className="compare-tray__header">
        <h2 className="compare-tray__title">
          Selected flights ({entries.length}/{MAX_COMPARE})
        </h2>
        <button
          type="button"
          className="compare-tray__minimise"
          onClick={() => onToggleMinimised(true)}
          aria-label="Minimise selected flights"
          aria-expanded
        >
          <Minus size={16} aria-hidden="true" />
        </button>
      </div>

      <ul className="compare-tray__list">
        {entries.map((entry) => (
          <li key={entry.sliceKey} className="compare-tray__row">
            <AirlineLogo
              code={entry.airlineCode}
              name={entry.airlineName}
              className="compare-tray__logo"
            />

            <div className="compare-tray__detail">
              {/* title, so the full name is reachable when the column truncates it. */}
              <span className="compare-tray__airline" title={entry.airlineName}>
                {entry.airlineName}
              </span>

              <span className="compare-tray__times">
                {entry.departTime}
                <RouteLine stops={entry.stops} />
                {entry.arriveTime}
                {entry.arrivesNextDay && <sup className="compare-tray__nextday">+1</sup>}
              </span>

              <span className="compare-tray__meta">
                {entry.duration} ·{' '}
                {entry.stops === 0 ? 'Non-stop' : `${entry.stops} stop${entry.stops === 1 ? '' : 's'}`}
              </span>
            </div>

            <span className="compare-tray__price">
              {formatFlightMoney(entry.currency, entry.price)}
            </span>

            <button
              type="button"
              className="compare-tray__remove"
              onClick={() => onRemove(entry.sliceKey)}
              aria-label={`Remove ${entry.airlineName} ${entry.departTime} from comparison`}
            >
              <X size={14} aria-hidden="true" />
            </button>
          </li>
        ))}

        {/*
          Shown only on the one flight that cannot be compared yet.

          It used to appear for every free slot, so a tray holding two — enough
          to compare — still asked for another, reading as a requirement rather
          than the invitation it was. At the point comparison is possible the
          prompt is nagging for an optional third; below it, it names the one
          thing standing between the traveller and the Compare button, so it
          says "one more" rather than "another".
        */}
        {entries.length < MIN_COMPARE && (
          <li className="compare-tray__slot">Add one more flight to compare</li>
        )}
      </ul>

      <div className="compare-tray__footer">
        <button type="button" className="compare-tray__clear" onClick={onClear}>
          Clear all
        </button>

        <div className="compare-tray__cta">
          <button
            type="button"
            className="compare-tray__compare"
            onClick={canCompare ? onCompare : undefined}
            // Kept focusable so the hint below can explain itself — see
            // CompareToggle for the same reasoning.
            aria-disabled={!canCompare || undefined}
            aria-describedby={!canCompare ? 'compare-tray-hint' : undefined}
          >
            Compare flights
          </button>
          {!canCompare && (
            <span id="compare-tray-hint" className="compare-tray__hint" role="note">
              Add at least {MIN_COMPARE} flights.
            </span>
          )}
        </div>
      </div>
    </section>,
    document.body,
  );
}

/**
 * A miniature of the route, with a dot per stop.
 *
 * Decorative: the stop count is already written out beside it in words, so
 * this is hidden from assistive tech rather than announced as a second,
 * wordless version of the same fact.
 */
function RouteLine({ stops }: { stops: number }) {
  return (
    <span className="compare-tray__routeline" aria-hidden="true">
      <span className="compare-tray__routeline-track" />
      {Array.from({ length: Math.min(stops, 2) }).map((_, i) => (
        <span key={i} className="compare-tray__routeline-stop" />
      ))}
    </span>
  );
}
