import { useEffect } from 'react';

const KONAMI = [
  'ArrowUp',
  'ArrowUp',
  'ArrowDown',
  'ArrowDown',
  'ArrowLeft',
  'ArrowRight',
  'ArrowLeft',
  'ArrowRight',
  'KeyB',
  'KeyA',
];

function triggerPartyMode() {
  if (document.getElementById('party-overlay')) return;
  const overlay = document.createElement('div');
  overlay.id = 'party-overlay';
  overlay.style.cssText =
    'position:fixed;inset:0;z-index:9999;pointer-events:none;background:transparent;';
  document.body.appendChild(overlay);

  // Strobe flashes
  const strobe = document.createElement('div');
  strobe.style.cssText =
    'position:absolute;inset:0;background:#ffffff;opacity:0;mix-blend-mode:difference;';
  overlay.appendChild(strobe);

  const colors = ['#00F0FF', '#FF2A6D', '#C6FF00', '#B967FF'];
  let i = 0;
  const strobeInterval = setInterval(() => {
    const c = colors[i++ % colors.length];
    strobe.style.background = c;
    strobe.style.opacity = '0.4';
    setTimeout(() => (strobe.style.opacity = '0'), 60);
  }, 140);

  // Big text
  const text = document.createElement('div');
  text.textContent = 'PARTY MODE ACTIVATED';
  text.style.cssText = `
    position:absolute;top:50%;left:50%;transform:translate(-50%,-50%);
    font-family:"Bebas Neue",Impact,sans-serif;font-size:min(12vw,8rem);
    color:#C6FF00;text-shadow:0 0 30px #C6FF00;letter-spacing:0.1em;
    animation:glitch-skew 0.2s infinite;pointer-events:none;
  `;
  overlay.appendChild(text);

  // Clean up after 4 seconds
  setTimeout(() => {
    clearInterval(strobeInterval);
    overlay.style.transition = 'opacity 0.5s';
    overlay.style.opacity = '0';
    setTimeout(() => overlay.remove(), 500);
  }, 4000);
}

function playTick() {
  const soundOn = (window as unknown as { __soundOn?: boolean }).__soundOn;
  if (!soundOn) return;
  try {
    const AudioCtx =
      window.AudioContext || (window as unknown as { webkitAudioContext: typeof AudioContext }).webkitAudioContext;
    const ctx = new AudioCtx();
    const osc = ctx.createOscillator();
    const gain = ctx.createGain();
    osc.type = 'square';
    osc.frequency.value = 1200;
    gain.gain.value = 0.02;
    osc.connect(gain);
    gain.connect(ctx.destination);
    osc.start();
    gain.gain.exponentialRampToValueAtTime(0.0001, ctx.currentTime + 0.04);
    osc.stop(ctx.currentTime + 0.05);
  } catch {
    /* audio disabled */
  }
}

export default function EasterEggs() {
  useEffect(() => {
    // Konami code
    let buffer: string[] = [];
    function onKey(e: KeyboardEvent) {
      buffer.push(e.code);
      if (buffer.length > KONAMI.length) buffer.shift();
      if (KONAMI.every((k, i) => buffer[i] === k)) {
        triggerPartyMode();
        buffer = [];
      }
    }
    window.addEventListener('keydown', onKey);

    // Logo 5x click
    let logoClickCount = 0;
    let logoTimer: number | null = null;
    const logo = document.querySelector<HTMLElement>('header a[href="/"]');
    function onLogoClick(e: Event) {
      logoClickCount += 1;
      if (logoClickCount >= 5) {
        e.preventDefault();
        logoClickCount = 0;
        triggerPartyMode();
      }
      if (logoTimer) window.clearTimeout(logoTimer);
      logoTimer = window.setTimeout(() => {
        logoClickCount = 0;
      }, 2000);
    }
    logo?.addEventListener('click', onLogoClick);

    // Tick on hover links/buttons
    function onMouseOver(e: MouseEvent) {
      const t = e.target as HTMLElement;
      if (!t?.closest) return;
      if (t.closest('a, button, [role="button"]')) {
        playTick();
      }
    }
    document.addEventListener('mouseover', onMouseOver, { passive: true });

    return () => {
      window.removeEventListener('keydown', onKey);
      logo?.removeEventListener('click', onLogoClick);
      document.removeEventListener('mouseover', onMouseOver);
    };
  }, []);

  return null;
}
