'use client';

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

const STORAGE_KEY = 'tracker_selected_product';

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);

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

  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;
}
