"use client";

import { useCallback, useEffect, useLayoutEffect, useRef, useState } from "react";
import { createPortal } from "react-dom";
import { Info } from "lucide-react";
import { useIsClient } from "@/lib/useIsClient";

/**
 * The rate disclosure beside an indicative converted fee.
 *
 * WHY IT IS PORTALLED AND FIXED
 * The policy table lives inside `.table-responsive`, whose `overflow-x: auto`
 * establishes a clipping context: an absolutely-positioned panel is cut off by
 * it and the row gains a scrollbar instead of the panel escaping. Rendering
 * into `document.body` with `position: fixed` puts it above everything,
 * clipped by nothing — which is how a tooltip is expected to behave.
 *
 * WHY NOT A BOOTSTRAP POPOVER
 * Bootstrap's bundle loads `afterInteractive` on this route, so a popover
 * trigger is inert for the first moments after paint — and a control that
 * silently does nothing when pressed is worse than one that is not there.
 *
 * HOVER VERSUS TAP
 * Pointer-capable devices open it on hover, as a tooltip should. Touch devices
 * have no hover, so there it is a tap. Keyboard focus opens it in both cases —
 * the trigger is a real <button>, which is what makes that possible at all.
 *
 * WHY THE PANEL IS HOVERABLE
 * It carries the provider attribution link our licence requires, so it cannot
 * be inert: a link inside a `pointer-events: none` panel is unclickable. The
 * panel therefore keeps itself open while hovered, and closing is delayed
 * briefly so the cursor can cross the gap between trigger and panel without it
 * vanishing en route.
 */
