/**
 * DpadHelperOverlay — small fading on-screen hint card that
 * teaches first-time TV-remote users which directions and buttons
 * map to which actions inside a modal/overlay.
 *
 * UX
 *   • Renders only on Smart TV (Tizen / WebOS) — desktop users
 *     already see the gold focus ring + arrow-key behaviour.
 *   • Top-right corner, 2-second fade-out (per Samsung QA pattern
 *     guidance that on-screen hints must not stay forever).
 *   • Shown ONCE per session per overlay-id (localStorage), so
 *     subscribers don't see it every single time they open a modal.
 *
 * Usage
 *   <DpadHelperOverlay show={open} id="add-server" />
 *
 * The `show` prop controls visibility (mount on open, unmount on
 * close). The `id` makes the "shown once" memo per-overlay so each
 * dialog gets its own first-time onboarding.
 */
import { useEffect, useState } from "react";
import { motion, AnimatePresence } from "framer-motion";
import {
  ChevronUp,
  ChevronDown,
  ChevronLeft,
  ChevronRight,
  CornerDownLeft,
  Undo2,
} from "lucide-react";
import { isSmartTV } from "@/lib/platform";

const SEEN_PREFIX = "nadiplay_dpad_helper_seen:";
const FADE_OUT_MS = 2000;

export interface DpadHelperOverlayProps {
  /** Mount/show the helper. Typically the modal's `open` prop. */
  show: boolean;
  /** Unique id per overlay — used for the "show only once" memo. */
  id: string;
  /** Force the helper to show every time, ignoring the once-only memo. */
  alwaysShow?: boolean;
}

export const DpadHelperOverlay = ({
  show,
  id,
  alwaysShow = false,
}: DpadHelperOverlayProps) => {
  const [visible, setVisible] = useState(false);

  useEffect(() => {
    if (!show) {
      setVisible(false);
      return;
    }
    // Desktop / mobile — never show. Skip the hint entirely.
    if (!isSmartTV()) return;

    if (!alwaysShow) {
      const key = `${SEEN_PREFIX}${id}`;
      try {
        if (localStorage.getItem(key)) return;
        localStorage.setItem(key, "1");
      } catch {
        /* ignore quota / private-mode errors */
      }
    }

    setVisible(true);
    const t = window.setTimeout(() => setVisible(false), FADE_OUT_MS);
    return () => window.clearTimeout(t);
  }, [show, id, alwaysShow]);

  return (
    <AnimatePresence>
      {visible && (
        <motion.div
          initial={{ opacity: 0, y: -8 }}
          animate={{ opacity: 1, y: 0 }}
          exit={{ opacity: 0, y: -8 }}
          transition={{ duration: 0.25, ease: "easeOut" }}
          data-testid={`dpad-helper-${id}`}
          className="fixed top-3 end-3 z-[120] pointer-events-none"
        >
          <div
            className="flex items-center gap-2 rounded-2xl px-3 py-2 backdrop-blur-md"
            style={{
              background: "hsla(200, 30%, 8%, 0.85)",
              border: "1px solid hsla(40, 80%, 55%, 0.35)",
              boxShadow: "0 6px 30px hsla(40, 80%, 55%, 0.18)",
            }}
          >
            <Glyph>
              <ChevronUp className="w-3.5 h-3.5" />
            </Glyph>
            <Glyph>
              <ChevronDown className="w-3.5 h-3.5" />
            </Glyph>
            <Glyph>
              <ChevronLeft className="w-3.5 h-3.5" />
            </Glyph>
            <Glyph>
              <ChevronRight className="w-3.5 h-3.5" />
            </Glyph>
            <span className="text-[10px] text-muted-foreground tracking-[0.2em] uppercase mx-1">
              navigate
            </span>
            <Glyph>
              <CornerDownLeft className="w-3.5 h-3.5" />
            </Glyph>
            <span className="text-[10px] text-foreground/80 tracking-[0.2em] uppercase mx-1">
              ok
            </span>
            <Glyph>
              <Undo2 className="w-3.5 h-3.5" />
            </Glyph>
            <span className="text-[10px] text-foreground/80 tracking-[0.2em] uppercase">
              back
            </span>
          </div>
        </motion.div>
      )}
    </AnimatePresence>
  );
};

const Glyph = ({ children }: { children: React.ReactNode }) => (
  <span
    className="grid place-items-center w-6 h-6 rounded-md border text-primary"
    style={{
      borderColor: "hsla(40, 80%, 55%, 0.35)",
      background: "hsla(40, 80%, 55%, 0.10)",
    }}
  >
    {children}
  </span>
);

export default DpadHelperOverlay;
