'use client';

import React, { createContext, useContext, useState, useEffect, ReactNode } from 'react';
import SizeGuideModal from '@/components/ui/SizeGuideModal';

export const AVAILABLE_SIZES = ['39', '40', '41', '42', '43', '44', '45'];

interface SizeContextType {
  selectedSize: string | null;
  selectSize: (size: string) => void;
  clearSize: () => void;
  isSizeAvailable: (size: string) => boolean;
  isSizeGuideOpen: boolean;
  openSizeGuide: () => void;
  closeSizeGuide: () => void;
}

const SizeContext = createContext<SizeContextType | undefined>(undefined);

const STORAGE_KEY = 'rm_selected_size';

export function SizeProvider({ children }: { children: ReactNode }) {
  const [selectedSize, setSelectedSize] = useState<string | null>(null);
  const [isSizeGuideOpen, setIsSizeGuideOpen] = useState(false);

  useEffect(() => {
    try {
      const stored = localStorage.getItem(STORAGE_KEY);
      if (stored && AVAILABLE_SIZES.includes(stored)) {
        setSelectedSize(stored);
      }
    } catch {
      // LocalStorage not available
    }
  }, []);

  const selectSize = (size: string) => {
    setSelectedSize((prev) => {
      const next = prev === size ? null : size;
      try {
        if (next) {
          localStorage.setItem(STORAGE_KEY, next);
        } else {
          localStorage.removeItem(STORAGE_KEY);
        }
      } catch {
        // Storage write failed
      }
      return next;
    });
  };

  const clearSize = () => {
    setSelectedSize(null);
    try {
      localStorage.removeItem(STORAGE_KEY);
    } catch {
      // Storage remove failed
    }
  };

  const isSizeAvailable = (size: string) => {
    return AVAILABLE_SIZES.includes(size);
  };

  const openSizeGuide = () => setIsSizeGuideOpen(true);
  const closeSizeGuide = () => setIsSizeGuideOpen(false);

  return (
    <SizeContext.Provider
      value={{
        selectedSize,
        selectSize,
        clearSize,
        isSizeAvailable,
        isSizeGuideOpen,
        openSizeGuide,
        closeSizeGuide,
      }}
    >
      {children}
      <SizeGuideModal />
    </SizeContext.Provider>
  );
}

export function useSize(): SizeContextType {
  const context = useContext(SizeContext);
  if (!context) {
    throw new Error('useSize must be used within a SizeProvider');
  }
  return context;
}
