'use client';

import { useEffect, useState } from 'react';
import { useTheme } from 'next-themes';
import { Sun, Moon } from 'lucide-react';
import { cn } from '@/lib/utils/cn';

/**
 * The brand's light/dark switch. Track is azure when light, maroon when dark —
 * this is the "switch" referenced in the design brief, not just a settings toggle.
 * Reused in the dashboard/admin header once those are built.
 */
export function ThemeToggle({ className }: { className?: string }) {
  const { resolvedTheme, setTheme } = useTheme();
  const [mounted, setMounted] = useState(false);

  // Avoid a hydration mismatch: next-themes doesn't know the real theme until mounted.
  useEffect(() => setMounted(true), []);
  if (!mounted) return <div className={cn('h-8 w-16 rounded-full bg-black/5 dark:bg-white/5', className)} />;

  const isDark = resolvedTheme === 'dark';

  return (
    <button
      type="button"
      role="switch"
      aria-checked={isDark}
      aria-label={isDark ? 'Switch to light mode' : 'Switch to dark mode'}
      onClick={() => setTheme(isDark ? 'light' : 'dark')}
      className={cn(
        'relative inline-flex h-8 w-16 items-center rounded-full transition-colors duration-300',
        isDark ? 'bg-maroon' : 'bg-azure',
        className
      )}
    >
      <span
        className={cn(
          'absolute flex h-6 w-6 items-center justify-center rounded-full bg-paper-soft shadow-card transition-transform duration-300',
          isDark ? 'translate-x-9' : 'translate-x-1'
        )}
      >
        {isDark ? <Moon size={14} className="text-maroon" /> : <Sun size={14} className="text-azure" />}
      </span>
    </button>
  );
}
