'use client';

import { useCallback, useEffect, useState } from 'react';
import { Moon, Sun } from 'lucide-react';
import { Button } from '@/components/ui/Primitives';

// Theme toggle (Phase 6 polish). The design system already defines
// `[data-theme="light"]` overrides in `styles/tokens.css`; we just need a
// way to switch the attribute on `<html>` and persist the choice.
//
// FOUC: a tiny inline script in the root layout reads the same key BEFORE
// React mounts so the first paint is in the chosen theme. See
// `app/layout.tsx`.

const STORAGE_KEY = 'bytelyst.theme.v1';
const THEME_EVENT = 'bytelyst-theme-change';
type Theme = 'dark' | 'light';
const THEMES: Theme[] = ['dark', 'light'];

function readPersisted(): Theme {
  if (typeof window === 'undefined') return 'dark';
  try {
    const raw = window.localStorage.getItem(STORAGE_KEY);
    if (raw && (THEMES as string[]).includes(raw)) return raw as Theme;
  } catch {
    // localStorage may be unavailable; fall through.
  }
  return 'dark';
}

function applyTheme(theme: Theme) {
  if (typeof document === 'undefined') return;
  document.documentElement.setAttribute('data-theme', theme);
  document.documentElement.classList.toggle('dark', theme === 'dark');
}

export function ThemeToggle() {
  // Mirror the SSR-safe default the inline FOUC-prevention script also uses.
  const [theme, setTheme] = useState<Theme>('dark');

  useEffect(() => {
    const persisted = readPersisted();
    setTheme(persisted);
    applyTheme(persisted);

    function handleThemeChange(event: Event) {
      const next = (event as CustomEvent<Theme>).detail;
      if ((THEMES as string[]).includes(next)) {
        setTheme(next);
        applyTheme(next);
      }
    }

    window.addEventListener(THEME_EVENT, handleThemeChange);
    return () => window.removeEventListener(THEME_EVENT, handleThemeChange);
  }, []);

  const toggle = useCallback(() => {
    setTheme((prev) => {
      const next = prev === 'dark' ? 'light' : 'dark';
      try {
        if (typeof window !== 'undefined') {
          window.localStorage.setItem(STORAGE_KEY, next);
          window.localStorage.setItem('theme', next);
          window.dispatchEvent(new CustomEvent(THEME_EVENT, { detail: next }));
        }
      } catch {
        // ignore
      }
      applyTheme(next);
      return next;
    });
  }, []);

  return (
    <Button
      variant="ghost"
      size="sm"
      onClick={toggle}
      aria-label={`Switch to ${theme === 'dark' ? 'light' : 'dark'} theme`}
      title={`Switch to ${theme === 'dark' ? 'light' : 'dark'} theme`}
    >
      {theme === 'dark' ? <Sun className="h-4 w-4" /> : <Moon className="h-4 w-4" />}
    </Button>
  );
}
