"use client";

import { CartPageLayout } from "@/components/cart/containers/CartPageLayout";
import { CartContent } from "@/components/cart/content/CartContent";
import { CartContentSkeleton } from "@/components/cart/state/CartContentSkeleton";
import { CartErrorState } from "@/components/cart/state/CartErrorState";
import { useCart } from "@/lib/cart/useCart";
import { useCartMutations } from "@/lib/cart/useCartMutations";
import { useCartSessionId } from "@/lib/cart/useCartSessionId";

/**
 * Cart page: wires Convex data and mutations to shared CartContent.
 * Shows skeleton while loading, error state on failure, otherwise CartContent with real data.
 */
export function CartPageView() {
  const sessionId = useCartSessionId();
  const { items, subtotal, isLoading, error } = useCart(sessionId);
  const { updateItem, removeItem } = useCartMutations(sessionId);

  if (isLoading) {
    return (
      <CartPageLayout itemCount={0}>
        <CartContentSkeleton />
      </CartPageLayout>
    );
  }

  if (error) {
    return (
      <CartPageLayout itemCount={0}>
        <CartErrorState
          message={error.message ?? "Something went wrong loading your cart."}
          onRetry={() => window.location.reload()}
        />
      </CartPageLayout>
    );
  }

  const itemCount = items.reduce((sum, i) => sum + i.quantity, 0);

  return (
    <CartPageLayout itemCount={itemCount}>
      <CartContent
        items={items}
        subtotal={subtotal}
        onUpdateQuantity={updateItem}
        onRemove={removeItem}
        isEmpty={items.length === 0}
        onViewFullCart={undefined}
        hideHeading
        layout="page"
      />
    </CartPageLayout>
  );
}
