'use client';

import { useEffect, useState } from 'react';
import { Moon, Sun } from 'lucide-react';
import { useTranslations } from 'next-intl';
import { applyTheme, getStoredTheme, type ThemeMode } from '@/lib/theme';

export function ThemeToggle() {
  const t = useTranslations('theme');
  const [mode, setMode] = useState<ThemeMode | null>(null);

  useEffect(() => {
    setMode(getStoredTheme());
  }, []);

  const handleClick = () => {
    const current = getStoredTheme();
    const next: ThemeMode = current === 'dark' ? 'light' : 'dark';
    applyTheme(next);
    setMode(next);
  };

  if (mode === null) {
    return (
      <span
        className="inline-flex h-9 w-9 shrink-0 rounded-[var(--radius-md)] border border-border/60 bg-background-secondary/80"
        aria-hidden
      />
    );
  }

  const isDark = mode === 'dark';

  return (
    <button
      type="button"
      onClick={handleClick}
      className="inline-flex h-9 w-9 shrink-0 items-center justify-center rounded-[var(--radius-md)] border border-border/60 bg-background-secondary/80 text-text-primary hover:border-border-strong hover:bg-background-card/80 transition-colors"
      aria-label={isDark ? t('switchToLight') : t('switchToDark')}
      title={isDark ? t('lightMode') : t('darkMode')}
    >
      {isDark ? (
        <Sun className="h-[18px] w-[18px] icon-flat" />
      ) : (
        <Moon className="h-[18px] w-[18px] icon-flat" />
      )}
    </button>
  );
}
