'use client';

// Keyboard Shortcuts Overlay (V23.3) — Quick Win #3
//
// Press `?` or click the help button in TopBar to open. Shows all keyboard
// shortcuts grouped by category, with a live search filter.
//
// Each shortcut is rendered as a `<KeyCap>` visual showing the modifier
// keys (⌘/Ctrl, ⇧, ⌥/Alt) and the trigger key, like macOS cheat sheets.

import { useEffect, useMemo, useState } from 'react';
import { createPortal } from 'react-dom';
import { Keyboard, Search, X } from 'lucide-react';

interface Shortcut {
  /** Trigger key (e.g. "Z", "?", "ArrowRight", "/"). */
  key: string;
  /** Display label e.g. "Save Project". */
  label: string;
  /** Description for tooltip / search results. */
  hint: string;
  /** Modifier keys. */
  mod?: ('mod' | 'shift' | 'alt')[];
  /** Category for grouping in the grid. */
  category: 'Playback' | 'Edit' | 'Timeline' | 'View' | 'Project' | 'AI';
}

const SHORTCUTS: Shortcut[] = [
  // Playback
  { key: 'Space', label: 'เล่น/หยุด', hint: 'Play or pause the timeline', category: 'Playback' },
  { key: 'J', label: 'ย้อนหลัง', hint: 'Rewind (Shift = 5s)', mod: ['shift'], category: 'Playback' },
  { key: 'K', label: 'หยุดชั่วคราว', hint: 'Pause playback', category: 'Playback' },
  { key: 'L', label: 'เดินหน้า', hint: 'Forward (Shift = 5s)', mod: ['shift'], category: 'Playback' },
  { key: '←', label: 'เฟรมก่อนหน้า', hint: 'Previous frame', category: 'Playback' },
  { key: '→', label: 'เฟรมถัดไป', hint: 'Next frame', category: 'Playback' },
  { key: 'Home', label: 'ไปจุดเริ่มต้น', hint: 'Jump to start', category: 'Playback' },
  { key: 'End', label: 'ไปจุดสิ้นสุด', hint: 'Jump to end', category: 'Playback' },

  // Edit
  { key: 'Z', label: 'ย้อนกลับ', hint: 'Undo last action', mod: ['mod'], category: 'Edit' },
  { key: 'Z', label: 'ทำซ้ำ', hint: 'Redo', mod: ['mod', 'shift'], category: 'Edit' },
  { key: 'Y', label: 'ทำซ้ำ (alt)', hint: 'Redo (alternative)', mod: ['mod'], category: 'Edit' },
  { key: 'S', label: 'แยกคลิป', hint: 'Split clip at playhead', category: 'Edit' },
  { key: 'I', label: 'ตั้ง in-point', hint: 'Set in-point of selected clip', category: 'Edit' },
  { key: 'O', label: 'ตั้ง out-point', hint: 'Set out-point of selected clip', category: 'Edit' },
  { key: 'Delete', label: 'ลบคลิป', hint: 'Delete selected clip(s)', category: 'Edit' },
  { key: 'A', label: 'เลือกทั้งหมด', hint: 'Select all clips', mod: ['mod'], category: 'Edit' },
  { key: 'D', label: 'คัดลอกคลิป', hint: 'Duplicate selected clip(s)', mod: ['mod'], category: 'Edit' },
  { key: 'G', label: 'จัดกลุ่ม', hint: 'Group selected clips', mod: ['mod'], category: 'Edit' },
  { key: 'G', label: 'เลิกจัดกลุ่ม', hint: 'Ungroup selection', mod: ['mod', 'shift'], category: 'Edit' },

  // Timeline
  { key: '+', label: 'ซูมเข้า', hint: 'Zoom timeline in', category: 'Timeline' },
  { key: '-', label: 'ซูมออก', hint: 'Zoom timeline out', category: 'Timeline' },
  { key: '0', label: 'พอดีจอ', hint: 'Fit timeline to viewport', category: 'Timeline' },
  { key: 'M', label: 'เพิ่ม marker', hint: 'Add marker at playhead', category: 'Timeline' },

  // View
  { key: '1', label: 'ดู Preview', hint: 'Focus preview pane', mod: ['mod'], category: 'View' },
  { key: '2', label: 'ดู Media', hint: 'Focus media library', mod: ['mod'], category: 'View' },
  { key: '3', label: 'ดู Properties', hint: 'Focus properties panel', mod: ['mod'], category: 'View' },
  { key: 'F', label: 'เต็มจอ', hint: 'Toggle fullscreen preview', category: 'View' },
  { key: '\\', label: 'ซ่อน/แสดง Sidebar', hint: 'Toggle left sidebar', mod: ['mod'], category: 'View' },

  // Project
  { key: 'S', label: 'บันทึกโปรเจกต์', hint: 'Save project (manual)', mod: ['mod'], category: 'Project' },
  { key: 'N', label: 'โปรเจกต์ใหม่', hint: 'Create new project', mod: ['mod'], category: 'Project' },
  { key: 'P', label: 'เปิดโปรเจกต์', hint: 'Open project picker', mod: ['mod'], category: 'Project' },
  { key: 'E', label: 'ส่งออก mp4', hint: 'Export current project', mod: ['mod'], category: 'Project' },
  { key: 'L', label: 'แชร์ลิงค์', hint: 'Copy share URL', mod: ['mod', 'shift'], category: 'Project' },

  // AI
  { key: 'W', label: 'Whisper Captions', hint: 'Auto-generate captions', mod: ['mod', 'shift'], category: 'AI' },
  { key: 'T', label: 'เพิ่ม Text Overlay', hint: 'Add floating text', category: 'AI' },
  { key: '?', label: 'แสดงคีย์ลัด', hint: 'Show this overlay', mod: ['shift'], category: 'AI' },
];

