/**
 * CMS ELEMENT: buy-box
 * Shopware element type `buy-box` — the purchase column on a product detail
 * CMS layout. Reads the resolved product from `slot.data.product` (injected by
 * resolveProductCmsSlots) and reuses the same buy widgets as the PDP.
 */

import Link from 'next/link';
import AddToCartButton from '@/components/product/AddToCartButton';
import WishlistButton from '@/components/product/WishlistButton';
import ProductVariantSelector from '@/components/product/ProductVariantSelector';
import { formatPrice, groupRawOptions, type ShopwareProduct } from '@/lib/shopware-api';
import type { CmsSlot } from '@/components/cms/types';

export default function CmsElementBuyBox({ slot }: { slot: CmsSlot }) {
  const product: ShopwareProduct | undefined = slot.data?.product;
  if (!product) return null;

  const price = product.calculatedPrice?.unitPrice ?? product.price?.[0]?.gross ?? 0;
  const listPrice = product.calculatedPrice?.listPrice?.price;
  const deliveryTime = product.deliveryTime?.translated?.name || product.deliveryTime?.name;
  const shippingFree = product.shippingFree;
  const parentId = product.parentId || product.id;

  // Variant options, if Shopware resolved a configurator into the slot.
  const rawConfigurator =
    slot.data?.configuratorSettings?.elements ??
    slot.data?.configuratorSettings ??
    slot.data?.configurator ??
    [];
  const configuratorElements =
    Array.isArray(rawConfigurator) && rawConfigurator.length > 0
      ? groupRawOptions(rawConfigurator).elements
      : [];

  return (
    <div className="flex flex-col">
      {/* Price */}
      {price > 0 && (
        <div className="mb-4 flex items-baseline gap-3">
          <span className="text-3xl font-bold">{formatPrice(price)}</span>
          {listPrice && listPrice > price && (
            <>
              <span className="text-lg text-surface-400 line-through">{formatPrice(listPrice)}</span>
              <span className="text-sm font-semibold text-red-500 bg-red-50 px-2 py-0.5 rounded-md">
                -{Math.round(((listPrice - price) / listPrice) * 100)}%
              </span>
            </>
          )}
        </div>
      )}

      {/* VAT note */}
      {price > 0 && (
        <p className="text-xs text-surface-500 mb-4">
          Prices incl. VAT plus{' '}
          <Link href="/shipping-info" className="text-brand-500 hover:underline">shipping costs</Link>
        </p>
      )}

      {/* Delivery / shipping */}
      {deliveryTime && (
        <div className="flex items-center gap-2 mb-3 text-sm">
          <span className="w-2.5 h-2.5 rounded-full bg-green-500 flex-shrink-0" />
          <span className="text-surface-600">Available, delivery time: {deliveryTime}</span>
        </div>
      )}
      {shippingFree && (
        <div className="flex items-center gap-1.5 mb-3 text-sm">
          <span className="w-2 h-2 rounded-full bg-brand-500 flex-shrink-0" />
          <span className="text-surface-600">Free shipping</span>
        </div>
      )}

      {/* Variant selector */}
      {configuratorElements.length > 0 && (
        <div className="mb-6 mt-2">
          <ProductVariantSelector
            parentId={parentId}
            selectedOptionIds={product.optionIds || []}
            elements={configuratorElements}
          />
        </div>
      )}

      {/* Add to cart */}
      {price > 0 ? (
        <AddToCartButton productId={product.id} />
      ) : configuratorElements.length > 0 ? (
        <p className="text-sm text-surface-500">Please select your options above to see the price.</p>
      ) : null}

      {/* Wishlist */}
      <div className="mt-3">
        <WishlistButton productId={product.id} variant="detail" />
      </div>

      {/* Product number */}
      <p className="text-sm text-surface-500 mt-4 font-medium">
        Product number: {product.productNumber}
      </p>
    </div>
  );
}
