"use client";

import { Chip, Separator } from "@heroui/react";
import type { CartContentProps } from "@/lib/cart/types";
import { CartLineItems } from "./CartLineItems";
import { CartSummaryCard } from "./CartOrderSummary";
import { CartActions } from "./CartActions";
import { CartEmptyState } from "./CartEmptyState";

/**
 * Shared cart content composed from CartLineItems, CartSummaryCard, and CartActions.
 * Used in cart page, side drawer (lg+), and bottom sheet (< lg).
 * Presentational: receives items and callbacks; data/mutations live at container level.
 */
export function CartContent({
  items,
  subtotal,
  onUpdateQuantity,
  onRemove,
  isEmpty,
  onCheckout,
  onViewFullCart,
  onClose,
  hideHeading = false,
  layout = "overlay",
}: CartContentProps) {
  const itemCount = items.reduce((sum, i) => sum + i.quantity, 0);

  if (isEmpty) {
    return (
      <div className="flex flex-col gap-6">
        {!hideHeading && (
          <header className="flex items-center gap-2">
            <h2 className="text-xl font-semibold font-[family-name:var(--font-fraunces)]">
              Cart
            </h2>
            <Chip size="sm" variant="soft">
              0
            </Chip>
          </header>
        )}
        <CartEmptyState onClose={onClose} />
      </div>
    );
  }

  const heading = !hideHeading && (
    <header className="flex items-center gap-2">
      <h2 className="text-xl font-semibold font-[family-name:var(--font-fraunces)]">
        Cart
      </h2>
      <Chip size="sm" variant="soft" className="bg-[#e8f7f6] text-[var(--foreground)]">
        {itemCount}
      </Chip>
    </header>
  );

  const lineItems = (
    <CartLineItems
      items={items}
      onUpdateQuantity={onUpdateQuantity}
      onRemove={onRemove}
      variant={layout === "page" ? "full" : "compact"}
    />
  );

  const isOverlay = layout === "overlay";

  if (layout === "page") {
    return (
      <div className="flex flex-col gap-6">
        {heading}
        <div className="grid grid-cols-1 gap-6 lg:grid-cols-[1fr,360px] lg:items-start">
          <div>{lineItems}</div>
          <div className="lg:sticky lg:top-8 lg:self-start">
            <div className="flex flex-col gap-4">
              <CartSummaryCard subtotal={subtotal} display="card" />
              <CartActions
                onCheckout={onCheckout}
                onViewFullCart={onViewFullCart}
                onClose={onClose}
                layout="page"
              />
            </div>
          </div>
        </div>
      </div>
    );
  }

  return (
    <div className="flex flex-col gap-4">
      {heading}
      {lineItems}
      <Separator className="my-1" />
      <CartSummaryCard subtotal={subtotal} display="inline" />
      <CartActions
        onCheckout={onCheckout}
        onViewFullCart={isOverlay ? onViewFullCart : undefined}
        onClose={onClose}
        layout="overlay"
      />
    </div>
  );
}
