'use client';

import { useState, useEffect, useCallback } from 'react';

const STORAGE_KEY = 'spanglish-admin-stats-hidden';

export function useStatsPrivacy() {
  const [showStats, setShowStatsState] = useState(true);

  useEffect(() => {
    if (typeof window === 'undefined') return;
    try {
      const stored = localStorage.getItem(STORAGE_KEY);
      if (stored !== null) {
        setShowStatsState(stored !== 'true');
      }
    } catch {
      // ignore
    }
  }, []);

  const setShowStats = useCallback((value: boolean | ((prev: boolean) => boolean)) => {
    setShowStatsState((prev) => {
      const next = typeof value === 'function' ? value(prev) : value;
      try {
        if (typeof window !== 'undefined') {
          localStorage.setItem(STORAGE_KEY, String(!next));
        }
      } catch {
        // ignore
      }
      return next;
    });
  }, []);

  const toggleStats = useCallback(() => {
    setShowStats((prev) => !prev);
  }, [setShowStats]);

  return [showStats, setShowStats, toggleStats] as const;
}