const CATEGORY_ORDER: Shortcut['category'][] = [
  'Playback', 'Edit', 'Timeline', 'View', 'Project', 'AI',
];

interface ShortcutsModalProps {
  open: boolean;
  onClose: () => void;
}

export function ShortcutsModal({ open, onClose }: ShortcutsModalProps) {
  const [query, setQuery] = useState('');

  // Reset search when modal opens
  useEffect(() => {
    if (open) setQuery('');
  }, [open]);

  // Close on Escape
  useEffect(() => {
    if (!open) return;
    function onKey(e: KeyboardEvent) {
      if (e.key === 'Escape') onClose();
    }
    window.addEventListener('keydown', onKey);
    return () => window.removeEventListener('keydown', onKey);
  }, [open, onClose]);

  const filtered = useMemo(() => {
    const q = query.trim().toLowerCase();
    if (!q) return SHORTCUTS;
    return SHORTCUTS.filter(
      (s) =>
        s.label.toLowerCase().includes(q) ||
        s.hint.toLowerCase().includes(q) ||
        s.key.toLowerCase().includes(q) ||
        s.category.toLowerCase().includes(q),
    );
  }, [query]);

  const grouped = useMemo(() => {
    const map = new Map<Shortcut['category'], Shortcut[]>();
    for (const cat of CATEGORY_ORDER) map.set(cat, []);
    for (const s of filtered) map.get(s.category)?.push(s);
    return map;
  }, [filtered]);

  if (!open) return null;

  return createPortal(
    <div
      className="fixed inset-0 z-[9999] flex items-center justify-center bg-black/60 backdrop-blur-md animate-fade-in"
      onClick={onClose}
      data-testid="shortcuts-modal"
    >
      <div
        className="relative w-[760px] max-w-[92vw] max-h-[88vh] rounded-2xl bg-[#181a20] border border-white/10 shadow-2xl animate-slide-up flex flex-col"
        onClick={(e) => e.stopPropagation()}
      >
        {/* Header */}
        <div className="px-6 pt-5 pb-3 border-b border-white/5 flex items-center gap-3">
          <div className="w-10 h-10 rounded-xl bg-gradient-to-br from-blue-500 to-purple-500 flex items-center justify-center shadow-glow-blue">
            <Keyboard size={20} className="text-white" />
          </div>
          <div className="flex-1">
            <h2 className="text-lg font-semibold text-white">คีย์ลัด · Keyboard Shortcuts</h2>
            <p className="text-[11px] text-slate-400 mt-0.5">
              กด <Kbd>?</Kbd> เปิด · <Kbd>Esc</Kbd> ปิด · ค้นหาด้านล่าง
            </p>
          </div>
          <button
            type="button"
            onClick={onClose}
            className="w-8 h-8 rounded-md flex items-center justify-center text-slate-400 hover:text-white hover:bg-white/10 transition-colors"
            aria-label="close"
          >
            <X size={16} />
          </button>
        </div>

        {/* Search */}
        <div className="px-6 py-3 border-b border-white/5">
          <div className="relative">
            <Search size={14} className="absolute left-3 top-1/2 -translate-y-1/2 text-slate-500" />
            <input
              type="text"
              autoFocus
              value={query}
              onChange={(e) => setQuery(e.target.value)}
              placeholder="ค้นหา ... เช่น undo, zoom, export"
              className="w-full pl-9 pr-3 py-2 rounded-lg bg-white/[0.03] border border-white/10 text-sm text-white placeholder:text-slate-500 focus:outline-none focus:border-blue-500 transition-colors"
            />
          </div>
        </div>

        {/* Grid of shortcuts */}
        <div className="flex-1 overflow-y-auto px-6 py-4">
          {filtered.length === 0 ? (
            <div className="text-center text-slate-400 py-12 text-sm">
              ไม่พบคีย์ลัดที่ตรงกับ &ldquo;<span className="text-white">{query}</span>&rdquo;
            </div>
          ) : (
            <div className="grid grid-cols-2 gap-x-6 gap-y-5">
              {CATEGORY_ORDER.map((cat) => {
                const items = grouped.get(cat);
                if (!items || items.length === 0) return null;
                return (
                  <div key={cat} className="space-y-2">
                    <div className="flex items-center gap-1.5 text-[10px] font-bold uppercase tracking-wider text-slate-400">
                      <span className="w-1.5 h-1.5 rounded-full bg-capcut-blue" />
                      {cat} <span className="text-slate-600">({items.length})</span>
                    </div>
                    <div className="space-y-1">
                      {items.map((s, i) => (
                        <ShortcutRow key={`${cat}-${i}`} s={s} />
                      ))}
                    </div>
                  </div>
                );
              })}
            </div>
          )}
        </div>

        {/* Footer */}
        <div className="px-6 py-3 border-t border-white/5 flex items-center justify-between text-[10px] text-slate-500">
          <span>{filtered.length} shortcuts · {CATEGORY_ORDER.length} categories</span>
          <span>Pro tip: ⇧ = Shift · ⌘ = Ctrl/Cmd · ⌥ = Alt</span>
        </div>
      </div>
    </div>,
    document.body,
  );
}

