"use client";

import { useCart } from "@/context/CartContext";
import CatalogShippingCalculator from "@/components/CatalogShippingCalculator";
import { formatShippingPrice, isPickupShippingOption } from "@/lib/catalog-shipping";
import { X, Minus, Plus, ShoppingBag, Trash2, Flame } from "lucide-react";
import { motion, AnimatePresence } from "framer-motion";
import Image from "next/image";
import { useState } from "react";
import { useRouter } from "next/navigation";
import { normalizeWhatsappForLink } from "@/lib/phone";
import { calculateEffectiveQuantity, checkSaleQuantityLimits } from "@/lib/price-tiers";
import ValorMinimoDoItem from "@/components/ValorMinimoDoItem";
import CupomNoCarrinho from "@/components/CupomNoCarrinho";
import { ensureColorContrast, getAccessibleAccent } from "@/lib/color-contrast";
import { trackCatalogEvent } from "@/lib/catalog-analytics";
import { useVisaoDaLoja } from "@/components/VisaoDaLojaContext";
import { faltaParaOPedidoMinimo } from "@/lib/loja/regras-da-loja";

const EPSILON = 0.000001;

function getAllowedQuantitiesFromItem(item: {
  allowed_sale_qty_enabled?: boolean;
  allowed_sale_quantities?: number[] | null;
}) {
  if (!item.allowed_sale_qty_enabled || !Array.isArray(item.allowed_sale_quantities)) return [];
  const values = item.allowed_sale_quantities
    .map((value) => Number(value))
    .filter((value) => Number.isFinite(value) && value > 0)
    .map((value) => Number(value.toFixed(3)));
  if (!values.length) return [];
  return Array.from(new Set(values)).sort((a, b) => a - b);
}

function resolveAdjacentAllowedQuantity(allowedValues: number[], currentValue: number, direction: -1 | 1) {
  if (!allowedValues.length) return null;
  if (direction < 0) {
    for (let index = allowedValues.length - 1; index >= 0; index -= 1) {
      if (allowedValues[index] + EPSILON < currentValue) return allowedValues[index];
    }
    return null;
  }
  for (let index = 0; index < allowedValues.length; index += 1) {
    if (allowedValues[index] - EPSILON > currentValue) return allowedValues[index];
  }
  return null;
}

