"use client";

import { useCallback, useRef, useState, type ReactNode } from "react";
import { CartUIContext } from "./CartUIContext";
import { CartSideDrawer } from "./containers/CartSideDrawer";
import { CartBottomSheet } from "./containers/CartBottomSheet";

/**
 * Provides cart overlay state (drawer on lg+, sheet on smaller in Phase 4).
 * Open/close state is React state (single source of truth); Phase 5 can add
 * cart item count for badge. Only one of drawer vs sheet is shown per breakpoint.
 */
export function CartUIProvider({ children }: { children: ReactNode }) {
  const [isOpen, setIsOpen] = useState(false);
  const triggerRef = useRef<HTMLElement | null>(null);

  const openCart = useCallback((triggerElement?: HTMLElement | null) => {
    if (triggerElement) triggerRef.current = triggerElement;
    setIsOpen(true);
  }, []);

  const closeCart = useCallback(() => {
    const trigger = triggerRef.current;
    triggerRef.current = null;
    setIsOpen(false);
    // Return focus to trigger after overlay unmounts (Phase 6 a11y)
    if (trigger?.focus) {
      setTimeout(() => trigger.focus({ preventScroll: true }), 0);
    }
  }, []);

  return (
    <CartUIContext.Provider value={{ isOpen, openCart, closeCart }}>
      {children}
      <CartSideDrawer />
      <CartBottomSheet />
    </CartUIContext.Provider>
  );
}
