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

interface Settings {
  uiZoom: number;
}

const DEFAULT_SETTINGS: Settings = {
  uiZoom: 100,
};

export const useSettings = () => {
  const [settings, setSettings] = useState<Settings>(DEFAULT_SETTINGS);
  const [isLoaded, setIsLoaded] = useState(false);

  // Load settings from localStorage
  useEffect(() => {
    const loadSettings = () => {
      try {
        const saved = localStorage.getItem('typogenie-settings');
        if (saved) {
          const parsed = JSON.parse(saved);
          const merged = { ...DEFAULT_SETTINGS, ...parsed };
          setSettings(merged);
          // Apply zoom immediately on load
          applyZoom(merged.uiZoom);
        }
      } catch (e) {
        console.error('Failed to load settings:', e);
      }
      setIsLoaded(true);
    };
    loadSettings();
  }, []);

  // Apply zoom using font-size scaling on root element
  // This is the most reliable way to scale UI while preserving scrollability
  const applyZoom = (zoom: number) => {
    const scale = zoom / 100;
    const root = document.documentElement;
    
    // Base font size is 16px, scale it
    root.style.fontSize = `${16 * scale}px`;
    
    // Store zoom value as CSS variable for other calculations
    root.style.setProperty('--ui-zoom', String(scale));
    root.style.setProperty('--ui-zoom-percent', `${zoom}%`);
    
    // Adjust the app container
    const appRoot = document.getElementById('root');
    if (appRoot) {
      // Remove any transform-based scaling
      appRoot.style.transform = 'none';
      appRoot.style.width = '100%';
      appRoot.style.height = '100%';
    }
  };

  // Save settings when they change
  const saveSettings = useCallback((newSettings: Partial<Settings>) => {
    const updated = { ...settings, ...newSettings };
    setSettings(updated);
    
    // Apply zoom immediately
    if (newSettings.uiZoom !== undefined) {
      applyZoom(newSettings.uiZoom);
    }
    
    try {
      localStorage.setItem('typogenie-settings', JSON.stringify(updated));
    } catch (e) {
      console.error('Failed to save settings:', e);
    }
  }, [settings]);

  const setUiZoom = useCallback((zoom: number) => {
    const clamped = Math.max(50, Math.min(200, zoom));
    saveSettings({ uiZoom: clamped });
  }, [saveSettings]);

  return {
    settings,
    isLoaded,
    setUiZoom,
    uiZoom: settings.uiZoom,
  };
};