export default function FxRateInfo({
  filedCurrency,
  convertedCurrency,
  rate,
  asOf,
  panelId,
}: {
  filedCurrency: string;
  convertedCurrency: string;
  rate: string;
  asOf: string;
  panelId: string;
}) {
  const [open, setOpen] = useState(false);
  const [coords, setCoords] = useState<{ top: number; left: number } | null>(null);
  const triggerRef = useRef<HTMLButtonElement>(null);
  const panelRef = useRef<HTMLDivElement>(null);
  const closeTimer = useRef<ReturnType<typeof setTimeout> | null>(null);

  const cancelClose = useCallback(() => {
    if (closeTimer.current) clearTimeout(closeTimer.current);
    closeTimer.current = null;
  }, []);

  const show = useCallback(() => {
    cancelClose();
    setOpen(true);
  }, [cancelClose]);

  /** Long enough to cross the 8px gap to the panel, short enough not to linger. */
  const hide = useCallback(() => {
    cancelClose();
    closeTimer.current = setTimeout(() => setOpen(false), 140);
  }, [cancelClose]);

  useEffect(() => cancelClose, [cancelClose]);

  // Portals need a DOM: there is none on the server, nor during hydration.
  const mounted = useIsClient();

  /**
   * True on devices with a real pointer. Read at interaction time rather than
   * from a width breakpoint — a narrow desktop window still has a mouse, and a
   * large tablet still does not.
   */
  const canHover = useCallback(
    () =>
      typeof window !== "undefined" &&
      window.matchMedia("(hover: hover) and (pointer: fine)").matches,
    []
  );

  /**
   * Anchor to the trigger's rect in viewport coordinates.
   *
   * Prefers below, flips above when the panel would run off the bottom, and
   * clamps horizontally so it can never sit outside the viewport — a fee near
   * the right edge of a phone-width table would otherwise push it off-screen.
   */
  const position = useCallback(() => {
    const trigger = triggerRef.current;
    const panel = panelRef.current;
    if (!trigger) return;

    const rect = trigger.getBoundingClientRect();
    const width = panel?.offsetWidth ?? 240;
    const height = panel?.offsetHeight ?? 96;
    const GAP = 8;
    const MARGIN = 8;

    const flipAbove = rect.bottom + GAP + height > window.innerHeight && rect.top - GAP - height > 0;

    const left = Math.min(
      Math.max(MARGIN, rect.left + rect.width / 2 - width / 2),
      window.innerWidth - width - MARGIN
    );
    const top = flipAbove ? rect.top - GAP - height : rect.bottom + GAP;

    setCoords({ top, left });
  }, []);

  useLayoutEffect(() => {
    if (open) position();
  }, [open, position]);

  useEffect(() => {
    if (!open) return;

    const close = () => setOpen(false);
    const onKeyDown = (event: KeyboardEvent) => {
      if (event.key === "Escape") close();
    };
    const onPointerDown = (event: MouseEvent | TouchEvent) => {
      const target = event.target as Node;
      if (triggerRef.current?.contains(target) || panelRef.current?.contains(target)) return;
      close();
    };

    document.addEventListener("keydown", onKeyDown);
    document.addEventListener("mousedown", onPointerDown);
    document.addEventListener("touchstart", onPointerDown);
    // A fixed panel does not travel with the page, so it is repositioned rather
    // than left stranded beside where the trigger used to be. Capture phase
    // catches scrolling inside the table as well as the window.
    window.addEventListener("scroll", position, true);
    window.addEventListener("resize", position);

    return () => {
      document.removeEventListener("keydown", onKeyDown);
      document.removeEventListener("mousedown", onPointerDown);
      document.removeEventListener("touchstart", onPointerDown);
      window.removeEventListener("scroll", position, true);
      window.removeEventListener("resize", position);
    };
  }, [open, position]);

  const panel = (
    <div
      id={panelId}
      ref={panelRef}
      role="tooltip"
      className="policy-fx-tooltip"
      style={{ top: coords?.top ?? 0, left: coords?.left ?? 0, visibility: coords ? "visible" : "hidden" }}
      onMouseEnter={() => canHover() && show()}
      onMouseLeave={() => canHover() && hide()}
    >
      {/* The answer the reader opened this for — the only line at full weight. */}
      <span className="d-block policy-fx-tooltip__rate">
        1 {convertedCurrency} = {rate} {filedCurrency}
      </span>

      <span className="d-block policy-fx-tooltip__meta">Updated {formatAsOf(asOf)}</span>

      <span className="d-block policy-fx-tooltip__meta">
        The final amount may vary based on your bank&apos;s exchange rate.
      </span>

      {/* Required by the rate provider's licence. Kept to the smallest tier and
          below a rule, so it reads as a credit rather than as information the
          traveller needs to act on. */}
      <a
        className="policy-fx-tooltip__credit"
        href="https://www.exchangerate-api.com"
        target="_blank"
        rel="noopener noreferrer"
      >
        Rates By Exchange Rate API
      </a>
    </div>
  );

  return (
    <>
      <button
        type="button"
        ref={triggerRef}
        className="policy-fx-info__trigger"
        aria-describedby={open ? panelId : undefined}
        // Names the control by what it reveals — "info" alone tells a screen
        // reader nothing about which of the many fees on this page it explains.
        aria-label={`Exchange rate used for the ${convertedCurrency} estimate`}
        onMouseEnter={() => canHover() && show()}
        onMouseLeave={() => canHover() && hide()}
        onFocus={show}
        onBlur={hide}
        // On a pointer device hover already governs this, and a click that
        // closed what the cursor is still hovering reads as a broken control.
        onClick={() => !canHover() && (open ? hide() : show())}
      >
        <Info size={14} aria-hidden="true" />
      </button>

      {open && mounted ? createPortal(panel, document.body) : null}
    </>
  );
}

/**
 * "2026-09-23T00:02:31Z" -> "23 Sep 2026, 00:02 UTC".
 *
 * Pinned to UTC rather than the reader's zone: the rate has one publication
 * moment, and localising it would make two people describing the same tooltip
 * disagree about when it was updated. Falls back to the raw string rather than
 * rendering "Invalid Date".
 */
function formatAsOf(asOf: string): string {
  const parsed = new Date(asOf);
  if (Number.isNaN(parsed.getTime())) return asOf;

  const date = parsed.toLocaleDateString("en-GB", {
    day: "numeric",
    month: "short",
    year: "numeric",
    timeZone: "UTC",
  });
  const time = parsed.toLocaleTimeString("en-GB", {
    hour: "2-digit",
    minute: "2-digit",
    timeZone: "UTC",
  });
  return `${date}, ${time} UTC`;
}