export default function CartSidebar({
  primaryColor = "#4F46E5",
  whatsappNumber,
  storeSlug,
  theme,
}: {
  primaryColor?: string,
  whatsappNumber?: string,
  storeSlug?: string,
  theme?: string | null,
}) {
  const router = useRouter();
  /* O que este visitante pode ver e fazer (regras da loja). */
  const visao = useVisaoDaLoja();
  const semPreco = !visao.mostrarPreco;
  const modoOrcamento = visao.modoDeCompra === "quote";
  const textoSemPreco = visao.textoNoLugarDoPreco;
  const {
    isCartOpen,
    toggleCart,
    items,
    updateQuantity,
    removeFromCart,
    clearCart,
    cartSubtotal,
    discountTotal,
    shippingDiscount,
    shippingSelection,
    setShippingSelection,
    shippingItems,
    shippingTotal,
    cartTotal,
    clearCoupon,
    appliedCoupon,
    orderCouponCodes,
    appliedCoupons,
    avisosDeEstoque,
  } = useCart();
  const hasOnRequest = items.some((i) => i.price_on_request);
  /* O pedido minimo da loja (em reais ou em unidades), conferido aqui e de
     novo no servidor. */
  const faltaMinimo = faltaParaOPedidoMinimo(visao.regras, {
    total: cartSubtotal,
    unidades: items.filter((i) => !i.is_combo_item).reduce((soma, i) => soma + Number(i.quantity || 0), 0),
    mostrarPreco: visao.mostrarPreco,
  });
  const [checkoutModalOpen, setCheckoutModalOpen] = useState(false);
  const [checkoutStatus, setCheckoutStatus] = useState<{ type: "success" | "error"; text: string } | null>(null);
  const [quantityStatus, setQuantityStatus] = useState<string | null>(null);
  const [checkoutSubmitting, setCheckoutSubmitting] = useState(false);
  const whatsappLinkDigits = normalizeWhatsappForLink(whatsappNumber);
  /* Checkout próprio (a página /checkout, com pagamento) vale para os temas
     de loja virtual. Sem o Vendor nesta lista, ele caía no fluxo de WhatsApp
     mesmo com pagamento configurado. A Boutique tem carrinho próprio, mas
     entra aqui também: se um dia o CartSidebar a servir, não cai no WhatsApp. */
  const usesDedicatedCheckout =
    (theme === "vitrine" || theme === "vendor" || theme === "boutique") && Boolean(storeSlug?.trim()) && !modoOrcamento;

  const badgeTextColor = ensureColorContrast(primaryColor, "#FFFFFF", {
    dark: "#111827",
    light: "#FFFFFF",
    minRatio: 4.5,
  });

  const formatMoney = (value: number) =>
    new Intl.NumberFormat('pt-BR', { style: 'currency', currency: 'BRL' }).format(value);

  const formatQuantityLimit = (value: number | null) => {
    if (value === null || !Number.isFinite(value)) return "0";
    const rounded = Number(value.toFixed(3));
    return Number.isInteger(rounded)
      ? String(rounded)
      : new Intl.NumberFormat("pt-BR", { minimumFractionDigits: 0, maximumFractionDigits: 3 }).format(rounded);
  };

  const getCheckForQuantity = (item: typeof items[number], quantity: number) =>
    checkSaleQuantityLimits({
      min_sale_qty_enabled: item.min_sale_qty_enabled,
      min_sale_qty: item.min_sale_qty,
      max_sale_qty_enabled: item.max_sale_qty_enabled,
      max_sale_qty: item.max_sale_qty,
      allowed_sale_qty_enabled: item.allowed_sale_qty_enabled,
      allowed_sale_quantities: item.allowed_sale_quantities,
      effectiveQuantity: calculateEffectiveQuantity({
        quantity,
        unit_type: item.unit_type,
        width_m: item.width_m,
        height_m: item.height_m,
        length_m: item.length_m,
      }),
    });

  const getQuantityRuleMessage = (check: ReturnType<typeof getCheckForQuantity>) => {
    if (check.isBelowMin && check.minQty !== null) {
      return `Quantidade minima: ${formatQuantityLimit(check.minQty)}.`;
    }
    if (check.isAboveMax && check.maxQty !== null) {
      return `Quantidade maxima: ${formatQuantityLimit(check.maxQty)}.`;
    }
    if (check.isNotAllowedValue && check.allowedQuantities.length > 0) {
      return `Use quantidade permitida: ${check.allowedQuantities
        .map((value) => formatQuantityLimit(value))
        .join(", ")}.`;
    }
    return "";
  };


  /* Os dados de quem pede, quando nao ha cadastro: o pedido de orcamento
     precisa de um nome e um contato para a loja responder. */
  const [contato, setContato] = useState({ nome: "", whatsapp: "", email: "", observacoes: "" });

  const itensParaOServidor = () =>
    items.map((item) => ({
      product_id: item.product_id,
      name: item.name,
      price: Number(item.price || 0),
      quantity: Number(item.quantity || 0),
      unit_type: item.unit_type || "unit",
      width_m: item.width_m ?? 0,
      height_m: item.height_m ?? 0,
      length_m: item.length_m ?? 0,
      shipping_weight_kg: item.shipping_weight_kg ?? 0,
      shipping_width_cm: item.shipping_width_cm ?? 0,
      shipping_height_cm: item.shipping_height_cm ?? 0,
      shipping_length_cm: item.shipping_length_cm ?? 0,
      variation_description: item.variation_description || "",
      selected_options: item.selected_options || null,
      price_on_request: Boolean(item.price_on_request),
      is_combo_item: Boolean(item.is_combo_item),
      combo_parent_id: item.combo_parent_id || null,
    }));

  /*
    O pedido nasce no servidor (/api/catalog/pedido): e la que o preco vem do
    banco, o cupom e conferido, o frete e validado e a loja e avisada. Antes o
    navegador gravava o pedido direto no banco, com os precos que ele mesmo
    mandava.
  */
  const enviarPedido = async (modo: "whatsapp" | "orcamento", clearAfterOpen: boolean) => {
    if (!storeSlug?.trim()) {
      return { ok: false as const, message: "Loja inválida." };
    }
    try {
      const resposta = await fetch("/api/catalog/pedido", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({
          slug: storeSlug,
          modo,
          items: itensParaOServidor(),
          couponCodes: orderCouponCodes,
          shippingSelection: modo === "whatsapp" ? shippingSelection : null,
          clearAfterOpen,
          customer: { name: contato.nome, whatsapp: contato.whatsapp, email: contato.email, notes: contato.observacoes },
        }),
      });
      const dados = (await resposta.json().catch(() => null)) as
        | { ok?: boolean; order_number?: number | null; whatsapp_url?: string | null; error?: string }
        | null;
      if (!resposta.ok || !dados?.ok) {
        return { ok: false as const, message: dados?.error || "Não foi possível registrar o pedido." };
      }
      return { ok: true as const, numero: dados.order_number ?? null, whatsappUrl: dados.whatsapp_url || "" };
    } catch {
      return { ok: false as const, message: "Não foi possível registrar o pedido. Tente de novo." };
    }
  };

  /* O pedido de orcamento: a lista vai para a loja sem valor nenhum; a loja
     recebe com os precos do cadastro e responde. */
  const enviarPedidoDeOrcamento = async () => {
    if (checkoutSubmitting) return;
    if (!visao.cliente) {
      if (!contato.nome.trim()) {
        setCheckoutStatus({ type: "error", text: "Diga o seu nome para a loja responder." });
        return;
      }
      if (!contato.whatsapp.trim() && !contato.email.trim()) {
        setCheckoutStatus({ type: "error", text: "Informe um WhatsApp ou e-mail para a loja responder." });
        return;
      }
    }
    setCheckoutSubmitting(true);
    if (storeSlug?.trim()) {
      void trackCatalogEvent({ slug: storeSlug, eventName: "checkout_started", meta: { items_count: items.length, quote_request: true } });
    }
    const resultado = await enviarPedido("orcamento", true);
    setCheckoutSubmitting(false);
    if (!resultado.ok) {
      setCheckoutStatus({ type: "error", text: resultado.message });
      return;
    }
    if (storeSlug?.trim()) {
      void trackCatalogEvent({ slug: storeSlug, eventName: "order_created", meta: { items_count: items.length, quote_request: true } });
    }
    clearCoupon();
    clearCart();
    setCheckoutStatus({
      type: "success",
      text: `Pedido de orçamento${resultado.numero ? ` nº ${resultado.numero}` : ""} enviado! A loja vai responder em breve.`,
    });
    if (resultado.whatsappUrl) window.open(resultado.whatsappUrl, "_blank");
  };

  const handleCheckout = async (clearAfterOpen: boolean) => {
    if (checkoutSubmitting) return;
    if (!whatsappLinkDigits) return;
    if (storeSlug?.trim()) {
      void trackCatalogEvent({
        slug: storeSlug,
        eventName: "checkout_started",
        meta: {
          items_count: items.length,
          cart_total: Number(cartTotal.toFixed(2)),
          clear_after_open: clearAfterOpen,
        },
      });
    }
    setCheckoutSubmitting(true);

    const pendingResult = await enviarPedido("whatsapp", clearAfterOpen);
    if (!pendingResult.ok) {
      setCheckoutSubmitting(false);
      setCheckoutStatus({
        type: "error",
        text: pendingResult.message,
      });
      return;
    }
    if (storeSlug?.trim()) {
      void trackCatalogEvent({
        slug: storeSlug,
        eventName: "order_created",
        meta: {
          items_count: items.length,
          cart_total: Number(cartTotal.toFixed(2)),
          clear_after_open: clearAfterOpen,
        },
      });
    }

    // Do not use noopener here because some browsers return null and block our success flow.
    const openedWindow = window.open(pendingResult.whatsappUrl, "_blank");
    if (!openedWindow) {
      setCheckoutSubmitting(false);
      setCheckoutStatus({
        type: "error",
        text: "Nao foi possivel abrir o WhatsApp. Verifique se o navegador bloqueou pop-ups.",
      });
      return;
    }

    if (clearAfterOpen) {
      clearCoupon();
      clearCart();
      setCheckoutModalOpen(false);
      setCheckoutStatus(null);
      if (isCartOpen) {
        toggleCart();
      }
      setCheckoutSubmitting(false);
      return;
    }

    setCheckoutModalOpen(false);
    setCheckoutStatus({
      type: "success",
      text: "Pedido registrado e enviado com carrinho mantido.",
    });
    setCheckoutSubmitting(false);
  };

  return (
    <AnimatePresence>
      {isCartOpen && (
        <>
          <motion.div
            initial={{ opacity: 0 }}
            animate={{ opacity: 0.5 }}
            exit={{ opacity: 0 }}
            onClick={toggleCart}
            className="fixed inset-0 bg-black z-[85]"
          />
          <motion.div
            initial={{ x: "100%" }}
            animate={{ x: 0 }}
            exit={{ x: "100%" }}
            transition={{ type: "tween", duration: 0.3, ease: [0.25, 0.1, 0.25, 1] }}
            className="bg-white shadow-xl z-[86] flex flex-col relative will-change-transform"
            style={{
              position: "fixed",
              right: 0,
              top: 0,
              bottom: 0,
              left: "auto",
              width: "100%",
              maxWidth: "28rem",
              height: "100dvh",
            }}
          >
            <div className="p-4 border-b flex items-center justify-between bg-gray-50">
              <h2 className="text-lg font-bold text-gray-900 flex items-center gap-2">
                <ShoppingBag size={20} />
                {visao.tituloDoCarrinho}
              </h2>
              <button onClick={toggleCart} aria-label="Fechar carrinho" className="p-2 hover:bg-gray-200 rounded-full transition-colors">
                <X size={20} />
              </button>
            </div>

            <div className="flex-1 overflow-y-auto p-4 space-y-4">
              {items.length === 0 ? (
                <div className="h-full flex flex-col items-center justify-center text-gray-400 space-y-4">
                  <ShoppingBag size={48} className="opacity-20" />
                  {checkoutStatus?.type === "success" ? (
                    <p className="max-w-xs rounded-lg border border-emerald-100 bg-emerald-50 px-3 py-2 text-center text-sm text-emerald-700">
                      {checkoutStatus.text}
                    </p>
                  ) : null}
                  <p>{modoOrcamento ? "Sua lista está vazia" : "Seu carrinho está vazio"}</p>
                  <button 
                    onClick={toggleCart}
                    className="text-sm font-medium hover:underline"
                    style={{ color: getAccessibleAccent(primaryColor) }}
                  >
                    Continuar comprando
                  </button>
                </div>
              ) : (
                items
                  .filter(item => !item.combo_parent_id)
                  .map((item) => {
                  const quantityCheck = getCheckForQuantity(item, item.quantity);
                  const quantityRuleMessage = getQuantityRuleMessage(quantityCheck);
                  const allowedQuantities = getAllowedQuantitiesFromItem(item);
                  const nextQuantityDown = allowedQuantities.length
                    ? resolveAdjacentAllowedQuantity(allowedQuantities, item.quantity, -1)
                    : Math.max(1, item.quantity - 1);
                  const nextQuantityUp = allowedQuantities.length
                    ? resolveAdjacentAllowedQuantity(allowedQuantities, item.quantity, 1)
                    : item.quantity + 1;
                  const canDecrease =
                    nextQuantityDown !== null &&
                    nextQuantityDown > 0 &&
                    getCheckForQuantity(item, nextQuantityDown).isValid;
                  const canIncrease =
                    nextQuantityUp !== null &&
                    getCheckForQuantity(item, nextQuantityUp).isValid;

                  const isMainItem = !item.is_combo_item && !item.combo_parent_id;
                    const comboChildren = items.filter(child => child.combo_parent_id === item.id);

                    return (
                      <div key={item.id} className={`flex flex-col ${item.is_combo_item && !item.combo_parent_id ? "opacity-90" : ""}`}>
                        {/* Main Item */}
                        <div className={`flex gap-4 bg-white p-3 rounded-xl border shadow-sm relative z-10 ${comboChildren.length > 0 ? 'border-gray-200 border-b-gray-100 rounded-b-none' : 'border-gray-100'}`}>
                          {item.image_url ? (
                          <Image
                            src={item.image_url}
                            alt={item.name}
                            className="w-20 h-20 object-cover rounded-lg bg-gray-100"
                            width={80}
                            height={80}
                          />
                      ) : (
                          <div className="w-20 h-20 bg-gray-100 rounded-lg flex items-center justify-center">
                              <ShoppingBag className="text-gray-300" />
                          </div>
                      )}
                      <div className="flex-1 flex flex-col justify-between">
                        <div>
                          <div className="flex items-start justify-between gap-2">
                            <h3 className="font-medium text-gray-900 line-clamp-1">{item.name}</h3>
                            {item.is_combo_item && (
                              <span className="text-[9px] font-bold bg-emerald-100 text-emerald-700 px-1.5 py-0.5 rounded uppercase tracking-wider shrink-0">
                                Combo
                              </span>
                            )}
                          </div>
                          {item.variation_description && (
                            <p className="text-[11px] text-gray-500 line-clamp-2 mt-0.5">
                              {item.variation_description}
                            </p>
                          )}
                          {avisosDeEstoque[item.id] ? (
                            /* Estoque v2: o servidor conferiu o carrinho inteiro. */
                            <p className="mt-1 text-[11px] font-semibold text-red-600">{avisosDeEstoque[item.id]}</p>
                          ) : null}
                          {item.unit_type === "square_meter" ? (
                            <div className="space-y-0.5 mt-1">
                               <div className="flex items-center justify-between gap-2">
                                  <p className="text-[10px] text-gray-500 font-medium bg-gray-50 px-1.5 py-0.5 rounded">
                                    {item.price_on_request
                                      ? textoSemPreco
                                      : item.valor_minimo_aplicado != null
                                        ? "Valor mínimo"
                                        : `${formatMoney(item.price)}/m²`}
                                  </p>
                                  {!item.price_on_request && (
                                     <p className="text-sm font-bold text-gray-900">
                                       {formatMoney(
                                         item.valor_minimo_aplicado != null
                                           ? item.valor_minimo_aplicado
                                           : item.price * (item.width_m || 0) * (item.height_m || 0) * item.quantity
                                       )}
                                     </p>
                                  )}
                               </div>
                              {(item.width_m || 0) > 0 && (item.height_m || 0) > 0 && (
                                <p className="text-[10px] text-gray-400">
                                  {new Intl.NumberFormat('pt-BR', { minimumFractionDigits: 2, maximumFractionDigits: 2 }).format(item.width_m as number)}m ×{" "}
                                  {new Intl.NumberFormat('pt-BR', { minimumFractionDigits: 2, maximumFractionDigits: 2 }).format(item.height_m as number)}m
                                </p>
                              )}
                            </div>
                          ) : (
                            <div className="flex items-center justify-between mt-1">
                               <p className="text-[10px] text-gray-500 font-medium bg-gray-50 px-1.5 py-0.5 rounded">
                                 {item.price_on_request
                                   ? textoSemPreco
                                   : item.valor_minimo_aplicado != null
                                     ? "Valor mínimo"
                                     : `${formatMoney(item.price)} un.`}
                               </p>
                               {!item.price_on_request && (
                                 <p className="text-sm font-bold text-gray-900">
                                   {formatMoney(item.valor_minimo_aplicado != null ? item.valor_minimo_aplicado : item.price * item.quantity)}
                                 </p>
                               )}
                            </div>
                          )}
                          {!item.price_on_request && item.valor_minimo_aplicado != null && (
                            <div className="mt-1.5">
                              <ValorMinimoDoItem minimo={item.valor_minimo_aplicado} cor={primaryColor} modo="linha" className="!text-[11px]" />
                            </div>
                          )}
                        </div>
                        <div className="flex items-center justify-between mt-2">
                          {!item.is_combo_item ? (
                            <div className="flex items-center gap-2 bg-gray-50 rounded-lg p-1">
                              <button
                                onClick={() => {
                                  if (nextQuantityDown === null) return;
                                  const result = updateQuantity(item.id, nextQuantityDown);
                                  if (!result.ok) {
                                    setQuantityStatus(result.message || "Nao foi possivel atualizar a quantidade.");
                                    return;
                                  }
                                  setQuantityStatus(null);
                                }}
                                disabled={!canDecrease}
                                aria-label="Diminuir quantidade"
                                className="p-1 hover:bg-white rounded-md shadow-sm transition-all disabled:opacity-40 disabled:cursor-not-allowed"
                              >
                                <Minus size={14} />
                              </button>
                              <span className="text-sm font-medium w-6 text-center">{item.quantity}</span>
                              <button
                                onClick={() => {
                                  if (nextQuantityUp === null) return;
                                  const result = updateQuantity(item.id, nextQuantityUp);
                                  if (!result.ok) {
                                    setQuantityStatus(result.message || "Nao foi possivel atualizar a quantidade.");
                                    return;
                                  }
                                  setQuantityStatus(null);
                                }}
                                disabled={!canIncrease}
                                aria-label="Aumentar quantidade"
                                className="p-1 hover:bg-white rounded-md shadow-sm transition-all disabled:opacity-40 disabled:cursor-not-allowed"
                              >
                                <Plus size={14} />
                              </button>
                            </div>
                          ) : (
                            <div className="text-[11px] text-gray-500 flex items-center">
                              Qtd: <span className="font-medium text-gray-900 ml-1">{item.quantity}</span>
                            </div>
                          )}
                          <button
                            onClick={() => removeFromCart(item.id)}
                            aria-label="Remover item do carrinho"
                            title="Remover item"
                            className="text-red-400 hover:text-red-600 p-2"
                          >
                            <Trash2 size={18} />
                          </button>
                        </div>
                        {quantityRuleMessage && (
                          <p className="mt-1 text-[11px] font-medium text-amber-700">{quantityRuleMessage}</p>
                        )}
                      </div>
                    </div>
                    {/* Combo Children */}
                    {comboChildren.length > 0 && (
                      <div 
                        className="border border-t-0 rounded-b-xl p-3 flex flex-col gap-3 mt-[-4px] pt-4 relative z-0"
                        style={{ 
                          borderColor: `${primaryColor}40`,
                          background: `linear-gradient(to bottom, ${primaryColor}25, ${primaryColor}05)`
                        }}
                      >
                        {comboChildren.map(child => (
                          <div 
                            key={child.id} 
                            className="relative bg-white/95 backdrop-blur-sm p-3 rounded-xl border flex flex-col gap-2 transition-all shadow-sm"
                            style={{ borderColor: `${primaryColor}30` }}
                          >
                            {/* Combo Badge */}
                            <div 
                              className="absolute -top-2.5 -right-2 flex items-center gap-1 px-2 py-0.5 rounded-full text-[9px] font-bold uppercase tracking-wider shadow-sm border-2 border-white"
                              style={{ backgroundColor: primaryColor, color: badgeTextColor }}
                            >
                              <Flame size={10} strokeWidth={3} style={{ color: badgeTextColor === '#FFFFFF' ? '#FDE047' : '#D97706' }} />
                              Compre Junto
                            </div>

                            <div className="flex gap-3">
                              {child.image_url ? (
                                <Image src={child.image_url} alt={child.name} className="w-14 h-14 object-cover rounded-lg bg-gray-50 border border-gray-100 shrink-0" width={56} height={56} />
                              ) : (
                                <div className="w-14 h-14 bg-gray-50 rounded-lg flex items-center justify-center border border-gray-100 shrink-0"><ShoppingBag size={18} className="text-gray-300" /></div>
                              )}
                              
                              <div className="flex-1 min-w-0 flex flex-col justify-between">
                                <div className="flex items-start justify-between gap-1">
                                  <p className="text-sm font-semibold text-gray-800 line-clamp-1 pr-4">{child.name}</p>
                                  <button
                                    onClick={() => removeFromCart(child.id)}
                                    className="text-gray-300 hover:text-red-500 transition-colors absolute right-2 top-2"
                                    title="Remover item do combo"
                                  >
                                    <X size={16} />
                                  </button>
                                </div>
                                
                                {child.variation_description && (
                                  <p className="text-[11px] text-gray-500 line-clamp-1 mt-0.5">
                                    {child.variation_description}
                                  </p>
                                )}
                                {avisosDeEstoque[child.id] ? (
                                  <p className="mt-0.5 text-[11px] font-semibold text-red-600">{avisosDeEstoque[child.id]}</p>
                                ) : null}
                                {(child.width_m || 0) > 0 && (child.height_m || 0) > 0 && (
                                  <p className="text-[11px] text-gray-500 mt-0.5">
                                    Medidas: {new Intl.NumberFormat('pt-BR', { minimumFractionDigits: 2, maximumFractionDigits: 2 }).format(child.width_m as number)}m ×{" "}
                                    {new Intl.NumberFormat('pt-BR', { minimumFractionDigits: 2, maximumFractionDigits: 2 }).format(child.height_m as number)}m
                                  </p>
                                )}

                                <div className="flex items-end justify-between mt-2">
                                  <div className="flex items-center gap-1 bg-gray-50 rounded-lg p-0.5 border border-gray-200">
                                    <button
                                        onClick={() => {
                                          if (child.quantity > 1) {
                                            updateQuantity(child.id, child.quantity - 1);
                                          }
                                        }}
                                        disabled={child.quantity <= 1}
                                        className="w-6 h-6 flex items-center justify-center text-gray-500 hover:text-gray-900 hover:bg-white rounded-md shadow-sm transition-all disabled:opacity-40 disabled:shadow-none"
                                      >
                                        <Minus size={12} strokeWidth={2.5} />
                                      </button>
                                      <input 
                                        type="number"
                                        value={child.quantity}
                                        onChange={(e) => {
                                          let val = parseInt(e.target.value, 10);
                                          if (isNaN(val) || val < 1) val = 1;
                                          updateQuantity(child.id, val);
                                        }}
                                        className="w-7 text-[12px] font-bold text-center text-gray-800 focus:outline-none bg-transparent border-none p-0 hide-arrows"
                                        min="1"
                                      />
                                      <button
                                      onClick={() => {
                                        updateQuantity(child.id, child.quantity + 1);
                                      }}
                                      className="w-6 h-6 flex items-center justify-center text-gray-500 hover:text-gray-900 hover:bg-white rounded-md shadow-sm transition-all"
                                    >
                                      <Plus size={12} strokeWidth={2.5} />
                                    </button>
                                  </div>
                                  <div className="flex flex-col items-end">
                                    <span className="text-sm font-black" style={{ color: getAccessibleAccent(primaryColor) }}>
                                      {child.price_on_request || semPreco ? textoSemPreco : formatMoney(child.price * child.quantity)}
                                    </span>
                                  </div>
                                </div>
                              </div>
                            </div>
                          </div>
                        ))}
                      </div>
                    )}
                  </div>
                  );
                })
              )}
            </div>

            {items.length > 0 && (
              /*
                Teto de altura e rolagem propria: a lista de fretes cresce com
                as opcoes da transportadora e empurrava total, cupom e o botao
                de finalizar para fora da tela, sem rolagem nenhuma. O botao
                fica fixo embaixo para a compra nunca ficar inalcancavel.
              */
              <div className="flex max-h-[68dvh] min-h-0 flex-col border-t bg-gray-50">
                <div className="min-h-0 flex-1 space-y-4 overflow-y-auto p-4">
                {/*
                  Cotacao pelo carrinho inteiro. O simulador so existia na pagina
                  do produto e no checkout, entao quem montava um carrinho com
                  varios itens nao tinha como saber o frete antes de finalizar.
                */}
                {storeSlug && !modoOrcamento && !semPreco ? (
                  <CatalogShippingCalculator
                    slug={storeSlug}
                    primaryColor={primaryColor || "#4425A7"}
                    items={shippingItems}
                    selectedShipping={shippingSelection}
                    onSelectShipping={setShippingSelection}
                    compact
                  />
                ) : null}

                {semPreco ? (
                  /* Sem preco para este visitante nao ha total: a lista vai
                     para a loja, e a loja responde com os valores. */
                  <div className="rounded-lg border border-gray-200 bg-white px-3 py-2 text-xs text-gray-600">
                    {modoOrcamento ? "Os valores vêm no orçamento da loja." : textoSemPreco}
                  </div>
                ) : (
                <div className="space-y-3">
                  <div className="flex items-center justify-between text-sm text-gray-600">
                    <span>Subtotal</span>
                    <span>{formatMoney(cartSubtotal)}</span>
                  </div>
                  {shippingSelection && (
                    <div className="flex items-center justify-between gap-3 text-sm text-gray-600">
                      <span className="truncate">
                        {/* O nome do servico escolhido, nao o da integracao:
                            "Melhor Envio" nao diz nada ao cliente, que escolheu
                            "eFacil" ou "SEDEX". */}
                        {isPickupShippingOption(shippingSelection.option)
                          ? `Retirada (${shippingSelection.option.service})`
                          : `Frete${
                              shippingSelection.option.service
                                ? ` (${shippingSelection.option.service})`
                                : ""
                            }`}
                      </span>
                      <span className="shrink-0">{formatShippingPrice(shippingTotal)}</span>
                    </div>
                  )}
                  {appliedCoupons
                    .filter((c) => c.discount > 0 || c.shippingDiscount > 0)
                    .map((c) => (
                      <div key={c.code} className="flex items-center justify-between gap-3 text-sm text-emerald-600">
                        <span className="truncate">
                          {c.slot === "frete" ? "Frete grátis" : "Desconto"} ({c.automatic ? c.name : c.code})
                        </span>
                        <span className="shrink-0">-{formatMoney(c.slot === "frete" ? Math.min(c.shippingDiscount, shippingDiscount) : c.discount)}</span>
                      </div>
                    ))}
                  <div className="flex items-center justify-between text-lg font-bold text-gray-900">
                    <span>{hasOnRequest ? "Total parcial" : "Total"}</span>
                    <span>{formatMoney(cartTotal)}</span>
                  </div>
                </div>
                )}
                {visao.avisoDePreco && !semPreco ? (
                  <p className="text-[11px] text-gray-500">{visao.avisoDePreco}</p>
                ) : null}
                {!semPreco && !modoOrcamento && (
                <CupomNoCarrinho corDaLoja={primaryColor} />
                )}
                {hasOnRequest && !semPreco && (
                  <div className="text-xs text-gray-500">
                    Itens “{textoSemPreco}” não entram no total parcial.
                  </div>
                )}
                {faltaMinimo ? (
                  <div className="text-xs rounded-lg px-3 py-2 bg-amber-50 text-amber-700 border border-amber-100">{faltaMinimo}</div>
                ) : null}
                {modoOrcamento && !visao.cliente ? (
                  <div className="space-y-2 rounded-xl border border-gray-200 bg-white p-3">
                    <p className="text-xs font-semibold uppercase tracking-wide text-gray-500">Para a loja responder</p>
                    <input
                      value={contato.nome}
                      onChange={(e) => setContato((atual) => ({ ...atual, nome: e.target.value }))}
                      placeholder="Seu nome"
                      autoComplete="name"
                      className="w-full rounded-lg border border-gray-200 px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-indigo-500/20"
                    />
                    <input
                      value={contato.whatsapp}
                      onChange={(e) => setContato((atual) => ({ ...atual, whatsapp: e.target.value }))}
                      placeholder="WhatsApp"
                      inputMode="tel"
                      autoComplete="tel"
                      className="w-full rounded-lg border border-gray-200 px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-indigo-500/20"
                    />
                    <input
                      value={contato.email}
                      onChange={(e) => setContato((atual) => ({ ...atual, email: e.target.value }))}
                      placeholder="E-mail (opcional)"
                      inputMode="email"
                      autoComplete="email"
                      className="w-full rounded-lg border border-gray-200 px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-indigo-500/20"
                    />
                    <textarea
                      value={contato.observacoes}
                      onChange={(e) => setContato((atual) => ({ ...atual, observacoes: e.target.value }))}
                      placeholder="Observações (opcional)"
                      rows={2}
                      className="w-full rounded-lg border border-gray-200 px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-indigo-500/20"
                    />
                  </div>
                ) : modoOrcamento ? (
                  <textarea
                    value={contato.observacoes}
                    onChange={(e) => setContato((atual) => ({ ...atual, observacoes: e.target.value }))}
                    placeholder="Observações para a loja (opcional)"
                    rows={2}
                    className="w-full rounded-lg border border-gray-200 bg-white px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-indigo-500/20"
                  />
                ) : null}
                {checkoutStatus && (
                  <div className={`text-xs rounded-lg px-3 py-2 ${checkoutStatus.type === "success" ? "bg-emerald-50 text-emerald-600 border border-emerald-100" : "bg-rose-50 text-rose-600 border border-rose-100"}`}>
                    {checkoutStatus.text}
                  </div>
                )}
                {quantityStatus && (
                  <div className="text-xs rounded-lg px-3 py-2 bg-amber-50 text-amber-700 border border-amber-100">
                    {quantityStatus}
                  </div>
                )}
                </div>

                <div className="shrink-0 border-t border-gray-200 bg-gray-50 p-4">
                <button
                  onClick={() => {
                    setCheckoutStatus(null);
                    /* Preco so para quem entrou, ou cadastro exigido para fechar:
                       primeiro o login, depois o pedido. */
                    if (visao.precisaEntrar || (visao.exigeLoginParaFechar && !visao.cliente)) {
                      if (isCartOpen) toggleCart();
                      router.push(`/${storeSlug}/cliente/login?next=${encodeURIComponent(window.location.pathname)}`);
                      return;
                    }
                    if (!visao.podeComprar) return;
                    if (modoOrcamento) {
                      void enviarPedidoDeOrcamento();
                      return;
                    }
                    if (usesDedicatedCheckout) {
                      if (isCartOpen) toggleCart();
                      router.push(`/${storeSlug}/checkout`);
                      return;
                    }
                    setCheckoutModalOpen(true);
                  }}
                  disabled={
                    checkoutSubmitting ||
                    (!visao.podeComprar && !visao.precisaEntrar) ||
                    (!modoOrcamento && !visao.precisaEntrar && !whatsappLinkDigits) ||
                    (Boolean(faltaMinimo) && !visao.precisaEntrar)
                  }
                  className="w-full py-3.5 px-4 rounded-xl font-bold shadow-lg hover:opacity-90 active:scale-[0.98] transition-all disabled:opacity-50 disabled:cursor-not-allowed flex items-center justify-center gap-2"
                  style={{
                    backgroundColor: modoOrcamento || visao.precisaEntrar ? primaryColor : whatsappLinkDigits ? "#25D366" : "gray",
                    color: modoOrcamento || visao.precisaEntrar ? badgeTextColor : "#ffffff",
                  }}
                >
                  {checkoutSubmitting
                    ? "Enviando..."
                    : visao.precisaEntrar
                      ? visao.regras.textoPrecoLogin
                      : !visao.podeComprar
                        ? (visao.motivoDoBloqueio || "Indisponível")
                        : modoOrcamento
                          ? (visao.rotuloDeFechar || "Enviar pedido de orçamento")
                          : whatsappLinkDigits
                            ? usesDedicatedCheckout
                              ? "Continuar para finalizar"
                              : (visao.rotuloDeFechar || "Finalizar Pedido no WhatsApp")
                            : "Loja sem WhatsApp configurado"}
                </button>
                </div>
              </div>
            )}
            <AnimatePresence>
              {checkoutModalOpen && items.length > 0 && (
                <>
                  <motion.button
                    type="button"
                    initial={{ opacity: 0 }}
                    animate={{ opacity: 1 }}
                    exit={{ opacity: 0 }}
                    onClick={() => setCheckoutModalOpen(false)}
                    className="absolute inset-0 bg-black/30 z-10"
                  />
                  <motion.div
                    initial={{ opacity: 0, y: 12, scale: 0.98 }}
                    animate={{ opacity: 1, y: 0, scale: 1 }}
                    exit={{ opacity: 0, y: 12, scale: 0.98 }}
                    transition={{ duration: 0.15 }}
                    className="absolute left-4 right-4 bottom-4 z-20 bg-white border border-gray-200 rounded-2xl shadow-xl p-4 space-y-3"
                  >
                    <h3 className="text-sm font-bold text-gray-900">Como deseja finalizar?</h3>
                    <p className="text-xs text-gray-600">Abriremos o WhatsApp com este pedido.</p>
                    <button
                      onClick={() => handleCheckout(true)}
                      disabled={checkoutSubmitting}
                      className="w-full py-2.5 px-3 rounded-xl text-white font-semibold disabled:opacity-60"
                      style={{ backgroundColor: "#25D366" }}
                    >
                      {checkoutSubmitting ? "Registrando..." : "Finalizar e limpar carrinho"}
                    </button>
                    <button
                      onClick={() => handleCheckout(false)}
                      disabled={checkoutSubmitting}
                      className="w-full py-2.5 px-3 rounded-xl font-semibold text-gray-700 border border-gray-200 hover:bg-gray-50 disabled:opacity-60"
                    >
                      {checkoutSubmitting ? "Registrando..." : "Finalizar e manter carrinho"}
                    </button>
                    <button
                      onClick={() => !checkoutSubmitting && setCheckoutModalOpen(false)}
                      disabled={checkoutSubmitting}
                      className="w-full py-2.5 px-3 rounded-xl font-semibold text-gray-500 hover:bg-gray-50 disabled:opacity-60"
                    >
                      Cancelar
                    </button>
                  </motion.div>
                </>
              )}
            </AnimatePresence>
          </motion.div>
        </>
      )}
    </AnimatePresence>
  );
}
