"use client";

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

export type TextSize = "small" | "medium" | "large";

interface TextSizeContextValue {
  textSize: TextSize;
  updateTextSize: (size: TextSize) => void;
  labels: {
    ar: { small: string; medium: string; large: string };
    en: { small: string; medium: string; large: string };
  };
  sizes: {
    ar: { small: string; medium: string; large: string };
    en: { small: string; medium: string; large: string };
  };
}

const TextSizeContext = createContext<TextSizeContextValue | undefined>(
  undefined,
);

const STORAGE_KEY = "blog-text-size";
const DEFAULT_SIZE: TextSize = "medium";
const VALID_SIZES: TextSize[] = ["small", "medium", "large"];

interface TextSizeProviderProps {
  children: ReactNode;
}

export function TextSizeProvider({ children }: TextSizeProviderProps) {
  const [textSize, setTextSize] = useState<TextSize>(DEFAULT_SIZE);
  const [mounted, setMounted] = useState(false);

  // Load saved preference from localStorage on mount
  useEffect(() => {
    setMounted(true);

    // Check if window is available (SSR safety)
    if (typeof window !== "undefined") {
      try {
        const saved = localStorage.getItem(STORAGE_KEY) as TextSize;
        if (saved && VALID_SIZES.includes(saved)) {
          setTextSize(saved);
        }
      } catch (error) {
        // localStorage might be blocked or unavailable
        console.error("Failed to load text size preference:", error);
      }
    }
  }, []);

  const updateTextSize = (size: TextSize) => {
    if (!VALID_SIZES.includes(size)) {
      console.error(`Invalid text size: ${size}`);
      return;
    }

    setTextSize(size);

    // Persist to localStorage
    if (typeof window !== "undefined") {
      try {
        localStorage.setItem(STORAGE_KEY, size);
      } catch (error) {
        // localStorage might be blocked or unavailable
        console.error("Failed to save text size preference:", error);
      }
    }
  };

  // Bilingual labels
  const labels = {
    ar: {
      small: "صغير",
      medium: "متوسط",
      large: "كبير",
    },
    en: {
      small: "Small",
      medium: "Medium",
      large: "Large",
    },
  };

  // Bilingual size labels
  const sizes = {
    ar: {
      small: "14 بكسل",
      medium: "18 بكسل",
      large: "22 بكسل",
    },
    en: {
      small: "14px",
      medium: "18px",
      large: "22px",
    },
  };

  const value: TextSizeContextValue = {
    textSize: mounted ? textSize : DEFAULT_SIZE,
    updateTextSize,
    labels,
    sizes,
  };

  return (
    <TextSizeContext.Provider value={value}>
      {children}
    </TextSizeContext.Provider>
  );
}

export function useTextSize() {
  const context = useContext(TextSizeContext);

  if (context === undefined) {
    throw new Error("useTextSize must be used within a TextSizeProvider");
  }

  return context;
}