function ShortcutRow({ s }: { s: Shortcut }) {
  return (
    <div className="flex items-center justify-between gap-2 py-1.5 px-2 rounded hover:bg-white/[0.04] transition-colors group">
      <div className="flex-1 min-w-0">
        <div className="text-xs text-white truncate" title={s.hint}>
          {s.label}
        </div>
        <div className="text-[10px] text-slate-500 truncate">{s.hint}</div>
      </div>
      <div className="flex items-center gap-1 shrink-0">
        {s.mod?.includes('mod') && <Kbd>⌘</Kbd>}
        {s.mod?.includes('shift') && <Kbd>⇧</Kbd>}
        {s.mod?.includes('alt') && <Kbd>⌥</Kbd>}
        <Kbd highlight>{s.key}</Kbd>
      </div>
    </div>
  );
}

function Kbd({ children, highlight }: { children: React.ReactNode; highlight?: boolean }) {
  return (
    <kbd
      className={`inline-flex items-center justify-center min-w-[24px] h-6 px-1.5 rounded text-[10px] font-mono font-semibold border ${
        highlight
          ? 'bg-blue-500/15 border-blue-500/40 text-blue-300 shadow-[0_0_0_1px_rgba(59,130,246,0.2)]'
          : 'bg-white/[0.06] border-white/15 text-slate-300'
      }`}
    >
      {children}
    </kbd>
  );
}

/** Hook to register `?` key globally for opening the shortcuts modal. */
export function useShortcutsModalKey(open: () => void) {
  useEffect(() => {
    function onKey(e: KeyboardEvent) {
      const target = e.target as HTMLElement | null;
      if (target && (target.tagName === 'INPUT' || target.tagName === 'TEXTAREA' || target.isContentEditable)) {
        return;
      }
      // `?` is Shift+/ on most keyboards
      if (e.key === '?' || (e.shiftKey && e.key === '/')) {
        e.preventDefault();
        open();
      }
    }
    window.addEventListener('keydown', onKey);
    return () => window.removeEventListener('keydown', onKey);
  }, [open]);
}