'use client';

import { useEffect, useState } from 'react';
import { CrmIcon } from '@/components/crm/CrmIcon';

function readTheme(): 'light' | 'dark' {
  if (typeof document === 'undefined') return 'light';
  return document.documentElement.getAttribute('data-theme') === 'dark' ? 'dark' : 'light';
}

/** Matches design `theme_toggle()` on auth pages (top-right). */
export function ThemeToggle({ className = '' }: { className?: string }) {
  const [theme, setTheme] = useState<'light' | 'dark'>('light');

  useEffect(() => {
    setTheme(readTheme());
  }, []);

  const toggle = () => {
    const next = readTheme() === 'dark' ? 'light' : 'dark';
    document.documentElement.setAttribute('data-theme', next);
    try {
      localStorage.setItem('crm-theme', next);
    } catch {
      // ignore
    }
    setTheme(next);
  };

  const dark = theme === 'dark';

  return (
    <button
      type="button"
      className={`icon-btn theme-toggle ${className}`.trim()}
      data-theme-toggle
      aria-pressed={dark}
      title={dark ? 'Switch to light mode' : 'Switch to dark mode'}
      aria-label={dark ? 'Switch to light mode' : 'Switch to dark mode'}
      onClick={toggle}
    >
      <span className="crm-visually-hidden">Toggle dark mode</span>
      <CrmIcon name="sun" className="iconSize-18 icon-sun" />
      <CrmIcon name="moon" className="iconSize-18 icon-moon" />
    </button>
  );
}
