import { useCallback, useEffect, useState } from 'react';
import { getStoredTheme, setTheme as persistTheme, type Theme } from '@/lib/theme';

export function useTheme(): { theme: Theme; setTheme: (t: Theme) => void } {
  const [theme, setLocal] = useState<Theme>(getStoredTheme);
  const set = useCallback((t: Theme) => {
    persistTheme(t);
    setLocal(t);
  }, []);
  useEffect(() => {
    if (theme !== 'system') return;
    const mq = window.matchMedia('(prefers-color-scheme: dark)');
    const handler = () => setLocal('system');
    mq.addEventListener('change', handler);
    return () => mq.removeEventListener('change', handler);
  }, [theme]);
  return { theme, setTheme: set };
}
