"use client";

import { useState } from "react";

import { AddToCartButton } from "@/components/cart/AddToCartButton";
import { QuantitySelector } from "@/components/cart/QuantitySelector";
import type { Product } from "@/types/product";

/**
 * Quantity selector and add-to-cart button, wired together.
 *
 * They share one piece of state, so the quantity chosen here is the quantity
 * that lands in the cart. The server-rendered product page stays a Server
 * Component and hands this island a plain product object.
 */
export function ProductPurchasePanel({ product }: { product: Product }) {
  const [quantity, setQuantity] = useState(1);
  const maxQuantity = Math.max(1, product.stock);

  return (
    <div className="flex flex-wrap items-center gap-3">
      <QuantitySelector
        value={quantity}
        onChange={setQuantity}
        max={maxQuantity}
        disabled={product.stock <= 0}
      />
      <AddToCartButton
        product={product}
        quantity={quantity}
        className="px-6 py-3 text-base"
        label={quantity > 1 ? `Add ${quantity} to cart` : undefined}
      />
    </div>
  );
}
