'use client';

import * as Tooltip from '@radix-ui/react-tooltip';
import React, { useEffect, useRef, useState } from 'react';
import type { FlightAmenity, FlightAmenitySegmentGroup } from './types';
import FlightAmenityDetailIcon from './FlightAmenityDetailIcon';
import AirlineLogo from './AirlineLogo';

interface FlightAmenityListProps {
  groups: FlightAmenitySegmentGroup[];
  /** Quick-glance amenities from the fare; only their count is used for the label. */
  preview?: FlightAmenity[];
}

/**
 * The amenities entry on a flight leg — a quiet "Fare Benefits: N" text item that
 * matches the sibling "Cabin: …" / "Check-in: …" features, marked interactive
 * with a dashed underline. On hover it opens the full real breakdown, one
 * section per flight segment (a connection can genuinely change aircraft/cabin
 * between segments, so each gets its own list): a grey flight header (airline
 * logo + flight no. + route), then a two-column icon+label grid with chargeable
 * perks marked "(Chargeable)" in plain text.
 */
export default function FlightAmenityList({ groups, preview = [] }: FlightAmenityListProps) {
  /**
   * Whether this device points with a finger.
   *
   * A tooltip opens on hover, and a finger cannot hover — so on a phone this
   * control simply did nothing. Rather than swap in a different primitive for
   * touch, the same tooltip is driven in controlled mode: hover still opens it
   * on a mouse, and a tap opens it on a screen.
   *
   * `pointer: coarse` rather than a width breakpoint, because the question is
   * what the visitor is pointing with, not how wide their screen is — a touch
   * laptop needs the tap and a narrow desktop window does not.
   */
  const [isTouch, setIsTouch] = useState(false);
  const [open, setOpen] = useState(false);
  const triggerRef = useRef<HTMLSpanElement>(null);

  useEffect(() => {
    const query = window.matchMedia('(pointer: coarse)');
    const sync = () => setIsTouch(query.matches);
    sync();
    query.addEventListener('change', sync);
    return () => query.removeEventListener('change', sync);
  }, []);

  /**
   * Dismissal, which Radix normally provides and cannot here.
   *
   * In controlled mode its own outside-click and Escape handling routes
   * through `onOpenChange`, which is deliberately ignored on touch so a stray
   * hover event cannot drive the panel. That means owning both.
   */
  useEffect(() => {
    if (!isTouch || !open) return;

    const onPointerDown = (event: PointerEvent) => {
      const target = event.target as HTMLElement | null;
      if (triggerRef.current?.contains(target as Node)) return;
      // The panel is portalled out of this subtree, so containment cannot find
      // it — it is marked instead.
      if (target?.closest?.('[data-amenity-panel]')) return;
      setOpen(false);
    };
    const onKeyDown = (event: KeyboardEvent) => {
      if (event.key === 'Escape') setOpen(false);
    };

    document.addEventListener('pointerdown', onPointerDown);
    document.addEventListener('keydown', onKeyDown);
    return () => {
      document.removeEventListener('pointerdown', onPointerDown);
      document.removeEventListener('keydown', onKeyDown);
    };
  }, [isTouch, open]);

  const totalCount = groups.reduce((n, g) => n + g.amenities.length, 0);
  if (!totalCount && !preview.length) return null;

  const count = totalCount || preview.length;

  const trigger = (hoverable: boolean) => (
    <span
      ref={triggerRef}
      className={`amenities text-sm text-grey d-inline-flex align-items-center gap-1${hoverable ? ' cursor-pointer' : ''}`}
      style={hoverable ? { borderBottom: '1px dashed #c7ccd1' } : undefined}
      {...(hoverable && isTouch
        ? {
            role: 'button' as const,
            tabIndex: 0,
            'aria-expanded': open,
            onClick: (event: React.MouseEvent) => {
              // The row sits inside a clickable card; without this a tap would
              // open the panel and navigate away from it in the same gesture.
              event.preventDefault();
              event.stopPropagation();
              setOpen((v) => !v);
            },
          }
        : {})}
    >
      <svg xmlns="http://www.w3.org/2000/svg" width={15} height={15} viewBox="0 0 24 24" fill="none" stroke="#bdbdbd" strokeWidth={2} strokeLinecap="round" strokeLinejoin="round">
        <path d="M9.94 15.5A2 2 0 0 0 8.5 14.06l-6.14-1.58a.5.5 0 0 1 0-.96L8.5 9.94A2 2 0 0 0 9.94 8.5l1.58-6.14a.5.5 0 0 1 .96 0L14.06 8.5A2 2 0 0 0 15.5 9.94l6.14 1.58a.5.5 0 0 1 0 .96L15.5 14.06a2 2 0 0 0-1.44 1.44l-1.58 6.14a.5.5 0 0 1-.96 0z" />
      </svg>{' '}
      Fare Benefits: {count}
    </span>
  );

  if (!totalCount) return trigger(false);

  return (
    <Tooltip.Provider delayDuration={100}>
      {/* Controlled on touch only. On a mouse this stays uncontrolled so Radix
          keeps its own hover, focus, Escape and outside-click behaviour —
          there is nothing wrong with it there, and reimplementing it would be
          a second set of rules to keep in step. */}
      <Tooltip.Root
        {...(isTouch ? { open, onOpenChange: () => {} } : {})}
      >
        <Tooltip.Trigger asChild>{trigger(true)}</Tooltip.Trigger>
        <Tooltip.Portal>
          <Tooltip.Content
            // Marks the portalled panel so the outside-tap handler above can
            // recognise it — it renders outside this component's subtree, so
            // `contains()` cannot.
            data-amenity-panel=""
            side="bottom"
            align="start"
            sideOffset={8}
            style={{
              zIndex: 9999,
              background: '#fff',
              border: '1px solid #e2e8f0',
              borderRadius: '16px',
              padding: '14px',
              boxShadow: '0 10px 34px rgba(15,23,42,0.14)',
              minWidth: '400px',
              maxWidth: '460px',
              maxHeight: '380px',
              overflowY: 'auto',
              fontFamily: 'inherit',
            }}
          >
            {groups.map((g, i) => {
              const code = (g.flightNumber || '').trim().split(/\s+/)[0];
              return (
                <div key={`${g.flightNumber}-${g.routeLabel}`} style={{ marginTop: i > 0 ? 14 : 0 }}>
                  {/* flight header */}
                  <div
                    style={{
                      display: 'flex',
                      alignItems: 'center',
                      justifyContent: 'space-between',
                      gap: 10,
                      background: '#f4f4f5',
                      border: '1px solid #e4e4e7',
                      borderRadius: 10,
                      padding: '7px 10px',
                    }}
                  >
                    <span style={{ display: 'inline-flex', alignItems: 'center', gap: 7, minWidth: 0 }}>
                      {code ? (
                        <AirlineLogo
                          code={code}
                          name=""
                          width={16}
                          height={16}
                          style={{ objectFit: 'contain', borderRadius: 3, flexShrink: 0 }}
                        />
                      ) : null}
                      <span
                        style={{
                          fontSize: 12.5,
                          fontWeight: 700,
                          color: '#0f172a',
                          whiteSpace: 'nowrap',
                          overflow: 'hidden',
                          textOverflow: 'ellipsis',
                        }}
                      >
                        {g.carrierName}
                        <span style={{ color: '#94a3b8', fontWeight: 600 }}> | {g.flightNumber}</span>
                      </span>
                    </span>
                    <span style={{ fontSize: 12, fontWeight: 700, color: '#334155', whiteSpace: 'nowrap' }}>
                      {g.routeLabel}
                    </span>
                  </div>

                  {/* amenities grid */}
                  <div
                    style={{
                      display: 'grid',
                      gridTemplateColumns: '1fr 1fr',
                      gap: '9px 14px',
                      padding: '10px 4px 2px',
                    }}
                  >
                    {g.amenities.map((a) => (
                      <div
                        key={`${a.type}-${a.label}`}
                        style={{
                          display: 'flex',
                          alignItems: 'flex-start',
                          gap: 8,
                          fontSize: 12,
                          lineHeight: '16px',
                          color: '#1e293b',
                        }}
                      >
                        {/* icon boxed to exactly one text line (`1lh`, so it
                            tracks the real font size), centred in it, with a small
                            optical nudge down — lines up with the FIRST line of a
                            two-line label, and with the text on a one-line label */}
                        <span
                          style={{
                            display: 'inline-flex',
                            alignItems: 'center',
                            justifyContent: 'center',
                            height: '1lh',
                            marginTop: '0.1em',
                            flexShrink: 0,
                          }}
                        >
                          <FlightAmenityDetailIcon type={a.type} label={a.label} />
                        </span>
                        {/* plain inline text — wraps only at spaces, never mid-word */}
                        <span style={{ overflowWrap: 'normal', wordBreak: 'normal' }}>
                          {a.label}
                          {a.isChargeable && (
                            <span style={{ color: '#78716c', fontWeight: 500, whiteSpace: 'nowrap' }}>
                              {' '}(Chargeable)
                            </span>
                          )}
                        </span>
                      </div>
                    ))}
                  </div>
                </div>
              );
            })}
            <Tooltip.Arrow style={{ fill: '#fff' }} />
          </Tooltip.Content>
        </Tooltip.Portal>
      </Tooltip.Root>
    </Tooltip.Provider>
  );
}
