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

const FontSettingsContext = createContext(null);

const STORAGE_KEY = "supersam-font-settings";

// Categories: key → { label, defaultScale, min, max, step, description }
export const FONT_CATEGORIES = [
  { key: "table", label: "Таблицы", description: "Текст в таблицах и списках", defaultScale: 1.0, min: 0.8, max: 1.5, step: 0.05 },
  { key: "card", label: "Карточки", description: "Текст в карточках и панелях", defaultScale: 1.0, min: 0.8, max: 1.5, step: 0.05 },
  { key: "nav", label: "Меню и навигация", description: "Пункты меню, вкладки, кнопки", defaultScale: 1.0, min: 0.8, max: 1.5, step: 0.05 },
  { key: "heading", label: "Заголовки", description: "Названия секций и страниц", defaultScale: 1.0, min: 0.8, max: 1.6, step: 0.05 },
  { key: "body", label: "Основной текст", description: "Обычный текст в интерфейсе", defaultScale: 1.0, min: 0.8, max: 1.5, step: 0.05 },
  { key: "small", label: "Мелкий текст", description: "Подписи, метки, временные отметки", defaultScale: 1.0, min: 0.8, max: 1.5, step: 0.05 },
];

const DEFAULT_SETTINGS = FONT_CATEGORIES.reduce((acc, cat) => {
  acc[cat.key] = cat.defaultScale;
  return acc;
}, {});

function loadSettings() {
  try {
    const raw = localStorage.getItem(STORAGE_KEY);
    if (!raw) return { ...DEFAULT_SETTINGS };
    const parsed = JSON.parse(raw);
    // Merge with defaults to handle new categories
    return { ...DEFAULT_SETTINGS, ...parsed };
  } catch {
    return { ...DEFAULT_SETTINGS };
  }
}

function applySettings(settings) {
  const root = document.documentElement;
  for (const cat of FONT_CATEGORIES) {
    root.style.setProperty(`--fs-scale-${cat.key}`, String(settings[cat.key] ?? 1.0));
  }
}

export const FontSettingsProvider = ({ children }) => {
  const [settings, setSettings] = useState(loadSettings);

  useEffect(() => {
    applySettings(settings);
    localStorage.setItem(STORAGE_KEY, JSON.stringify(settings));
  }, [settings]);

  const updateCategory = (key, scale) => {
    setSettings((prev) => ({ ...prev, [key]: scale }));
  };

  const resetAll = () => {
    setSettings({ ...DEFAULT_SETTINGS });
  };

  const value = {
    settings,
    updateCategory,
    resetAll,
    categories: FONT_CATEGORIES,
  };

  return <FontSettingsContext.Provider value={value}>{children}</FontSettingsContext.Provider>;
};

export const useFontSettings = () => {
  const context = useContext(FontSettingsContext);
  if (!context) {
    throw new Error("useFontSettings must be used within FontSettingsProvider");
  }
  return context;
};