'use client';

import { useEffect, useId, useRef, useState } from 'react';
import { ShieldCheck, Star, Lock } from 'lucide-react';
import * as Popover from '@radix-ui/react-popover';
import { useTranslations } from 'next-intl';
import { useMatchMedia } from '@/hooks/useMatchMedia';
import { cn } from '@/lib/utils';

export type TrustType = 'verified' | 'top_rated' | 'escrow_protected';

const TRUST_ICONS: Record<TrustType, React.ElementType> = {
  verified: ShieldCheck,
  top_rated: Star,
  escrow_protected: Lock,
};

const TRUST_COLORS: Record<TrustType, string> = {
  verified: 'text-success bg-success/10',
  top_rated: 'text-warning bg-warning/10',
  escrow_protected: 'text-info bg-info/10',
};

/**
 * Feature 054 (US6, T054) — Dual-mode TrustBadge.
 *
 * - Pointer:fine (mouse + trackpad): inline hover tooltip on mouseenter /
 *   focus. No popover. The description is rendered as a `<span role="tooltip">`
 *   with a stable id so `aria-describedby` works for screen readers regardless
 *   of visual hover state.
 * - Touch: Radix Popover triggered by tap. Escape + outside click close;
 *   Radix automatically returns focus to the trigger button.
 *
 * Both modes share the `aria-describedby` description so AT users get the
 * same content the visual UI surfaces.
 */
export function TrustBadge({ type, className }: { type: TrustType; className?: string }) {
  const t = useTranslations('trust_badge');
  const Icon = TRUST_ICONS[type];
  const isFinePointer = useMatchMedia('(pointer: fine)');
  const descriptionId = `trust-badge-${useId()}`;

  const label = t(type);
  const description = t(`${type}_desc` as `${TrustType}_desc`);

  if (isFinePointer) {
    return (
      <FinePointerBadge
        type={type}
        Icon={Icon}
        label={label}
        description={description}
        descriptionId={descriptionId}
        className={className}
      />
    );
  }

  return (
    <Popover.Root>
      <Popover.Trigger asChild>
        <button
          type="button"
          aria-describedby={descriptionId}
          className={cn(
            'inline-flex items-center gap-1 rounded-full px-2 py-0.5 text-[11px] font-medium leading-none cursor-pointer focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary-600 focus-visible:ring-offset-1',
            TRUST_COLORS[type],
            className,
          )}
          data-testid={`trust-badge-${type}`}
        >
          <Icon className="h-3 w-3" aria-hidden />
          {label}
        </button>
      </Popover.Trigger>
      <Popover.Portal>
        <Popover.Content
          id={descriptionId}
          role="tooltip"
          side="top"
          align="center"
          sideOffset={4}
          className="z-50 max-w-[220px] rounded-lg border border-neutral-200 bg-white p-3 text-xs text-neutral-700 shadow-lg"
        >
          {description}
          <Popover.Arrow className="fill-white stroke-neutral-200" />
        </Popover.Content>
      </Popover.Portal>
    </Popover.Root>
  );
}

function FinePointerBadge({
  type,
  Icon,
  label,
  description,
  descriptionId,
  className,
}: {
  type: TrustType;
  Icon: React.ElementType;
  label: string;
  description: string;
  descriptionId: string;
  className?: string;
}) {
  const [open, setOpen] = useState(false);
  const buttonRef = useRef<HTMLButtonElement>(null);

  useEffect(() => {
    if (!open) return;
    const onKey = (e: KeyboardEvent) => {
      if (e.key === 'Escape') {
        setOpen(false);
        buttonRef.current?.focus();
      }
    };
    window.addEventListener('keydown', onKey);
    return () => window.removeEventListener('keydown', onKey);
  }, [open]);

  return (
    <span className="relative inline-flex">
      <button
        ref={buttonRef}
        type="button"
        aria-describedby={descriptionId}
        onMouseEnter={() => setOpen(true)}
        onMouseLeave={() => setOpen(false)}
        onFocus={() => setOpen(true)}
        onBlur={() => setOpen(false)}
        className={cn(
          'inline-flex items-center gap-1 rounded-full px-2 py-0.5 text-[11px] font-medium leading-none cursor-default focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary-600 focus-visible:ring-offset-1',
          TRUST_COLORS[type],
          className,
        )}
        data-testid={`trust-badge-${type}`}
      >
        <Icon className="h-3 w-3" aria-hidden />
        {label}
      </button>

      <span
        id={descriptionId}
        role="tooltip"
        data-state={open ? 'open' : 'closed'}
        className={cn(
          'pointer-events-none absolute left-1/2 top-full z-50 mt-1.5 -translate-x-1/2 whitespace-nowrap rounded-md bg-neutral-900 px-2.5 py-1.5 text-xs text-white shadow-md transition-opacity duration-150',
          open ? 'opacity-100' : 'opacity-0',
        )}
      >
        {description}
      </span>
    </span>
  );
}
