'use client';

/**
 * Registers global navigation shortcuts at app startup.
 * Shortcuts: g n → /notify, g i → /issues, g r → /repos, g m → /rooms
 * Uses the two-key chord pattern (press g, then the key).
 */

import { useEffect, useRef } from 'react';
import { useNavigate } from 'react-router-dom';

interface ChordTarget {
  key: string;
  path: string;
  description: string;
}

const CHORD_KEY = 'g';

const TARGETS: ChordTarget[] = [
  { key: 'n', path: '/notify', description: 'Go to Notifications' },
  { key: 'i', path: '/issues', description: 'Go to Issues' },
  { key: 'r', path: '/repos', description: 'Go to Repositories' },
  { key: 'm', path: '/rooms', description: 'Go to Messages' },
];

/** Show a brief indicator when a chord is active */
function showChordHint() {
  const existing = document.getElementById('nav-chord-hint');
  if (existing) existing.remove();

  const el = document.createElement('div');
  el.id = 'nav-chord-hint';
  el.textContent = 'g _';
  el.style.cssText = `
    position: fixed;
    bottom: 80px;
    left: 50%;
    transform: translateX(-50%);
    background: var(--foreground);
    color: var(--background);
    padding: 4px 12px;
    border-radius: 6px;
    font-size: 13px;
    font-family: monospace;
    font-weight: 600;
    z-index: 9999;
    pointer-events: none;
    opacity: 1;
    transition: opacity 0.3s ease;
  `;
  document.body.appendChild(el);

  setTimeout(() => {
    el.style.opacity = '0';
    setTimeout(() => el.remove(), 300);
  }, 600);
}

export function GlobalNavigationShortcuts() {
  const navigate = useNavigate();
  const pendingKeyRef = useRef<string | null>(null);
  const timerRef = useRef<ReturnType<typeof setTimeout> | null>(null);

  useEffect(() => {
    const handleKey = (e: KeyboardEvent) => {
      const target = e.target as HTMLElement;
      const isEditing =
        target.tagName === 'INPUT' ||
        target.tagName === 'TEXTAREA' ||
        target.isContentEditable;
      if (isEditing) return;

      if (pendingKeyRef.current) {
        const next = e.key.toLowerCase();
        const match = TARGETS.find((t) => t.key === next);
        if (match) {
          e.preventDefault();
          navigate(match.path);
        }
        pendingKeyRef.current = null;
        if (timerRef.current) { clearTimeout(timerRef.current); timerRef.current = null; }
        return;
      }

      if (e.key.toLowerCase() === CHORD_KEY) {
        pendingKeyRef.current = CHORD_KEY;
        showChordHint();
        timerRef.current = setTimeout(() => { pendingKeyRef.current = null; }, 600);
      }
    };

    window.addEventListener('keydown', handleKey);
    return () => window.removeEventListener('keydown', handleKey);
  }, [navigate]);

  return null;
}
