"use client";

/**
 * @file HUDOverlayDebugger.tsx
 * Visual debugger for HUD overlays & stacking order.
 * - Portals to #global-overlay-root (non-interactive)
 * - Toggle (Ctrl/Cmd + Shift + L)
 * - Opacity control: Ctrl/Cmd + Shift + [ / ]
 * - Shows mounted layers, z-index, and live highlights
 */

import React, { useEffect, useMemo, useState } from "react";
import ReactDOM from "react-dom";
import { motion } from "framer-motion";

export type HudLayerState = {
  key: "ai" | "voice" | string;
  label: string;
  zIndex: number;
  active: boolean;
};

interface HUDOverlayDebuggerProps {
  /** Current layers reported by HUDLayerManager */
  layers: HudLayerState[];
  /** Optional: default visibility */
  defaultOpen?: boolean;
}

export const HUDOverlayDebugger: React.FC<HUDOverlayDebuggerProps> = ({
  layers,
  defaultOpen = false,
}) => {
  const [rootEl, setRootEl] = useState<HTMLElement | null>(null);
  const [open, setOpen] = useState(defaultOpen);
  const [opacity, setOpacity] = useState(0.22);

  // mount portal root
  useEffect(() => {
    let el = document.getElementById("global-overlay-root");
    if (!el) {
      el = document.createElement("div");
      el.id = "global-overlay-root";
      document.body.appendChild(el);
    }
    setRootEl(el);
  }, []);

  // hotkeys
  useEffect(() => {
    const onKey = (e: KeyboardEvent) => {
      const mod = e.ctrlKey || e.metaKey;
      if (mod && e.shiftKey && (e.key === "L" || e.key === "l")) {
        e.preventDefault();
        setOpen((v) => !v);
      }
      if (mod && e.shiftKey && e.key === "]") {
        e.preventDefault();
        setOpacity((o) => Math.min(0.8, +(o + 0.05).toFixed(2)));
      }
      if (mod && e.shiftKey && e.key === "[") {
        e.preventDefault();
        setOpacity((o) => Math.max(0.05, +(o - 0.05).toFixed(2)));
      }
    };
    window.addEventListener("keydown", onKey);
    return () => window.removeEventListener("keydown", onKey);
  }, []);

  const maxZ = useMemo(
    () => (layers.length ? Math.max(...layers.map((l) => l.zIndex)) : 0),
    [layers]
  );

  if (!rootEl || !open) return null;

  return ReactDOM.createPortal(
    <>
      {/* global background grid (debug visual) */}
      <div
        className="fixed inset-0 pointer-events-none z-[9998]"
        style={{
          background:
            "repeating-linear-gradient(to bottom, rgba(56,189,248,.08), rgba(56,189,248,.08) 1px, transparent 1px, transparent 12px)",
          boxShadow: "inset 0 0 0 1px rgba(56,189,248,0.25)",
          opacity,
        }}
      />

      {/* Left-edge labels */}
      <div className="fixed top-2 left-2 space-y-2 z-[9999] pointer-events-none">
        {layers
          .slice()
          .sort((a, b) => a.zIndex - b.zIndex)
          .map((l) => (
            <div
              key={l.key}
              className="pointer-events-auto select-none rounded-md px-3 py-1.5 text-xs font-mono shadow
                         border border-cyan-500/30"
              style={{
                color: l.active ? "#22d3ee" : "#93c5fd",
                background: l.active
                  ? "rgba(8,145,178,0.22)"
                  : "rgba(30,58,138,0.18)",
                backdropFilter: "blur(6px)",
              }}
              title={`z-index: ${l.zIndex}`}
            >
              {l.label} <span className="opacity-70">z={l.zIndex}</span>
            </div>
          ))}
      </div>

      {/* Legend */}
      <motion.div
        className="fixed top-2 right-2 z-[9999] pointer-events-auto"
        initial={{ opacity: 0, y: -6 }}
        animate={{ opacity: 1, y: 0 }}
      >
        <div className="rounded-lg border border-cyan-400/30 bg-[rgba(2,8,23,0.7)] backdrop-blur-md p-3">
          <div className="text-[10px] text-cyan-200/80 font-semibold mb-2">
            HUD Overlay Debugger
          </div>
          <div className="text-[11px] text-cyan-100/80 space-y-1">
            <div>Max z-index: {maxZ || "—"}</div>
            <div>Opacity: {(opacity * 100).toFixed(0)}%</div>
            <div className="opacity-80">
              Toggle: <kbd>Ctrl/⌘</kbd>+<kbd>Shift</kbd>+<kbd>L</kbd>
            </div>
            <div className="opacity-80">
              Opacity: <kbd>Ctrl/⌘</kbd>+<kbd>Shift</kbd>+<kbd>[</kbd>/<kbd>]</kbd>
            </div>
          </div>
        </div>
      </motion.div>
    </>,
    rootEl
  );
};
