
import React, { createContext, useContext, useState, useEffect } from 'react';

const FontCustomizationContext = createContext(null);

export const useFontCustomization = () => {
  const context = useContext(FontCustomizationContext);
  if (!context) {
    throw new Error('useFontCustomization must be used within a FontCustomizationProvider');
  }
  return context;
};

export const FontCustomizationProvider = ({ children }) => {
  const [globalFontPreferences, setGlobalFontPreferences] = useState({
    family: 'Inter',
    size: '12',
    weight: 'normal'
  });

  const [elementFonts, setElementFonts] = useState({});

  useEffect(() => {
    const saved = localStorage.getItem('global_font_preferences');
    if (saved) {
      try {
        setGlobalFontPreferences(JSON.parse(saved));
      } catch (e) {
        console.error('Failed to parse saved font preferences', e);
      }
    }
  }, []);

  const updateGlobalPreference = (key, value) => {
    const newPrefs = { ...globalFontPreferences, [key]: value };
    setGlobalFontPreferences(newPrefs);
    localStorage.setItem('global_font_preferences', JSON.stringify(newPrefs));
  };

  const getFontForElement = (elementId) => {
    return elementFonts[elementId] || globalFontPreferences;
  };

  const setFontForElement = (elementId, settings) => {
    setElementFonts(prev => ({
      ...prev,
      [elementId]: { ...prev[elementId], ...settings }
    }));
  };

  const clearElementFont = (elementId) => {
    setElementFonts(prev => {
      const next = { ...prev };
      delete next[elementId];
      return next;
    });
  };

  return (
    <FontCustomizationContext.Provider value={{
      globalFontPreferences,
      updateGlobalPreference,
      elementFonts,
      setElementFonts,
      getFontForElement,
      setFontForElement,
      clearElementFont
    }}>
      {children}
    </FontCustomizationContext.Provider>
  );
};
