'use client';

import { createContext, useContext, useState, useCallback, useEffect, type ReactNode } from 'react';
import { KNOWN_PRODUCTS, PRODUCT_ID } from '@/lib/product-constants';

const STORAGE_KEY = 'admin_selected_product';
const PRODUCT_CHANGED_EVENT = 'admin:product-changed';

interface ProductContextValue {
  productId: string;
  productName: string;
  setProductId: (id: string) => void;
  products: typeof KNOWN_PRODUCTS;
}

const ProductContext = createContext<ProductContextValue | null>(null);

function getInitialProduct(): string {
  if (typeof window === 'undefined') return PRODUCT_ID;
  return localStorage.getItem(STORAGE_KEY) || PRODUCT_ID;
}

export function ProductProvider({ children }: { children: ReactNode }) {
  const [productId, setProductIdState] = useState<string>(getInitialProduct);

  useEffect(() => {
    function syncSelectedProduct() {
      setProductIdState(getInitialProduct());
    }

    window.addEventListener(PRODUCT_CHANGED_EVENT, syncSelectedProduct);
    window.addEventListener('storage', syncSelectedProduct);
    return () => {
      window.removeEventListener(PRODUCT_CHANGED_EVENT, syncSelectedProduct);
      window.removeEventListener('storage', syncSelectedProduct);
    };
  }, []);

  const setProductId = useCallback((id: string) => {
    setProductIdState(id);
    if (typeof window !== 'undefined') {
      localStorage.setItem(STORAGE_KEY, id);
      window.dispatchEvent(new Event(PRODUCT_CHANGED_EVENT));
    }
  }, []);

  const product = KNOWN_PRODUCTS.find(p => p.id === productId);
  const productName = product?.name ?? productId;

  return (
    <ProductContext.Provider
      value={{ productId, productName, setProductId, products: KNOWN_PRODUCTS }}
    >
      {children}
    </ProductContext.Provider>
  );
}

export function useProduct(): ProductContextValue {
  const ctx = useContext(ProductContext);
  if (!ctx) throw new Error('useProduct must be used within <ProductProvider>');
  return ctx;
}
