"use client";

import { useCallback, useEffect, useMemo, useRef, useState, type CSSProperties } from "react";
import { ShoppingBag, Search, Truck, CreditCard, ShieldCheck, ChevronLeft, ChevronRight, ChevronDown, ChevronUp, Package, Flame, Clock, BadgeCheck, MapPin, Headphones, Building2, Phone, MessageCircle, Instagram, Facebook, Linkedin, Twitter, Youtube, X, Tag, Copy, Check, Percent, Menu, Home, House, Heart, UserCircle2, User, LogOut, ArrowRight, Sparkles, Eye, DollarSign, LayoutGrid, Download, PlayCircle } from "lucide-react";
import Link from "next/link";
import Image from "next/image";
import { usePathname, useRouter, useSearchParams } from "next/navigation";
import { AnimatePresence, motion } from "framer-motion";
import AddToCartButton from "@/components/AddToCartButton";
import CartTrigger from "@/components/CartTrigger";
import CatalogMobileBottomNav from "@/components/CatalogMobileBottomNav";
import CatalogInfoStripMobile from "@/components/CatalogInfoStripMobile";
import { getSupabaseClient } from "@/lib/supabase";
import { trackCatalogEvent } from "@/lib/catalog-analytics";
import { normalizeWhatsappForLink } from "@/lib/phone";
import { destinoDoLink } from "@/lib/destino-do-link";
import { ensureColorContrast, getReadableTextColor, normalizeHexColor, withAlpha } from "@/lib/color-contrast";
import { useCatalogTheme } from "@/themes/provider";
import { useVisaoDaLoja } from "@/components/VisaoDaLojaContext";
import { estaEsgotado } from "@/lib/loja/regras-da-loja";
import StoriesCarousel from "./stories/StoriesCarousel";
import { SecaoNovaDaHome, ehSecaoNovaDaHome } from "@/components/home/SecoesNovasDaHome";
import { CaixaDaSecao, semFundoDeSempre } from "@/components/home/CaixaDaSecao";
import { marcaDeRegiao, useNavegacaoDaLoja } from "@/components/navegacao/ContextoDaNavegacao";
import { ItensDoMenuNaFaixa, ItensDoMenuNoCelular } from "@/components/navegacao/MenuDaLoja";
import { RodapeProprioPadrao, RodapeProprioVitrine, type PropsDoRodape } from "@/components/navegacao/RodapeDaLoja";
import { itensProntos } from "@/lib/navegacao-da-loja";

import ClientPortalFavoriteButton from "./ClientPortalFavoriteButton";
import ProductPurchaseCard from "./ProductPurchaseCard";

/* Quantos cards "todos os produtos" mostra por vez: 216 de uma vez travavam
   o celular. "Ver mais" solta o próximo lote, sem nova ida ao servidor. */
const LOTE_DA_GRADE = 40;

interface Product {
  /* A regra da loja escondeu o preco deste visitante (lib/loja/regras-da-loja.ts). */
  preco_oculto?: boolean | null;
  id: string;
  name: string;
  description?: string | null;
  price: number;
  image_url?: string;
  stock: number;
  track_inventory?: boolean | null;
  user_id: string;
  category_id?: string;
  unit_type?: string | null;
  price_on_request?: boolean | null;
  use_variation_price_only?: boolean | null;
  min_sale_qty_enabled?: boolean | null;
  min_sale_qty?: number | null;
  max_sale_qty_enabled?: boolean | null;
  max_sale_qty?: number | null;
  allowed_sale_qty_enabled?: boolean | null;
  allowed_sale_quantities?: number[] | null;
  product_price_tiers?: Array<{
    min_qty: number;
    max_qty: number | null;
    unit_price: number;
    sort_order?: number | null;
    active?: boolean | null;
  }>;
  product_attributes?: Array<{
    name?: string | null;
    is_required?: boolean | null;
    options?: Array<string | { label?: string | null; price?: number | null }> | null;
  }> | null;
  product_images?: Array<{
    id: string;
    image_url: string;
    sort_order?: number | null;
    is_primary?: boolean | null;
  }> | null;
  has_variations?: boolean;
  /* "digital": selo no card e compra rápida na página do produto. */
  product_kind?: string | null;
  /* O tipo do digital ("curso" leva o selo "Curso" no card). */
  digital_tipo?: string | null;
  custom_fields_config?: Array<{
    id?: string | null;
    title?: string | null;
    active?: boolean | null;
  }> | null;
}

interface Category {
  id: string;
  name: string;
  slug?: string;
  parent_id?: string | null;
}

interface Banner {
  id: string;
  image_url: string;
  link_type?: "none" | "product" | "url" | null;
  product_id?: string | null;
  link_url?: string | null;
  open_in_new_tab?: boolean | null;
  position?: number | null;
  created_at?: string;
}

interface InfoStripItem {
  icon: string;
  title: string;
  subtitle: string;
}

type AnnouncementCoupon = {
  id: string;
  code: string;
  type: "percent" | "value" | "free_shipping";
  value: number;
  active: boolean;
  starts_at?: string | null;
  ends_at?: string | null;
};

/* Glifo oficial do WhatsApp. Fica aqui, num lugar so, porque o botao
   flutuante e o rodape do menu mobile usam o mesmo desenho — duplicar o path
   e o caminho curto para os dois sairem do lugar quando um for mexido. */
function WhatsAppGlyph({ size = 24 }: { size?: number }) {
  return (
    <svg viewBox="0 0 24 24" width={size} height={size} fill="currentColor" aria-hidden="true">
      <path d="M17.472 14.382c-.297-.149-1.758-.867-2.03-.967-.273-.099-.471-.148-.67.15-.197.297-.767.966-.94 1.164-.173.199-.347.223-.644.075-.297-.15-1.255-.463-2.39-1.475-.883-.788-1.48-1.761-1.653-2.059-.173-.297-.018-.458.13-.606.134-.133.298-.347.446-.52.149-.174.198-.298.298-.497.099-.198.05-.371-.025-.52-.075-.149-.669-1.612-.916-2.207-.242-.579-.487-.5-.669-.51-.173-.008-.371-.01-.57-.01-.198 0-.52.074-.792.372-.272.297-1.04 1.016-1.04 2.479 0 1.462 1.065 2.875 1.213 3.074.149.198 2.096 3.2 5.077 4.487.709.306 1.262.489 1.694.625.712.227 1.36.195 1.871.118.571-.085 1.758-.719 2.006-1.413.248-.694.248-1.289.173-1.413-.074-.124-.272-.198-.57-.347m-5.421 7.403h-.004a9.87 9.87 0 01-5.031-1.378l-.361-.214-3.741.982.998-3.648-.235-.374a9.86 9.86 0 01-1.51-5.26c.001-5.45 4.436-9.884 9.888-9.884 2.64 0 5.122 1.03 6.988 2.898a9.825 9.825 0 012.893 6.994c-.003 5.45-4.437 9.884-9.885 9.884m8.413-18.297A11.815 11.815 0 0012.05 0C5.495 0 .16 5.335.157 11.892c0 2.096.547 4.142 1.588 5.945L.057 24l6.305-1.654a11.882 11.882 0 005.683 1.448h.005c6.554 0 11.89-5.335 11.893-11.893a11.821 11.821 0 00-3.48-8.413Z" />
    </svg>
  );
}

function getProductDescriptionPreview(value: unknown, maxLength = 180) {
  const text = String(value || "")
    .replace(/<[^>]*>/g, " ")
    .replace(/\s+/g, " ")
    .trim();
  if (!text) return "";
  if (text.length <= maxLength) return text;
  return `${text.slice(0, maxLength).trimEnd()}...`;
}

function getProductImageGalleryUrls(product: Pick<Product, "image_url" | "product_images">) {
  const sortedImages = product.product_images
    ? [...product.product_images].sort((a, b) => (a.sort_order || 0) - (b.sort_order || 0))
    : [];
  return Array.from(
    new Set(
      [product.image_url, ...sortedImages.map((img) => img.image_url)]
        .map((value) => String(value || "").trim())
        .filter(Boolean)
    )
  );
}

function filterProductsBySearchTerm(products: Product[], term: string) {
  const normalizedTerm = term.trim().toLocaleLowerCase("pt-BR");
  if (!normalizedTerm) return products;
  return products.filter((product) => {
    const name = String(product.name || "").toLocaleLowerCase("pt-BR");
    const description = String(product.description || "")
      .replace(/<[^>]*>/g, " ")
      .toLocaleLowerCase("pt-BR");
    return name.includes(normalizedTerm) || description.includes(normalizedTerm);
  });
}

const VITRINE_GRID_AUTO_ROW = 8;
const VITRINE_FEATURED_EDITORIAL_SLOTS = new Set([0, 6]);
const VITRINE_FEATURED_COMPACT_SLOTS = new Set([3, 8]);

type VitrineProductLayout = "mosaic" | "standard";
type VitrineCardVariant = "standard" | "featuredCompact" | "featuredEditorial";

function getVitrineProductContentProfile(product: Pick<Product, "name" | "description" | "image_url" | "product_images" | "price_on_request" | "use_variation_price_only">) {
  const imageGallery = getProductImageGalleryUrls(product);
  const descriptionPreview = getProductDescriptionPreview(product.description, 185);
  const descriptionLength = descriptionPreview.length;
  const extraImageCount = Math.max(0, imageGallery.length - 1);
  const hasExtraGalleryImages = extraImageCount > 0;
  const hasDescriptionPreview = descriptionLength > 0;
  const nameLength = String(product.name || "").trim().length;

  let richnessScore = 0;
  if (extraImageCount >= 3) richnessScore += 4;
  else if (extraImageCount >= 2) richnessScore += 3;
  else if (extraImageCount === 1) richnessScore += 2;
  if (descriptionLength >= 140) richnessScore += 3;
  else if (descriptionLength >= 80) richnessScore += 2;
  else if (descriptionLength > 0) richnessScore += 1;
  if (nameLength >= 42) richnessScore += 1;
  if (product.price_on_request || product.use_variation_price_only) richnessScore += 1;

  return {
    imageGallery,
    descriptionPreview,
    extraImageCount,
    hasExtraGalleryImages,
    hasDescriptionPreview,
    nameLength,
    richnessScore,
  };
}

function resolveVitrineCardVariant(
  product: Pick<Product, "name" | "description" | "image_url" | "product_images" | "price_on_request" | "use_variation_price_only">,
  index: number
): VitrineCardVariant {
  const slot = index % 10;
  const profile = getVitrineProductContentProfile(product);

  if (
    VITRINE_FEATURED_EDITORIAL_SLOTS.has(slot) &&
    (profile.extraImageCount >= 2 || (profile.hasExtraGalleryImages && profile.hasDescriptionPreview) || profile.richnessScore >= 5)
  ) {
    return "featuredEditorial";
  }

  if (
    (VITRINE_FEATURED_EDITORIAL_SLOTS.has(slot) || VITRINE_FEATURED_COMPACT_SLOTS.has(slot)) &&
    (profile.hasDescriptionPreview || profile.hasExtraGalleryImages || profile.nameLength >= 38 || profile.richnessScore >= 3)
  ) {
    return "featuredCompact";
  }

  return "standard";
}

function buildVitrineCardVariants(
  products: Array<Pick<Product, "name" | "description" | "image_url" | "product_images" | "price_on_request" | "use_variation_price_only">>
) {
  const variants: VitrineCardVariant[] = [];
  let lastFeaturedIndex = -10;
  let lastEditorialIndex = -10;

  products.forEach((product, index) => {
    const desiredVariant = resolveVitrineCardVariant(product, index);
    let finalVariant: VitrineCardVariant = desiredVariant;
    const profile = getVitrineProductContentProfile(product);

    if (desiredVariant === "featuredEditorial" && lastEditorialIndex >= 0 && index - lastEditorialIndex < 5) {
      finalVariant = profile.richnessScore >= 4 ? "featuredCompact" : "standard";
    }

    if (finalVariant !== "standard" && lastFeaturedIndex >= 0 && index - lastFeaturedIndex < 2) {
      finalVariant = profile.richnessScore >= 5 ? "featuredCompact" : "standard";
    }

    if (finalVariant === "featuredCompact" && !profile.hasDescriptionPreview && !profile.hasExtraGalleryImages && profile.nameLength < 42) {
      finalVariant = "standard";
    }

    if (finalVariant !== "standard") {
      lastFeaturedIndex = index;
    }

    if (finalVariant === "featuredEditorial") {
      lastEditorialIndex = index;
    }

    variants.push(finalVariant);
  });

  return variants;
}

type StoryGroup = {
  id: string;
  title: string;
  thumbnail_url: string | null;
  items: Array<{
    id: string;
    image_url: string;
    product_id?: string | null;
    product?: {
      id: string;
      name: string;
      price: number;
      price_on_request: boolean;
      image_url?: string;
    };
  }>;
};

const BRAZILIAN_NAMES = [
  "Ana Paula",
  "Carlos Eduardo",
  "Fernanda",
  "João Vitor",
  "Mariana",
  "Rafael",
  "Juliana",
  "Guilherme",
  "Larissa",
  "Bruno",
  "Camila",
  "Felipe",
  "Patrícia",
  "Diego",
  "Aline",
  "Mateus",
  "Vanessa",
  "Thiago",
  "Renata",
  "Leandro",
  "Priscila",
  "Eduardo",
  "Tatiane",
  "Lucas",
  "Natália",
  "Vinícius",
  "Beatriz",
  "Rodrigo",
  "Gabriela",
  "André",
];

export interface CatalogSection {
  id: string;
  title: string;
  background_color: string;
  text_color: string;
  type?: "manual" | "manual_products" | "all_products" | "category_products" | "subcategory_products" | "image_banner" | "category_navigator" | "image_grid" | "banner_carousel";
  section_type?: "manual_products" | "all_products" | "category_products" | "subcategory_products" | "image_banner" | "category_navigator" | "image_grid" | "banner_carousel";
  config?: Record<string, unknown>;
  placement?: "above" | "below";
  layout_width?: "full" | "contained";
  title_align?: "left" | "center" | "right";
  title_size?: "sm" | "md" | "lg" | "xl";
  products: Product[];
  position?: number | null;
}

function normalizeSectionConfig(config: unknown): Record<string, unknown> | null {
  if (config && typeof config === "object") return config as Record<string, unknown>;
  if (typeof config === "string") {
    try {
      const parsed = JSON.parse(config);
      return parsed && typeof parsed === "object" ? (parsed as Record<string, unknown>) : null;
    } catch {
      return null;
    }
  }
  return null;
}

interface StoreContentProps {
  products: Product[];
  categories: Category[];
  banners: Banner[];
  sections?: CatalogSection[];
  slideEnabled: boolean;
  infoStripEnabled: boolean;
  infoStripItems: InfoStripItem[];
  slug: string;
  primaryColor: string;
  storeName: string;
  storeSlogan?: string | null;
  logoUrl?: string | null;
  showStoreNameInHeader?: boolean | null;
  showStoreSloganInHeader?: boolean | null;
  storeNameColor?: string | null;
  storeSloganColor?: string | null;
  catalogHeaderIconColor?: string | null;
  logoEffectEnabled?: boolean | null;
  logoEffectType?: "none" | "rotate_3d" | "blink" | "pulse_glow" | null;
  logoEffectSpeed?: number | null;
  logoEffectIntensity?: number | null;
  whatsapp?: string | null;
  /* O botao verde flutuante no canto: escolha da loja, e nao consequencia de
     ter um numero cadastrado. */
  whatsappFloat?: boolean | null;
  phone?: string | null;
  companyPhone?: string | null;
  companyWhatsapp?: string | null;
  address?: string | null;
  cnpj?: string | null;
  catalogShowDocument?: boolean | null;
  footerColor?: string | null;
  footerTextColor?: string | null;
  headerColor?: string | null;
  pageBgColor?: string | null;
  cardButtonColor?: string | null;
  fontHeadingFamily?: string | null;
  fontBodyFamily?: string | null;
  headerTextColor?: string | null;
  menuColor?: string | null;
  menuTextColor?: string | null;
  buttonColor?: string | null;
  buttonTextColor?: string | null;
  socialFacebook?: string | null;
  socialInstagram?: string | null;
  socialTwitter?: string | null;
  socialLinkedin?: string | null;
  socialYoutube?: string | null;
  companySocialFacebook?: string | null;
  companySocialInstagram?: string | null;
  companySocialTwitter?: string | null;
  companySocialLinkedin?: string | null;
  companySocialYoutube?: string | null;
  initialSelectedCategoryId?: string | null;
  hideSections?: boolean;
  productsHeading?: string;
  /* Página extra da loja (/<slug>/pagina/<pagina>, migration 197): sem a
     grade de produtos inventada no fim, com o título da página no topo. */
  paginaExtra?: { titulo: string; mostrarTitulo: boolean; vazio?: React.ReactNode } | null;
  announcementEnabled?: boolean | null;
  announcementText?: string | null;
  announcementCountdownEnabled?: boolean | null;
  announcementCountdownEndAt?: string | null;
  announcementShowCouponBadge?: boolean | null;
  announcementCouponBadgeColor?: string | null;
  announcementBackgroundColor?: string | null;
  announcementTextColor?: string | null;
  announcementButtonLabel?: string | null;
  announcementButtonUrl?: string | null;
  announcementSticky?: boolean | null;
  announcementCoupon?: AnnouncementCoupon | null;
  announcementCouponId?: string | null;
  socialProofEnabled?: boolean | null;
  socialProofIntervalSeconds?: number | null;
  socialProofPosition?: string | null;
  socialProofDurationSeconds?: number | null;
  socialProofMaxVisible?: number | null;
  vitrineProductLayout?: VitrineProductLayout | null;
  loggedClient?: { id: string; name: string; avatar_url: string | null; favorites?: string[] | null } | null;
}

/* `textoSemPreco` e o que a loja escolheu mostrar no lugar do preco: vale para
   o "sob consulta" do cadastro e para o preco escondido pela regra da loja. */
function resolveProductPriceDisplay(product: Product, textoSemPreco = "Sob consulta") {
  const formatMoney = (value: number) =>
    new Intl.NumberFormat("pt-BR", { style: "currency", currency: "BRL" }).format(value);
  const splitMoney = (value: number) => {
    const formatted = formatMoney(value).replace(/\u00a0/g, " ").trim();
    const match = formatted.match(/^([^\d]+)\s*([\d.]+),(\d{2})$/);
    if (!match) {
      return { currency: "R$", integer: String(Math.round(value) || 0), decimal: "00" };
    }
    return {
      currency: match[1].trim() || "R$",
      integer: match[2] || "0",
      decimal: match[3] || "00",
    };
  };
  if (product.price_on_request || product.preco_oculto) {
    return {
      text: textoSemPreco,
      prefix: "",
      suffix: "",
      parts: null,
      hasWholesalePricing: false,
      hasWholesaleBadge: false,
      isPremiumMeasuredPricing: false,
      helperText: "",
    };
  }
  /* Produto digital grátis: "Grátis", não "R$ 0,00". */
  if (product.product_kind === "digital" && !(Number(product.price) > 0)) {
    return {
      text: "Grátis",
      prefix: "",
      suffix: "",
      parts: null,
      hasWholesalePricing: false,
      hasWholesaleBadge: false,
      isPremiumMeasuredPricing: false,
      helperText: "",
    };
  }
  if (product.unit_type === "square_meter") {
    return {
      text: "Preço sob medida",
      prefix: "",
      suffix: "",
      parts: null,
      hasWholesalePricing: false,
      hasWholesaleBadge: false,
      isPremiumMeasuredPricing: true,
      helperText: "Informe as medidas para calcular",
    };
  }
  const suffix = product.unit_type === "square_meter" ? " / m²" : "";
  const minimumVariationPrice = (() => {
    const attributes = Array.isArray(product.product_attributes) ? product.product_attributes : [];
    if (!attributes.length) return 0;
    const hasRequired = attributes.some((attribute) => Boolean(attribute?.is_required));
    const relevantAttributes = hasRequired
      ? attributes.filter((attribute) => Boolean(attribute?.is_required))
      : attributes;
    let total = 0;
    for (const attribute of relevantAttributes) {
      const options = Array.isArray(attribute?.options) ? attribute.options : [];
      const optionPrices = options
        .map((option) => (typeof option === "string" ? 0 : Number(option?.price) || 0))
        .filter((value) => Number.isFinite(value) && value >= 0);
      if (!optionPrices.length) continue;
      total += Math.min(...optionPrices);
    }
    return Math.max(0, total);
  })();
  if (product.use_variation_price_only) {
    return {
      text: `A partir de ${formatMoney(minimumVariationPrice)}${suffix}`,
      prefix: "A partir de",
      suffix,
      parts: splitMoney(minimumVariationPrice),
      hasWholesalePricing: true,
      hasWholesaleBadge: false,
      isPremiumMeasuredPricing: false,
      helperText: "",
    };
  }
  const basePrice = Number(product.price) || 0;
  const allowedQuantities =
    product.allowed_sale_qty_enabled && Array.isArray(product.allowed_sale_quantities)
      ? Array.from(
          new Set(
            product.allowed_sale_quantities
              .map((value) => Number(value))
              .filter((value) => Number.isFinite(value) && value > 0)
              .map((value) => Number(value.toFixed(3)))
          )
        ).sort((a, b) => a - b)
      : [];

  if (allowedQuantities.length > 0) {
    const exactTierUnitPrices = (product.product_price_tiers || [])
      .filter((tier) => tier.active !== false)
      .map((tier) => {
        const minQty = Number(tier.min_qty);
        const maxQty = tier.max_qty === null || tier.max_qty === undefined ? null : Number(tier.max_qty);
        const unitPrice = Number(tier.unit_price);
        if (!Number.isFinite(minQty) || !Number.isFinite(unitPrice) || unitPrice <= 0) return null;
        if (maxQty === null || !Number.isFinite(maxQty)) return null;
        if (Math.abs(maxQty - minQty) > 0.000001) return null;
        const isAllowed = allowedQuantities.some((value) => Math.abs(value - minQty) <= 0.000001);
        if (!isAllowed) return null;
        return unitPrice;
      })
      .filter((value): value is number => value !== null && Number.isFinite(value) && value > 0);

    if (exactTierUnitPrices.length > 0) {
      const priceValue = Math.min(...exactTierUnitPrices);
      return {
        text: `A partir de ${formatMoney(priceValue)}${suffix}`,
        prefix: "A partir de",
        suffix,
        parts: splitMoney(priceValue),
        hasWholesalePricing: true,
        hasWholesaleBadge: true,
        isPremiumMeasuredPricing: false,
        helperText: "",
      };
    }
  }

  const tierPrices = (product.product_price_tiers || [])
    .filter((tier) => tier.active !== false)
    .map((tier) => Number(tier.unit_price))
    .filter((price) => Number.isFinite(price) && price > 0);
  const lowestTier = tierPrices.length > 0 ? Math.min(...tierPrices) : null;
  const showcasePrice = lowestTier !== null ? Math.min(basePrice, lowestTier) : basePrice;
  if (lowestTier !== null && lowestTier < basePrice) {
    return {
      text: `A partir de ${formatMoney(showcasePrice)}${suffix}`,
      prefix: "A partir de",
      suffix,
      parts: splitMoney(showcasePrice),
      hasWholesalePricing: true,
      hasWholesaleBadge: true,
      isPremiumMeasuredPricing: false,
      helperText: "",
    };
  }
  const hasWholesalePricing = tierPrices.length > 0;
  return {
    text: `${formatMoney(showcasePrice)}${suffix}`,
    prefix: "",
    suffix,
    parts: splitMoney(showcasePrice),
    hasWholesalePricing,
    hasWholesaleBadge: hasWholesalePricing,
    isPremiumMeasuredPricing: false,
    helperText: "",
  };
}

function formatProductPrice(product: Product, textoSemPreco?: string) {
  return resolveProductPriceDisplay(product, textoSemPreco).text;
}

function resolveProductFilterPrice(product: Product) {
  if (product.price_on_request || product.unit_type === "square_meter") {
    return null;
  }

  const minimumVariationPrice = (() => {
    const attributes = Array.isArray(product.product_attributes) ? product.product_attributes : [];
    if (!attributes.length) return 0;
    const hasRequired = attributes.some((attribute) => Boolean(attribute?.is_required));
    const relevantAttributes = hasRequired
      ? attributes.filter((attribute) => Boolean(attribute?.is_required))
      : attributes;
    let total = 0;
    for (const attribute of relevantAttributes) {
      const options = Array.isArray(attribute?.options) ? attribute.options : [];
      const optionPrices = options
        .map((option) => (typeof option === "string" ? 0 : Number(option?.price) || 0))
        .filter((value) => Number.isFinite(value) && value >= 0);
      if (!optionPrices.length) continue;
      total += Math.min(...optionPrices);
    }
    return Math.max(0, total);
  })();

  if (product.use_variation_price_only) {
    return minimumVariationPrice;
  }

  const basePrice = Number(product.price) || 0;
  const allowedQuantities =
    product.allowed_sale_qty_enabled && Array.isArray(product.allowed_sale_quantities)
      ? Array.from(
          new Set(
            product.allowed_sale_quantities
              .map((value) => Number(value))
              .filter((value) => Number.isFinite(value) && value > 0)
              .map((value) => Number(value.toFixed(3)))
          )
        ).sort((a, b) => a - b)
      : [];

  if (allowedQuantities.length > 0) {
    const exactTierUnitPrices = (product.product_price_tiers || [])
      .filter((tier) => tier.active !== false)
      .map((tier) => {
        const minQty = Number(tier.min_qty);
        const maxQty = tier.max_qty === null || tier.max_qty === undefined ? null : Number(tier.max_qty);
        const unitPrice = Number(tier.unit_price);
        if (!Number.isFinite(minQty) || !Number.isFinite(unitPrice) || unitPrice <= 0) return null;
        if (maxQty === null || !Number.isFinite(maxQty)) return null;
        if (Math.abs(maxQty - minQty) > 0.000001) return null;
        const isAllowed = allowedQuantities.some((value) => Math.abs(value - minQty) <= 0.000001);
        if (!isAllowed) return null;
        return unitPrice;
      })
      .filter((value): value is number => value !== null && Number.isFinite(value) && value > 0);

    if (exactTierUnitPrices.length > 0) {
      return Math.min(...exactTierUnitPrices);
    }
  }

  const tierPrices = (product.product_price_tiers || [])
    .filter((tier) => tier.active !== false)
    .map((tier) => Number(tier.unit_price))
    .filter((price) => Number.isFinite(price) && price > 0);
  const lowestTier = tierPrices.length > 0 ? Math.min(...tierPrices) : null;
  const showcasePrice = lowestTier !== null ? Math.min(basePrice, lowestTier) : basePrice;

  return Number.isFinite(showcasePrice) && showcasePrice >= 0 ? showcasePrice : null;
}

function getCountdownParts(endAt: string, baseTimestamp: number) {
  const target = new Date(endAt).getTime();
  if (!Number.isFinite(target) || baseTimestamp <= 0) {
    return [
      { label: "D", value: "00" },
      { label: "H", value: "00" },
      { label: "M", value: "00" },
      { label: "S", value: "00" },
    ];
  }
  const diffMs = Math.max(0, target - baseTimestamp);
  const totalSeconds = Math.floor(diffMs / 1000);
  const days = Math.floor(totalSeconds / 86400);
  const hours = Math.floor((totalSeconds % 86400) / 3600);
  const minutes = Math.floor((totalSeconds % 3600) / 60);
  const seconds = totalSeconds % 60;
  return [
    { label: "D", value: String(days).padStart(2, "0") },
    { label: "H", value: String(hours).padStart(2, "0") },
    { label: "M", value: String(minutes).padStart(2, "0") },
    { label: "S", value: String(seconds).padStart(2, "0") },
  ];
}

function resolveAnnouncementButtonHref(rawUrl: string | null | undefined, slug: string) {
  const url = String(rawUrl || "").trim();
  if (!url) return "";
  const productMatch = url.match(/^catalog:\/\/product\/([^/?#]+)/i);
  if (productMatch?.[1]) {
    return `/${slug}/p/${decodeURIComponent(productMatch[1])}`;
  }
  const categoryMatch = url.match(/^catalog:\/\/(?:category|subcategory)\/([^/?#]+)/i);
  if (categoryMatch?.[1]) {
    return `/${slug}/c/${decodeURIComponent(categoryMatch[1])}`;
  }
  return url;
}

function formatCouponPromoText(coupon: AnnouncementCoupon | null | undefined) {
  if (!coupon) return "";
  if (coupon.type === "free_shipping") return `Use o cupom ${coupon.code} e ganhe frete grátis`;
  if (coupon.type === "percent") {
    return `Use o cupom ${coupon.code} e ganhe ${Number(coupon.value || 0)}% OFF`;
  }
  const amount = Number(coupon.value || 0);
  return `Use o cupom ${coupon.code} e ganhe R$ ${amount.toFixed(2)} OFF`;
}

function renderHighlightedText(text: string) {
  const tokens = text.split(/(\*\*[^*]+\*\*)/g).filter(Boolean);
  return tokens.map((token, index) => {
    if (token.startsWith("**") && token.endsWith("**")) {
      return (
        <strong key={`highlight-${index}`} className="font-extrabold">
          {token.slice(2, -2)}
        </strong>
      );
    }
    return <span key={`plain-${index}`}>{token}</span>;
  });
}

export default function StoreContent({
  products, 
  categories, 
  banners,
  sections,
  slideEnabled,
  infoStripEnabled,
  infoStripItems,
  slug, 
  primaryColor,
  storeName,
  storeSlogan,
  logoUrl,
  showStoreNameInHeader = true,
  showStoreSloganInHeader = true,
  storeNameColor,
  storeSloganColor,
  catalogHeaderIconColor,
  logoEffectEnabled,
  logoEffectType,
  logoEffectSpeed,
  logoEffectIntensity,
  whatsapp,
  whatsappFloat,
  phone,
  companyPhone,
  companyWhatsapp,
  address,
  cnpj,
  catalogShowDocument = true,
  footerColor,
  footerTextColor,
  headerColor,
  pageBgColor = null,
  cardButtonColor = null,
  fontHeadingFamily = null,
  fontBodyFamily = null,
  headerTextColor,
  menuColor,
  menuTextColor,
  buttonColor,
  buttonTextColor,
  socialFacebook,
  socialInstagram,
  socialTwitter,
  socialLinkedin,
  socialYoutube,
  companySocialFacebook,
  companySocialInstagram,
  companySocialTwitter,
  companySocialLinkedin,
  companySocialYoutube,
  initialSelectedCategoryId,
  hideSections = false,
  productsHeading = "Todos os Produtos",
  paginaExtra = null,
  announcementEnabled,
  announcementText,
  announcementCountdownEnabled,
  announcementCountdownEndAt,
  announcementShowCouponBadge,
  announcementCouponBadgeColor,
  announcementBackgroundColor,
  announcementTextColor,
  announcementButtonLabel,
  announcementButtonUrl,
  announcementSticky,
  announcementCoupon,
  announcementCouponId,
  socialProofEnabled,
  socialProofIntervalSeconds,
  socialProofPosition,
  socialProofDurationSeconds,
  socialProofMaxVisible,
  vitrineProductLayout = "mosaic",
  storiesGroups,
  catalogStoriesEnabled = true,
  loggedClient,
  isProductPage = false,
  children,
  envolverSecao,
  contarCliques = false,
}: StoreContentProps & { 
  storiesGroups?: StoryGroup[]; 
  catalogStoriesEnabled?: boolean;
  isProductPage?: boolean;
  children?: React.ReactNode;
  /* Só o editor da página inicial passa: põe a moldura (contorno, botões)
     em volta de cada seção. Sem ela, a seção sai como sempre saiu. */
  envolverSecao?: (secao: CatalogSection, indice: number, conteudo: React.ReactNode) => React.ReactNode;
  /* A loja montada pelo editor conta os cliques de cada seção (migration
     199). As outras não ganham caixa nenhuma em volta das seções. */
  contarCliques?: boolean;
}) {
  const { id: catalogThemeId } = useCatalogTheme();
  /* O cabeçalho, o menu e o rodapé publicados no editor (migration 197).
     Sem nada publicado, tudo abaixo segue o desenho de sempre. */
  const { navegacao, noEditor: noEditorDaNavegacao } = useNavegacaoDaLoja();
  const cabecalhoProprio = navegacao?.cabecalho ?? null;
  const menuProprio = navegacao?.menu ?? null;
  const rodapeProprio = navegacao?.rodape ?? null;
  const cabecalhoFixo = cabecalhoProprio?.fixo !== false;
  const mostrarBusca = cabecalhoProprio?.mostrar_busca !== false;
  const mostrarTodasAsCategorias = menuProprio?.mostrar_categorias !== false;
  const tamanhoDaLogo = cabecalhoProprio?.tamanho_da_logo ?? "normal";
  /* O que este visitante pode ver e fazer (regras da loja). */
  const visao = useVisaoDaLoja();
  const textoSemPreco = visao.textoNoLugarDoPreco;
  const useVitrineMosaicLayout = catalogThemeId === "vitrine" && vitrineProductLayout !== "standard";
  const [localSelectedCategory, setLocalSelectedCategory] = useState<string>("all");
  const selectedCategory = initialSelectedCategoryId || localSelectedCategory;
  const [searchTerm, setSearchTerm] = useState("");
  const [isSearchSuggestionsOpen, setIsSearchSuggestionsOpen] = useState(false);
  const [sortOrder, setSortOrder] = useState<string>("relevance");
  const [priceFilter, setPriceFilter] = useState<{min: string, max: string}>({min: "", max: ""});
  const [priceFilterDraft, setPriceFilterDraft] = useState<{min: string, max: string}>({min: "", max: ""});
  const [currentBanner, setCurrentBanner] = useState(0);
  const [quickViewProduct, setQuickViewProduct] = useState<Product | null>(null);
  const [quickViewActiveImageIndex, setQuickViewActiveImageIndex] = useState(0);
  const [cardActiveImageIndexByProduct, setCardActiveImageIndexByProduct] = useState<Record<string, number>>({});
  const [vitrineCardRowSpans, setVitrineCardRowSpans] = useState<Record<string, number>>({});
  const vitrineCardObserversRef = useRef<Map<string, ResizeObserver>>(new Map());
  const productsSectionRef = useRef<HTMLDivElement | null>(null);
  const desktopCategoriesRef = useRef<HTMLDivElement | null>(null);
  const desktopMenuNavRef = useRef<HTMLElement | null>(null);
  const desktopCategoryMeasureRefs = useRef<Map<string, HTMLSpanElement>>(new Map());
  const announcementRef = useRef<HTMLDivElement | null>(null);
  const headerRef = useRef<HTMLElement | null>(null);
  
  // Mobile UI States
  const [isDesktopSearchOpen, setIsDesktopSearchOpen] = useState(false);
  const [isMobileSearchOpen, setIsMobileSearchOpen] = useState(false);
  const [isMobileCategoriesOpen, setIsMobileCategoriesOpen] = useState(false);
  const [isVitrineMobileFiltersOpen, setIsVitrineMobileFiltersOpen] = useState(false);
  const [isVitrineMobileCategoriesMenuOpen, setIsVitrineMobileCategoriesMenuOpen] = useState(false);
  const [expandedMobileParentIds, setExpandedMobileParentIds] = useState<Set<string>>(new Set());
  const [isDesktopCategoriesOpen, setIsDesktopCategoriesOpen] = useState(false);
  const [openDesktopSubmenuId, setOpenDesktopSubmenuId] = useState<string | null>(null);
  const [announcementCouponCopied, setAnnouncementCouponCopied] = useState(false);
  const [announcementMarqueePaused, setAnnouncementMarqueePaused] = useState(false);
  const [resolvedAnnouncementCoupon, setResolvedAnnouncementCoupon] = useState<AnnouncementCoupon | null>(announcementCoupon || null);
  const [currentTimestamp, setCurrentTimestamp] = useState(0);
  const [socialProofToasts, setSocialProofToasts] = useState<Array<{ id: string; productId: string; name: string; productName: string; imageUrl?: string | null; minutesAgo: number }>>([]);
  const [announcementStickyOffset, setAnnouncementStickyOffset] = useState(0);
  
  const [activeMegaMenuCategory, setActiveMegaMenuCategory] = useState<string | null>(null);
  const [desktopVisibleCount, setDesktopVisibleCount] = useState(1);
  const normalizedSearchTerm = searchTerm.trim();

  // Mobile Section Expansion State (for Carousel/Grid toggle)
  const [expandedSectionIds, setExpandedSectionIds] = useState<Set<string>>(new Set());
  const [lotesPorSecao, setLotesPorSecao] = useState<Record<string, number>>({});
  const quantosVisiveis = (sectionId: string) => lotesPorSecao[sectionId] ?? LOTE_DA_GRADE;
  const mostrarMaisDaSecao = (sectionId: string) =>
    setLotesPorSecao((antes) => ({ ...antes, [sectionId]: (antes[sectionId] ?? LOTE_DA_GRADE) + LOTE_DA_GRADE }));

  const updateVitrineCardRowSpan = useCallback((key: string, node: HTMLDivElement) => {
    if (typeof window === "undefined") return;
    const parent = node.parentElement;
    if (!parent) return;
    const parentStyles = window.getComputedStyle(parent);
    const rowGap = Number.parseFloat(parentStyles.rowGap || parentStyles.gap || "0") || 0;
    const autoRows = Number.parseFloat(parentStyles.gridAutoRows || String(VITRINE_GRID_AUTO_ROW)) || VITRINE_GRID_AUTO_ROW;
    const height = node.getBoundingClientRect().height;
    const span = Math.max(1, Math.ceil((height + rowGap) / (autoRows + rowGap)));
    setVitrineCardRowSpans((current) => (current[key] === span ? current : { ...current, [key]: span }));
  }, []);

  const bindVitrineCardRef = useCallback(
    (key: string) => (node: HTMLDivElement | null) => {
      const existingObserver = vitrineCardObserversRef.current.get(key);
      if (existingObserver) {
        existingObserver.disconnect();
        vitrineCardObserversRef.current.delete(key);
      }

      if (!node) return;

      if (typeof ResizeObserver !== "undefined") {
        const observer = new ResizeObserver(() => updateVitrineCardRowSpan(key, node));
        observer.observe(node);
        vitrineCardObserversRef.current.set(key, observer);
      }

      requestAnimationFrame(() => updateVitrineCardRowSpan(key, node));
    },
    [updateVitrineCardRowSpan]
  );

  useEffect(() => {
    return () => {
      vitrineCardObserversRef.current.forEach((observer) => observer.disconnect());
      vitrineCardObserversRef.current.clear();
    };
  }, []);

  const toggleSectionExpansion = (sectionId: string) => {
    setExpandedSectionIds(prev => {
      const next = new Set(prev);
      if (next.has(sectionId)) {
        next.delete(sectionId);
      } else {
        next.add(sectionId);
      }
      return next;
    });
  };

  const router = useRouter();
  const pathname = usePathname();
  const searchParams = useSearchParams();
  const isDedicatedSearchRoute = pathname.endsWith("/buscar");
  const appliedSearchTerm = isDedicatedSearchRoute ? String(searchParams.get("search") || "").trim() : "";
  const isSearchResultsPage = Boolean(appliedSearchTerm);
  const [isAuthModalOpen, setIsAuthModalOpen] = useState(false);
  const [authMode, setAuthMode] = useState<"login" | "register">("login");
  const [authIdentifier, setAuthIdentifier] = useState("");
  const [authPassword, setAuthPassword] = useState("");
  const [authName, setAuthName] = useState("");
  const [authDocument, setAuthDocument] = useState("");
  const [authError, setAuthError] = useState("");
  const [authSuccess, setAuthSuccess] = useState("");
  const [authLoading, setAuthLoading] = useState(false);
  const [authIntent, setAuthIntent] = useState<
    | { type: "favorite_product"; productId: string }
    | { type: "favorites_header" }
    | { type: "see_prices" }
    | null
  >(null);

  const digitsOnly = (value: string) => value.replace(/\D/g, "");

  const formatCpfCnpj = (value: string) => {
    const digits = digitsOnly(value).slice(0, 14);
    if (digits.length <= 11) {
      const p1 = digits.slice(0, 3);
      const p2 = digits.slice(3, 6);
      const p3 = digits.slice(6, 9);
      const p4 = digits.slice(9, 11);
      return [p1, p2, p3].filter(Boolean).join(".") + (p4 ? `-${p4}` : "");
    }
    const p1 = digits.slice(0, 2);
    const p2 = digits.slice(2, 5);
    const p3 = digits.slice(5, 8);
    const p4 = digits.slice(8, 12);
    const p5 = digits.slice(12, 14);
    const base = [p1, p2, p3].filter(Boolean).join(".");
    const mid = p4 ? `/${p4}` : "";
    const end = p5 ? `-${p5}` : "";
    return `${base}${mid}${end}`;
  };

  const normalizeBrazilianPhoneDigits = (value: string) => {
    const raw = digitsOnly(value);
    if (raw.startsWith("55") && raw.length > 11) return raw.slice(2);
    return raw;
  };

  const formatBrazilianPhone = (value: string) => {
    const digits = normalizeBrazilianPhoneDigits(value).slice(0, 11);
    const ddd = digits.slice(0, 2);
    const rest = digits.slice(2);
    if (!ddd) return "";
    if (!rest) return `(${ddd}`;
    if (rest.length <= 4) return `(${ddd}) ${rest}`;
    if (rest.length <= 8) return `(${ddd}) ${rest.slice(0, 4)}-${rest.slice(4)}`;
    return `(${ddd}) ${rest.slice(0, 5)}-${rest.slice(5, 9)}`;
  };

  const normalizeEmail = (value: string) => value.trim().toLowerCase();

  const looksLikeEmail = (value: string) => /@/.test(value) || /[a-zA-Z]/.test(value);

  const looksLikePhone = (digits: string) => {
    const cleaned = normalizeBrazilianPhoneDigits(digits);
    if (cleaned.length === 10) return true;
    if (cleaned.length !== 11) return false;
    return cleaned[2] === "9";
  };

  const normalizeIdentifierForSubmit = (value: string) => {
    const raw = value.trim();
    if (looksLikeEmail(raw)) return normalizeEmail(raw);
    return normalizeBrazilianPhoneDigits(raw);
  };

  const normalizeDocumentForSubmit = (value: string) => digitsOnly(value).slice(0, 14);

  const handleLogout = async () => {
    try {
      await fetch("/api/client-portal/logout", { method: "POST" });
    } catch {}
    window.location.reload();
  };

  const openAuthModal = (
    intent: { type: "favorite_product"; productId: string } | { type: "favorites_header" } | { type: "see_prices" }
  ) => {
    setAuthIntent(intent);
    setIsAuthModalOpen(true);
    setAuthMode("login");
    setAuthError("");
    setAuthSuccess("");
    setAuthLoading(false);
  };

  useEffect(() => {
    const handleRequireLogin = (e: CustomEvent<{ intent: any }>) => {
      openAuthModal(e.detail.intent);
    };
    window.addEventListener("ks_require_login", handleRequireLogin as EventListener);
    return () => window.removeEventListener("ks_require_login", handleRequireLogin as EventListener);
  }, []);

  const closeAuthModal = () => {
    setIsAuthModalOpen(false);
    setAuthLoading(false);
    setAuthError("");
    setAuthSuccess("");
  };

  const handleAuthSubmit = async (event: React.FormEvent) => {
    event.preventDefault();
    if (authLoading) return;
    const identifierNormalized = normalizeIdentifierForSubmit(authIdentifier);
    const documentNormalized = normalizeDocumentForSubmit(authDocument);
    const isIdentifierEmail = looksLikeEmail(authIdentifier);
    const identifierDigits = digitsOnly(identifierNormalized);
    const emailValid = (value: string) => /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(value);

    if (authMode === "register") {
      if (!authName.trim()) {
        setAuthError("Informe seu nome.");
        return;
      }
      if (documentNormalized.length !== 11 && documentNormalized.length !== 14) {
        setAuthError("Informe um CPF (11 dígitos) ou CNPJ (14 dígitos).");
        return;
      }
      if (!identifierNormalized) {
        setAuthError("Informe e-mail ou telefone.");
        return;
      }
      if (isIdentifierEmail) {
        if (!emailValid(identifierNormalized)) {
          setAuthError("Informe um e-mail válido.");
          return;
        }
      } else {
        const phoneDigits = normalizeBrazilianPhoneDigits(identifierDigits);
        if (phoneDigits.length !== 10 && phoneDigits.length !== 11) {
          setAuthError("Informe um telefone válido com DDD.");
          return;
        }
      }
    } else {
      if (!identifierNormalized) {
        setAuthError("Informe seu e-mail, telefone ou CPF/CNPJ.");
        return;
      }
    }

    setAuthLoading(true);
    setAuthError("");
    setAuthSuccess("");
    try {
      const endpoint = authMode === "login" ? "/api/client-portal/login" : "/api/client-portal/register";
      const payload: Record<string, unknown> = {
        slug,
        identifier: identifierNormalized,
        password: authPassword,
      };
      if (authMode === "register") {
        payload["name"] = authName.trim();
        payload["document"] = documentNormalized;
      }

      const response = await fetch(endpoint, {
        method: "POST",
        headers: { "content-type": "application/json" },
        body: JSON.stringify(payload),
      });
      const data = (await response.json().catch(() => ({}))) as {
        error?: string;
        message?: string;
        manual_login_required?: boolean;
        portal_status?: string | null;
        client?: { id?: string | null };
      };

      if (!response.ok || data.error) {
        setAuthError(data.error || "Não foi possível concluir o login.");
        return;
      }

      if (data.manual_login_required) {
        setAuthMode("login");
        setAuthSuccess(data.message || "Cadastro concluído. Agora entre com sua senha.");
        return;
      }

      const clientId = String(data.client?.id || "");
      if (!clientId) {
        setAuthError("Não foi possível validar sua sessão.");
        return;
      }

      /* Cadastro que espera a aprovacao da loja: entra, e a faixa no topo
         explica que os precos ficam liberados depois. */
      if (data.portal_status === "pending") {
        closeAuthModal();
        router.refresh();
        return;
      }

      if (authIntent?.type === "favorite_product") {
        await fetch("/api/client-portal/favorites", {
          method: "POST",
          headers: { "Content-Type": "application/json" },
          body: JSON.stringify({ productId: authIntent.productId, action: "add", slug }),
        });
        closeAuthModal();
        router.refresh();
        return;
      }

      if (authIntent?.type === "favorites_header") {
        window.location.assign(`/${slug}/cliente?section=favorites`);
        return;
      }

      closeAuthModal();
      router.refresh();
    } catch {
      setAuthError("Não foi possível concluir o login.");
    } finally {
      setAuthLoading(false);
    }
  };
  
  // Auto-scroll logic for carousels
  const carouselRefs = useRef<Map<string, HTMLDivElement>>(new Map());
  const activeCarouselsRef = useRef<Set<string>>(new Set());
  const submenuCloseTimeoutRef = useRef<ReturnType<typeof setTimeout> | null>(null);
  const megaMenuCloseTimeoutRef = useRef<ReturnType<typeof setTimeout> | null>(null);

  // Handle touch interactions to pause auto-scroll
  const handleTouchStart = (sectionId: string) => {
    activeCarouselsRef.current.add(sectionId);
  };

  const handleTouchEnd = (sectionId: string) => {
    // Resume auto-scroll after 5 seconds of inactivity
    setTimeout(() => {
      activeCarouselsRef.current.delete(sectionId);
    }, 5000);
  };

  useEffect(() => {
    const intervalIds = new Map<string, NodeJS.Timeout>();

    const startAutoScroll = (sectionId: string) => {
      if (intervalIds.has(sectionId)) return;

      const id = setInterval(() => {
        const container = carouselRefs.current.get(sectionId);
        if (!container) return;

        // If user is interacting or section is expanded, don't scroll
        // Use ref for activeCarousels to avoid dependency loop and stale closures
        if (expandedSectionIds.has(sectionId) || activeCarouselsRef.current.has(sectionId)) return;

        const scrollAmount = container.clientWidth * 0.8; // Scroll 80% of width
        const maxScroll = container.scrollWidth - container.clientWidth;
        
        if (container.scrollLeft >= maxScroll - 10) {
          // Reset to start smoothly
          container.scrollTo({ left: 0, behavior: 'smooth' });
        } else {
          container.scrollBy({ left: scrollAmount, behavior: 'smooth' });
        }
      }, 4000); // Scroll every 4 seconds

      intervalIds.set(sectionId, id);
    };

    // Initialize auto-scroll for all non-expanded sections
    if (sections) {
      sections.forEach(section => {
        const configObject = normalizeSectionConfig(section.config);
        const configMode =
          configObject &&
          "mode" in configObject
            ? configObject.mode
            : undefined;
        const hasImageUrl = Boolean(
          configObject &&
          (("image_url" in configObject && configObject.image_url) || ("imageUrl" in configObject && configObject.imageUrl))
        );
        const rawMode = hasImageUrl && !configMode ? "image_banner" : (configMode ?? section.section_type);
        const mode =
          rawMode === "all_products" || rawMode === "category_products" || rawMode === "subcategory_products" || rawMode === "image_banner" || rawMode === "category_navigator"
            ? rawMode
            : "manual_products";
        // Skip for "all_products" or if expanded
        if (mode !== "all_products" && !expandedSectionIds.has(section.id)) {
           startAutoScroll(section.id);
        }
      });
    }

    return () => {
      intervalIds.forEach(id => clearInterval(id));
    };
  }, [sections, expandedSectionIds]); // Removed activeCarousels from deps

  const closeCategoryMenus = useCallback(() => {
    setIsMobileCategoriesOpen(false);
    setExpandedMobileParentIds(new Set());
    setIsDesktopCategoriesOpen(false);
    setOpenDesktopSubmenuId(null);
  }, []);

  useEffect(() => {
    if (!isDesktopCategoriesOpen) return;
    const handleKeyDown = (event: KeyboardEvent) => {
      if (event.key === "Escape") {
        closeCategoryMenus();
      }
    };
    window.addEventListener("keydown", handleKeyDown);
    return () => {
      window.removeEventListener("keydown", handleKeyDown);
    };
  }, [closeCategoryMenus, isDesktopCategoriesOpen]);

  // Fechar barra de pesquisa ao clicar fora
  useEffect(() => {
    if (!isDesktopSearchOpen && !isSearchSuggestionsOpen) return;
    const handleKeyDown = (event: KeyboardEvent) => {
      if (event.key === "Escape") {
        setIsDesktopSearchOpen(false);
        setIsSearchSuggestionsOpen(false);
      }
    };
    const handleClickOutside = (event: MouseEvent) => {
      if (headerRef.current && !headerRef.current.contains(event.target as Node)) {
        setIsDesktopSearchOpen(false);
        setIsSearchSuggestionsOpen(false);
      }
    };
    window.addEventListener("keydown", handleKeyDown);
    window.addEventListener("click", handleClickOutside);
    return () => {
      window.removeEventListener("keydown", handleKeyDown);
      window.removeEventListener("click", handleClickOutside);
    };
  }, [isDesktopSearchOpen, isSearchSuggestionsOpen]);

  const toggleMobileParentCategory = useCallback((categoryId: string) => {
    setExpandedMobileParentIds((prev) => {
      const next = new Set(prev);
      if (next.has(categoryId)) {
        next.delete(categoryId);
      } else {
        next.add(categoryId);
      }
      return next;
    });
  }, []);

  const cancelDesktopSubmenuClose = useCallback(() => {
    if (submenuCloseTimeoutRef.current) {
      clearTimeout(submenuCloseTimeoutRef.current);
      submenuCloseTimeoutRef.current = null;
    }
  }, []);

  const cancelMegaMenuClose = useCallback(() => {
    if (megaMenuCloseTimeoutRef.current) {
      clearTimeout(megaMenuCloseTimeoutRef.current);
      megaMenuCloseTimeoutRef.current = null;
    }
  }, []);

  const openMegaMenu = useCallback(() => {
    cancelMegaMenuClose();
    setIsDesktopCategoriesOpen(true);
  }, [cancelMegaMenuClose]);

  const scheduleMegaMenuClose = useCallback(() => {
    cancelMegaMenuClose();
    megaMenuCloseTimeoutRef.current = setTimeout(() => {
      setIsDesktopCategoriesOpen(false);
      megaMenuCloseTimeoutRef.current = null;
    }, 220);
  }, [cancelMegaMenuClose]);

  const openDesktopSubmenu = useCallback(
    (categoryId: string) => {
      cancelDesktopSubmenuClose();
      setOpenDesktopSubmenuId(categoryId);
    },
    [cancelDesktopSubmenuClose]
  );

  const scheduleDesktopSubmenuClose = useCallback(
    (categoryId: string) => {
      cancelDesktopSubmenuClose();
      submenuCloseTimeoutRef.current = setTimeout(() => {
        setOpenDesktopSubmenuId((prev) => (prev === categoryId ? null : prev));
        submenuCloseTimeoutRef.current = null;
      }, 240);
    },
    [cancelDesktopSubmenuClose]
  );

  useEffect(
    () => () => {
      cancelDesktopSubmenuClose();
      cancelMegaMenuClose();
    },
    [cancelDesktopSubmenuClose, cancelMegaMenuClose]
  );

  const getCategoryHref = useCallback(
    (category: Category) => (category.slug ? `/${slug}/c/${category.slug}` : `/${slug}`),
    [slug]
  );

  const rootCategories = useMemo(
    () => categories.filter((category) => !category.parent_id),
    [categories]
  );
  const subcategoriesByParent = useMemo(() => {
    const map = new Map<string, Category[]>();
    categories.forEach((category) => {
      if (!category.parent_id) return;
      const list = map.get(category.parent_id) || [];
      list.push(category);
      map.set(category.parent_id, list);
    });
    return map;
  }, [categories]);

  const desktopVisibleCategories = useMemo(
    () => rootCategories.slice(0, Math.max(1, Math.min(desktopVisibleCount, rootCategories.length))),
    [desktopVisibleCount, rootCategories]
  );
  const selectedTopCategoryId = useMemo(() => {
    if (selectedCategory === "all") return "all";
    const current = categories.find((category) => category.id === selectedCategory);
    if (!current) return selectedCategory;
    return current.parent_id || current.id;
  }, [categories, selectedCategory]);
  const isCategoryActive = useCallback(
    (categoryId: string) => selectedTopCategoryId === categoryId || selectedCategory === categoryId,
    [selectedCategory, selectedTopCategoryId]
  );
  const activeFilterCount = useMemo(() => {
    let count = 0;
    if (sortOrder !== "relevance") count += 1;
    if (priceFilter.min || priceFilter.max) count += 1;
    return count;
  }, [priceFilter.max, priceFilter.min, sortOrder]);
  const resetCatalogFilters = useCallback(() => {
    setSortOrder("relevance");
    setPriceFilter({ min: "", max: "" });
    setPriceFilterDraft({ min: "", max: "" });
  }, []);
  const recalculateDesktopVisibleCategories = useCallback(() => {
    const navElement = desktopMenuNavRef.current;
    if (!navElement) {
      setDesktopVisibleCount(rootCategories.length);
      return;
    }
    const availableWidth = navElement.clientWidth;
    if (!Number.isFinite(availableWidth) || availableWidth <= 0) return;

    const viewportWidth = typeof window !== "undefined" ? window.innerWidth : 1280;
    const itemGap = viewportWidth >= 1280 ? 16 : 12;

    const itemWidths = rootCategories.map((category) => {
      const itemElement = desktopCategoryMeasureRefs.current.get(category.id);
      const measuredWidth = itemElement?.offsetWidth || 120;
      return Math.max(72, measuredWidth);
    });

    let usedWidth = 0;
    let visibleCount = 0;
    for (let index = 0; index < itemWidths.length; index += 1) {
      const currentWidth = itemWidths[index];
      const nextUsed = usedWidth + (visibleCount > 0 ? itemGap : 0) + currentWidth;
      if (nextUsed > availableWidth) break;
      usedWidth = nextUsed;
      visibleCount += 1;
    }

    if (visibleCount === 0 && itemWidths.length > 0) {
      visibleCount = 1;
    }
    setDesktopVisibleCount((previous) => (previous === visibleCount ? previous : visibleCount));
  }, [rootCategories]);

  useEffect(() => {
    // eslint-disable-next-line react-hooks/set-state-in-effect
    recalculateDesktopVisibleCategories();
    if (typeof window === "undefined") return;

    const resizeObserver = new ResizeObserver(() => {
      recalculateDesktopVisibleCategories();
    });

    if (desktopMenuNavRef.current) {
      resizeObserver.observe(desktopMenuNavRef.current);
    }
    if (desktopCategoriesRef.current) {
      resizeObserver.observe(desktopCategoriesRef.current);
    }

    const documentWithFonts = document as Document & { fonts?: { ready?: Promise<unknown> } };
    if (documentWithFonts.fonts?.ready) {
      void documentWithFonts.fonts.ready.then(() => {
        recalculateDesktopVisibleCategories();
      });
    }

    const rafId = window.requestAnimationFrame(() => {
      recalculateDesktopVisibleCategories();
    });

    return () => {
      window.cancelAnimationFrame(rafId);
      resizeObserver.disconnect();
    };
  }, [recalculateDesktopVisibleCategories]);

  const categoryById = useMemo(() => new Map(categories.map((category) => [category.id, category])), [categories]);
  const childrenByParent = useMemo(() => {
    const map = new Map<string, string[]>();
    categories.forEach((category) => {
      if (!category.parent_id) return;
      const list = map.get(category.parent_id) || [];
      list.push(category.id);
      map.set(category.parent_id, list);
    });
    return map;
  }, [categories]);
  const getDescendantCategoryIds = useCallback((rootId: string) => {
    const visited = new Set<string>([rootId]);
    const stack = [rootId];
    while (stack.length > 0) {
      const current = stack.pop() as string;
      const children = childrenByParent.get(current) || [];
      children.forEach((childId) => {
        if (visited.has(childId)) return;
        visited.add(childId);
        stack.push(childId);
      });
    }
    return visited;
  }, [childrenByParent]);
  const allSearchSuggestionProducts = useMemo(
    () => filterProductsBySearchTerm(products, searchTerm),
    [products, searchTerm]
  );
  const searchSuggestionProducts = useMemo(
    () => allSearchSuggestionProducts.slice(0, 5),
    [allSearchSuggestionProducts]
  );
  const catalogScopedProducts = useMemo(() => {
    const allowedCategoryIds =
      selectedCategory === "all" ? null : getDescendantCategoryIds(selectedCategory);
    return products.filter((product) => {
      const matchesCategory =
        allowedCategoryIds === null
          ? true
          : Boolean(product.category_id && allowedCategoryIds.has(product.category_id));
      const matchesSearch = !appliedSearchTerm || filterProductsBySearchTerm([product], appliedSearchTerm).length > 0;
      return matchesCategory && matchesSearch;
    });
  }, [appliedSearchTerm, getDescendantCategoryIds, products, selectedCategory]);

  const priceBounds = useMemo(() => {
    const prices = catalogScopedProducts
      .map((product) => resolveProductFilterPrice(product))
      .filter((price): price is number => price !== null && Number.isFinite(price) && price >= 0);

    if (!prices.length) {
      return { minCents: 0, maxCents: 0, hasRange: false };
    }

    const minCents = Math.floor(Math.min(...prices) * 100);
    const rawMaxCents = Math.ceil(Math.max(...prices) * 100);
    const maxCents = rawMaxCents > minCents ? rawMaxCents : minCents + 100;

    return { minCents, maxCents, hasRange: true };
  }, [catalogScopedProducts]);

  const formatCurrencyInput = useCallback((rawValue: string) => {
    const digits = rawValue.replace(/\D/g, "");
    if (!digits) return "";
    const value = parseInt(digits, 10) / 100;
    return new Intl.NumberFormat("pt-BR", {
      minimumFractionDigits: 2,
      maximumFractionDigits: 2,
    }).format(value);
  }, []);

  const handlePriceInputChange = useCallback((field: "min" | "max", rawValue: string) => {
    const formatted = formatCurrencyInput(rawValue);
    setPriceFilterDraft((previous) => ({
      ...previous,
      [field]: formatted,
    }));
  }, [formatCurrencyInput]);

  const applyPriceFilterDraft = useCallback(() => {
    let finalMin = priceFilterDraft.min;
    let finalMax = priceFilterDraft.max;
    
    if (finalMin && finalMax) {
       const minVal = parseFloat(finalMin.replace(/\D/g, "")) / 100;
       const maxVal = parseFloat(finalMax.replace(/\D/g, "")) / 100;
       if (minVal > maxVal) {
          finalMin = priceFilterDraft.max;
          finalMax = priceFilterDraft.min;
          setPriceFilterDraft({ min: finalMin, max: finalMax });
       }
    }
    
    setPriceFilter({ min: finalMin, max: finalMax });
  }, [priceFilterDraft]);

  const filteredProducts = useMemo(() => {
    let result = [...catalogScopedProducts];

    if (priceFilter.min || priceFilter.max) {
      const min = priceFilter.min ? parseFloat(priceFilter.min.replace(/\D/g, "")) / 100 : 0;
      const max = priceFilter.max ? parseFloat(priceFilter.max.replace(/\D/g, "")) / 100 : Infinity;
      result = result.filter((product) => {
        const price = resolveProductFilterPrice(product);
        return price !== null && price >= min && price <= max;
      });
    }

    if (sortOrder === "price_asc") {
      result.sort((a, b) => (resolveProductFilterPrice(a) ?? Number.POSITIVE_INFINITY) - (resolveProductFilterPrice(b) ?? Number.POSITIVE_INFINITY));
    } else if (sortOrder === "price_desc") {
      result.sort((a, b) => (resolveProductFilterPrice(b) ?? Number.NEGATIVE_INFINITY) - (resolveProductFilterPrice(a) ?? Number.NEGATIVE_INFINITY));
    } else if (sortOrder === "name_asc") {
      result.sort((a, b) => a.name.localeCompare(b.name));
    } else if (sortOrder === "name_desc") {
      result.sort((a, b) => b.name.localeCompare(a.name));
    }

    return result;
  }, [catalogScopedProducts, sortOrder, priceFilter]);
  const searchPreviewProducts = useMemo(
    () => (normalizedSearchTerm ? searchSuggestionProducts : []),
    [normalizedSearchTerm, searchSuggestionProducts]
  );

  const trackCatalogInteraction = useCallback(
    (input: {
      eventName: string;
      productId?: string | null;
      categoryId?: string | null;
      sectionId?: string | null;
      searchTerm?: string;
      meta?: Record<string, unknown>;
    }) => {
      if (!slug?.trim()) return Promise.resolve(false);
      const sourcePath = typeof window !== "undefined" ? window.location.pathname : "";
      return trackCatalogEvent({
        slug,
        eventName: input.eventName,
        productId: input.productId || null,
        categoryId: input.categoryId || null,
        sectionId: input.sectionId || null,
        searchTerm: input.searchTerm,
        sourcePath,
        meta: input.meta,
      });
    },
    [slug]
  );

  useEffect(() => {
    if (!slug?.trim() || typeof window === "undefined") return;
    const pagePath = window.location.pathname;
    const markerKey = `ktalogu_catalog_once:${encodeURIComponent(slug)}:page_view:${pagePath}`;
    if (window.sessionStorage.getItem(markerKey)) return;
    let cancelled = false;
    const run = async () => {
      const tracked = await trackCatalogInteraction({
        eventName: "page_view",
        meta: { selected_category: selectedCategory },
      });
      if (!tracked && !cancelled) {
        window.setTimeout(() => {
          if (window.sessionStorage.getItem(markerKey)) return;
          void trackCatalogInteraction({
            eventName: "page_view",
            meta: { selected_category: selectedCategory, retry: true },
          }).then((retryTracked) => {
            if (retryTracked) {
              window.sessionStorage.setItem(markerKey, "1");
            }
          });
        }, 1200);
        return;
      }
      if (tracked) {
        window.sessionStorage.setItem(markerKey, "1");
      }
    };
    void run();
    return () => {
      cancelled = true;
    };
  }, [selectedCategory, slug, trackCatalogInteraction]);

  useEffect(() => {
    const normalizedTerm = searchTerm.trim().toLowerCase();
    if (!normalizedTerm || normalizedTerm.length < 2) return;
    const timer = window.setTimeout(() => {
      trackCatalogInteraction({
        eventName: "search",
        searchTerm: normalizedTerm,
        meta: { results_count: filteredProducts.length },
      });
    }, 500);
    return () => window.clearTimeout(timer);
  }, [filteredProducts.length, searchTerm, trackCatalogInteraction]);

  useEffect(() => {
    setSearchTerm(appliedSearchTerm);
    setIsSearchSuggestionsOpen(false);
  }, [appliedSearchTerm]);

  const executeCatalogSearch = useCallback(
    (options?: { closeDesktopSearch?: boolean; closeMobileSearch?: boolean }) => {
      if (!normalizedSearchTerm) return;
      setIsSearchSuggestionsOpen(false);
      if (options?.closeDesktopSearch) {
        setIsDesktopSearchOpen(false);
      }
      if (options?.closeMobileSearch) {
        setIsMobileSearchOpen(false);
      }
      router.push(`/${slug}/buscar?search=${encodeURIComponent(normalizedSearchTerm)}`);
    },
    [normalizedSearchTerm, router, slug]
  );

  const handleSearchInputKeyDown = useCallback(
    (
      event: React.KeyboardEvent<HTMLInputElement>,
      options?: { closeDesktopSearch?: boolean; closeMobileSearch?: boolean }
    ) => {
      if (event.key === "Enter") {
        event.preventDefault();
        executeCatalogSearch(options);
      }
      if (event.key === "Escape") {
        setIsSearchSuggestionsOpen(false);
        if (options?.closeDesktopSearch) {
          setIsDesktopSearchOpen(false);
        }
        if (options?.closeMobileSearch) {
          setIsMobileSearchOpen(false);
        }
      }
    },
    [executeCatalogSearch]
  );

  const renderSearchSuggestions = useCallback(
    (options?: { insidePopover?: boolean }) => {
      if (!isSearchSuggestionsOpen || !normalizedSearchTerm) return null;

      return (
        <div
          className={`absolute left-0 right-0 z-[70] overflow-hidden rounded-2xl border border-gray-200 bg-white shadow-[0_16px_45px_rgba(15,23,42,0.12)] ${
            options?.insidePopover ? "top-[calc(100%+8px)]" : "top-[calc(100%+10px)]"
          }`}
        >
          <div className="border-b border-gray-100 px-4 py-3">
            <p className="text-xs font-semibold uppercase tracking-[0.16em] text-gray-400">Busca</p>
            <p className="mt-1 text-sm text-gray-500">
              {allSearchSuggestionProducts.length > 0
                ? `${allSearchSuggestionProducts.length} opç${allSearchSuggestionProducts.length === 1 ? "ão" : "ões"} para "${normalizedSearchTerm}"`
                : `Nenhum resultado para "${normalizedSearchTerm}"`}
            </p>
          </div>

          {searchPreviewProducts.length > 0 ? (
            <div className="max-h-[360px] overflow-y-auto py-2">
              {searchPreviewProducts.map((product) => (
                <Link
                  key={product.id}
                  href={`/${slug}/p/${product.id}`}
                  onClick={() => {
                    setIsSearchSuggestionsOpen(false);
                    setIsDesktopSearchOpen(false);
                    trackCatalogInteraction({
                      eventName: "product_click",
                      productId: product.id,
                      categoryId: product.category_id || null,
                    });
                  }}
                  className="flex items-center gap-3 px-4 py-3 transition-colors hover:bg-gray-50"
                >
                  <div className="flex h-12 w-12 shrink-0 items-center justify-center overflow-hidden rounded-xl bg-gray-50">
                    {product.image_url ? (
                      <Image
                        src={product.image_url}
                        alt={product.name}
                        width={48}
                        height={48}
                        className="h-full w-full object-cover"
                        unoptimized
                      />
                    ) : (
                      <ShoppingBag size={18} className="text-gray-300" />
                    )}
                  </div>
                  <div className="min-w-0 flex-1">
                    <p className="truncate text-sm font-medium text-gray-900">{product.name}</p>
                    <p className="mt-0.5 text-sm font-semibold text-gray-500">{formatProductPrice(product, textoSemPreco)}</p>
                  </div>
                </Link>
              ))}
            </div>
          ) : (
            <div className="px-4 py-6 text-center text-sm text-gray-400">Digite outro termo para buscar produtos.</div>
          )}

          {normalizedSearchTerm ? (
            <button
              type="button"
              onClick={() => executeCatalogSearch({ closeDesktopSearch: true })}
              className="flex w-full items-center justify-center border-t border-gray-100 px-4 py-3 text-sm font-semibold text-gray-700 transition-colors hover:bg-gray-50"
            >
              {allSearchSuggestionProducts.length > 0
                ? `Ver todos os resultados (${allSearchSuggestionProducts.length})`
                : "Ver todos os resultados"}
            </button>
          ) : null}
        </div>
      );
    },
    [
      executeCatalogSearch,
      allSearchSuggestionProducts.length,
      isSearchSuggestionsOpen,
      normalizedSearchTerm,
      searchPreviewProducts,
      slug,
      trackCatalogInteraction,
      textoSemPreco,
    ]
  );

  function resolveSectionMode(section: CatalogSection) {
    const configObject = normalizeSectionConfig(section.config);
    const configMode =
      configObject &&
      "mode" in configObject
        ? configObject.mode
        : undefined;
    const hasImageUrl = Boolean(
      configObject &&
      (("image_url" in configObject && configObject.image_url) || ("imageUrl" in configObject && configObject.imageUrl))
    );
    if (hasImageUrl && !configMode) return "image_banner";
    const rawMode = configMode ?? section.section_type ?? section.type;
    if (rawMode === "all_products" || rawMode === "category_products" || rawMode === "subcategory_products" || rawMode === "image_banner" || rawMode === "category_navigator") return rawMode;
    /* Os tipos do editor da página inicial (desenhados em home/SecoesNovasDaHome). */
    if (rawMode === "image_grid" || rawMode === "banner_carousel") return rawMode;
    return "manual_products";
  }
  const getSectionProducts = (section: CatalogSection) => {
    const mode = resolveSectionMode(section);
    if (mode === "image_banner" || mode === "image_grid" || mode === "banner_carousel") return [];
    if (mode === "all_products") return filteredProducts;
    if (mode === "category_products" || mode === "subcategory_products") {
      const targetId =
        normalizeSectionConfig(section.config) &&
        "target_category_id" in (normalizeSectionConfig(section.config) as Record<string, unknown>)
          ? String((normalizeSectionConfig(section.config) as Record<string, unknown>).target_category_id || "")
          : "";
      if (!targetId) return [];
      const allowedIds = mode === "category_products" ? getDescendantCategoryIds(targetId) : new Set([targetId]);
      return filteredProducts.filter((product) => product.category_id && allowedIds.has(product.category_id));
    }
    return section.products;
  };
  const getSectionImageConfig = (section: CatalogSection) => {
    const config = normalizeSectionConfig(section.config);
    return {
      imageUrl: config ? String(("image_url" in config ? config.image_url : ("imageUrl" in config ? config.imageUrl : "")) || "") : "",
      linkUrl: destinoDoLink(config && "link_url" in config ? config.link_url : "")?.href || "",
      openInNewTab: Boolean(config && "open_in_new_tab" in config ? config.open_in_new_tab : false),
    };
  };
  const getSectionCategoryNavigatorItems = (section: CatalogSection) => {
    const formatCategoryNavigatorLabel = (rawLabel: string) => {
      const lowered = rawLabel
        .trim()
        .replace(/\s+/g, " ")
        .toLocaleLowerCase("pt-BR");
      if (!lowered) return "Categoria";
      const smallWords = new Set(["de", "da", "do", "das", "dos", "e", "a", "o", "em", "na", "no", "para", "por"]);
      return lowered
        .split(" ")
        .map((word, index) => {
          if (index > 0 && smallWords.has(word)) return word;
          return word.charAt(0).toLocaleUpperCase("pt-BR") + word.slice(1);
        })
        .join(" ");
    };
    const config = normalizeSectionConfig(section.config);
    const rawItems = config && Array.isArray(config.items) ? config.items : [];
    return rawItems
      .map((raw) => {
        const item = raw as Record<string, unknown>;
        const targetId = String(item.target_category_id || "").trim();
        const targetSlug = String(item.target_category_slug || "").trim();
        const explicitLabel = String(item.label || "").trim();
        const imageUrl = String(item.image_url || "").trim();
        const matchedCategory =
          (targetId ? categoryById.get(targetId) : null) ||
          categories.find((category) => category.slug === targetSlug) ||
          null;
        const finalSlug = targetSlug || matchedCategory?.slug || "";
        const finalCategoryId = targetId || matchedCategory?.id || "";
        const label = formatCategoryNavigatorLabel(explicitLabel || matchedCategory?.name || "Categoria");
        return {
          finalSlug,
          finalCategoryId,
          label,
          imageUrl,
        };
      })
      .filter((item) => item.finalSlug)
      .slice(0, 12);
  };
  const getSectionViewMoreHref = (section: CatalogSection) => {
    const mode = resolveSectionMode(section);
    if (mode !== "category_products" && mode !== "subcategory_products") return null;
    const targetId =
      normalizeSectionConfig(section.config) &&
      "target_category_id" in (normalizeSectionConfig(section.config) as Record<string, unknown>)
        ? String((normalizeSectionConfig(section.config) as Record<string, unknown>).target_category_id || "")
        : "";
    const targetCategory = targetId ? categoryById.get(targetId) : null;
    if (!targetCategory?.slug) return null;
    return `/${slug}/c/${targetCategory.slug}`;
  };
  const sortedSections = useMemo(() => {
    const syntheticAllProducts: CatalogSection = {
      id: "__synthetic_all_products__",
      title: productsHeading,
      background_color: "#ffffff",
      text_color: "#111827",
      section_type: "all_products",
      config: { mode: "all_products", show_view_more: false },
      placement: "above",
      layout_width: "full",
      title_align: "left",
      title_size: "md",
      products: [],
      position: (sections || []).length,
    };
    if (!sections) return hideSections ? [syntheticAllProducts] : [];
    const base = [...sections].sort((a, b) => (a.position ?? 0) - (b.position ?? 0));
    if (hideSections) return [syntheticAllProducts];
    if (base.some((section) => resolveSectionMode(section) === "all_products")) return base;
    /* A página extra mostra só as seções dela. */
    if (paginaExtra) return base;
    return [...base, syntheticAllProducts];
  }, [sections, hideSections, productsHeading, paginaExtra]);

  const renderStandardProductCard = (
    product: Product,
    sectionId: string,
    layoutClasses: string,
    options?: { variant?: VitrineCardVariant; useVitrineMasonry?: boolean }
  ) => {
    const priceDisplay = resolveProductPriceDisplay(product, textoSemPreco);
    const variant = options?.variant ?? "standard";
    const isFeaturedCard = variant !== "standard";
    const isEditorialCard = variant === "featuredEditorial";
    const isCompactFeaturedCard = variant === "featuredCompact";
    const cardKey = `${sectionId}:${product.id}`;
    const contentProfile = getVitrineProductContentProfile(product);
    const imageGallery = contentProfile.imageGallery;
    const hasExtraGalleryImages = contentProfile.hasExtraGalleryImages;
    const activeImageIndex = Math.min(cardActiveImageIndexByProduct[product.id] ?? 0, Math.max(imageGallery.length - 1, 0));
    const selectedImageUrl = imageGallery[activeImageIndex] || product.image_url;
    const hoverImageUrl = !isFeaturedCard
      ? imageGallery.find((url, index) => index !== activeImageIndex && url !== selectedImageUrl)
      : null;
    const descriptionPreview = isFeaturedCard ? contentProfile.descriptionPreview : "";
    const hasDescriptionPreview = isFeaturedCard && contentProfile.hasDescriptionPreview;
    const mediaClass = isEditorialCard
      ? "relative aspect-[6/5] sm:aspect-[16/11] md:min-h-[320px] lg:min-h-[380px]"
      : isCompactFeaturedCard
        ? "relative aspect-[1/1] sm:aspect-[6/5] md:aspect-[16/11]"
        : "relative aspect-square";
    const imageSizes = isFeaturedCard
      ? "(max-width: 768px) 100vw, (max-width: 1280px) 50vw, 40vw"
      : "(max-width: 640px) 50vw, (max-width: 1024px) 25vw, 20vw";
    const masonryStyle =
      options?.useVitrineMasonry && vitrineCardRowSpans[cardKey]
        ? ({ gridRowEnd: `span ${vitrineCardRowSpans[cardKey]}` } satisfies CSSProperties)
        : undefined;
    
    return (
      <div
        key={product.id}
        ref={options?.useVitrineMasonry ? bindVitrineCardRef(cardKey) : undefined}
        style={masonryStyle}
        className={`catalog-product-card ${layoutClasses} relative overflow-hidden rounded-[18px] border border-gray-100 bg-white transition-all duration-300 group hover:-translate-y-1 hover:shadow-[0_8px_24px_rgba(0,0,0,0.06)] flex flex-col self-start`}
      >
        <div className="absolute inset-0 z-10 pointer-events-none flex items-center justify-center opacity-0 group-hover:opacity-100 transition-opacity duration-300">
          <button 
            type="button"
            onClick={(e) => {
              e.preventDefault();
              e.stopPropagation();
              setQuickViewProduct(product);
            }}
            className="pointer-events-auto bg-white/95 backdrop-blur shadow-lg text-gray-900 px-4 py-2 rounded-full font-medium text-sm flex items-center gap-2 hover:bg-black hover:text-white transition-colors transform translate-y-4 group-hover:translate-y-0 duration-300"
          >
            <Eye size={16} />
            Espiar
          </button>
        </div>
        <Link
          href={`/${slug}/p/${product.id}`}
          onClick={() =>
            trackCatalogInteraction({
              eventName: "product_click",
              productId: product.id,
              categoryId: product.category_id || null,
              sectionId: sectionId,
            })
          }
          className={`block overflow-hidden bg-gray-50 ${mediaClass}`}
        >
          {selectedImageUrl ? (
            <>
              <Image
                src={selectedImageUrl}
                alt={product.name}
                className={`object-cover w-full h-full transition-all duration-700 ${hoverImageUrl ? 'group-hover:opacity-0' : 'group-hover:scale-105'}`}
                fill
                sizes={imageSizes}
                unoptimized
              />
              {hoverImageUrl && (
                <Image
                  src={hoverImageUrl}
                  alt={`${product.name} - Detalhe`}
                  className="object-cover w-full h-full absolute inset-0 opacity-0 group-hover:opacity-100 transition-all duration-700 group-hover:scale-105"
                  fill
                  sizes={imageSizes}
                  unoptimized
                />
              )}
            </>
          ) : (
            <div className="w-full h-full flex items-center justify-center">
              <ShoppingBag className="text-gray-200 w-10 h-10" />
            </div>
          )}
          {/* Subtle gradient overlay for depth */}
          <div className="absolute inset-0 bg-gradient-to-t from-black/5 to-transparent opacity-0 group-hover:opacity-100 transition-opacity duration-300" />
          
          {product.unit_type === "square_meter" && (
            <div className="absolute top-2.5 left-2.5">
              <span className="text-[9px] font-semibold uppercase tracking-wider px-2 py-0.5 rounded-full bg-white/90 backdrop-blur-sm text-gray-800 shadow-sm border border-white/50">
                m²
              </span>
            </div>
          )}
          {product.product_kind === "digital" && (
            <div className="absolute bottom-2.5 left-2.5">
              <span className="inline-flex items-center gap-1 rounded-full bg-slate-900/90 px-2 py-0.5 text-[10px] font-semibold text-white shadow-sm backdrop-blur-sm">
                {product.digital_tipo === "curso" ? <PlayCircle size={10} strokeWidth={2.5} /> : <Download size={10} strokeWidth={2.5} />}
                {product.digital_tipo === "curso" ? "Vídeo" : "Digital"}
              </span>
            </div>
          )}
          <ClientPortalFavoriteButton
            productId={product.id}
            clientId={loggedClient?.id}
            initialFavorites={loggedClient?.favorites}
            primaryColor={primaryPalette.base}
            onRequireLogin={(productId) => openAuthModal({ type: "favorite_product", productId })}
          />
          {estaEsgotado(product) && (
            <div className="absolute inset-0 bg-white/60 backdrop-blur-[1px] flex items-center justify-center">
              <span className="text-gray-800 font-medium px-3 py-1 bg-white shadow-sm border border-gray-100 rounded-full text-xs">Esgotado</span>
            </div>
          )}
        </Link>
        
        <div className={`flex flex-col flex-1 ${isFeaturedCard ? 'p-4 md:p-5 lg:p-6' : 'p-3'}`}>
          <div className="flex-1 min-h-0">
            <h3
              className={`mb-1.5 text-gray-600 ${
                isFeaturedCard
                  ? "font-semibold leading-[1.18] tracking-[-0.02em] text-[17px] sm:text-[18px] md:text-[22px] line-clamp-2"
                  : "font-medium leading-[1.35] text-[13px] h-[2.2rem] line-clamp-2"
              }`}
              title={product.name}
            >
              {product.name}
            </h3>
            
            <div className={`mb-2.5 flex items-center ${isFeaturedCard ? 'min-h-[28px] md:min-h-[36px]' : 'h-5'}`}>
              {priceDisplay.hasWholesaleBadge ? (
                <span className={`inline-flex items-center gap-1 rounded-full bg-orange-50 border border-orange-100/50 ${isFeaturedCard ? 'px-3 py-1.5' : 'px-1.5 py-0.5'}`}>
                  <Flame size={isFeaturedCard ? 14 : 9} className="text-orange-400 fill-orange-400" />
                  <span className={`font-bold uppercase tracking-wider text-orange-600/90 ${isFeaturedCard ? 'text-[12px]' : 'text-[9px]'}`}>
                    Atacado
                  </span>
                </span>
              ) : priceDisplay.isPremiumMeasuredPricing ? (
                <span className={`inline-flex items-center rounded-full border border-violet-200/90 bg-violet-50/90 font-bold uppercase tracking-wider text-violet-700 ${isFeaturedCard ? 'px-3.5 py-1.5 text-[12px]' : 'px-2 py-0.5 text-[9px]'}`}>
                  Sob medida
                </span>
              ) : null}
            </div>

            {isFeaturedCard && (hasDescriptionPreview || hasExtraGalleryImages) ? (
              <div className={`mt-2.5 ${isEditorialCard ? 'space-y-3.5' : 'space-y-2.5 md:space-y-3'}`}>
                {hasExtraGalleryImages ? (
                  <div>
                    <div className={`${isEditorialCard ? 'grid grid-cols-4 gap-2 md:gap-2.5' : 'grid grid-cols-3 gap-1.5 md:gap-2'}`}>
                      {imageGallery.slice(0, isEditorialCard ? 4 : 3).map((imageUrl, index) => {
                        const isActiveImage = index === activeImageIndex;
                        return (
                          <button
                            key={`${product.id}-gallery-${index}`}
                            type="button"
                            onClick={(event) => {
                              event.preventDefault();
                              event.stopPropagation();
                              setCardActiveImageIndexByProduct((current) => ({
                                ...current,
                                [product.id]: index,
                              }));
                            }}
                            className={`group/thumb relative aspect-square overflow-hidden border bg-gradient-to-br from-gray-50 to-gray-100 transition-all duration-300 ${
                              isActiveImage
                                ? "border-gray-900 ring-2 ring-gray-900/10 shadow-[0_10px_24px_rgba(17,24,39,0.12)]"
                                : "border-gray-200 hover:-translate-y-0.5 hover:border-gray-300 hover:shadow-[0_8px_18px_rgba(17,24,39,0.08)]"
                            } ${isEditorialCard ? 'rounded-2xl' : 'rounded-lg md:rounded-xl'}`}
                            aria-label={`Ver foto ${index + 1} de ${product.name}`}
                          >
                            <Image
                              src={imageUrl}
                              alt={`${product.name} - Foto ${index + 1}`}
                              fill
                              className={`object-cover transition-transform duration-500 ${
                                isActiveImage ? "scale-[1.02]" : "group-hover/thumb:scale-105"
                              }`}
                              sizes="120px"
                              unoptimized
                            />
                            <div
                              className={`absolute inset-0 transition-opacity ${
                                isActiveImage
                                  ? "bg-gradient-to-t from-black/10 via-transparent to-transparent"
                                  : "bg-gradient-to-t from-black/0 via-transparent to-transparent group-hover/thumb:from-black/5"
                              }`}
                            />
                          </button>
                        );
                      })}
                    </div>
                  </div>
                ) : null}
                {descriptionPreview ? (
                  <p
                    className={`text-[#6b7280] tracking-[0.012em] ${
                      isEditorialCard
                        ? "text-[13px] md:text-[14px] leading-[1.85] line-clamp-4"
                        : "text-[12px] md:text-[13px] leading-[1.72] line-clamp-3"
                    }`}
                    style={{ fontFamily: "var(--ks-catalog-font-body, var(--ks-font-editorial))" }}
                  >
                    {descriptionPreview}
                  </p>
                ) : null}
              </div>
            ) : null}
          </div>

          <div className="mt-auto flex items-end justify-between gap-2 pt-4">
            <div className="flex-1 min-w-0 flex flex-col justify-end">
              {priceDisplay.hasWholesalePricing && (
                <span className={`text-gray-400 font-medium leading-none mb-1 tracking-wide ${isFeaturedCard ? 'text-[13px]' : 'text-[9px]'}`}>
                  A partir de
                </span>
              )}
              {visao.precisaEntrar ? (
                /* Preco so para quem entrou: o lugar do preco vira o convite. */
                <button
                  type="button"
                  onClick={(event) => {
                    event.preventDefault();
                    event.stopPropagation();
                    openAuthModal({ type: "see_prices" });
                  }}
                  className={`text-left font-semibold leading-tight tracking-tight underline-offset-2 hover:underline ${isFeaturedCard ? 'text-[16px]' : 'text-[13px]'}`}
                  style={{ color: cardAccentColor }}
                >
                  {textoSemPreco}
                </button>
              ) : (
              <p
                className={`font-semibold leading-none tracking-tight ${
                  isEditorialCard
                    ? 'text-[26px] sm:text-[30px] md:text-[38px]'
                    : isCompactFeaturedCard
                      ? 'text-[22px] sm:text-[24px] md:text-[32px]'
                      : 'text-[17px]'
                }`}
                style={{ color: cardAccentColor }}
              >
                {priceDisplay.hasWholesalePricing
                  ? priceDisplay.text.replace("A partir de ", "")
                  : priceDisplay.text}
              </p>
              )}
              {priceDisplay.isPremiumMeasuredPricing && (
                <span className={`mt-1.5 leading-tight text-gray-500 ${isFeaturedCard ? 'text-[13px]' : 'text-[10px]'}`}>
                  {priceDisplay.helperText}
                </span>
              )}
            </div>
            <div className={`shrink-0 self-end ${isFeaturedCard ? 'scale-[1.2] origin-bottom-right' : ''}`}>
              <AddToCartButton product={product} primaryColor={cardAccentColor} slug={slug} variant="icon" />
            </div>
          </div>
        </div>
      </div>
    );
  };

  const renderSection = (section: CatalogSection) => {
    if (ehSecaoNovaDaHome(section)) {
      return (
        <SecaoNovaDaHome key={section.id} secao={section} variante="padrao" slug={slug} categorias={categories} corDaLoja={primaryPalette.base} produtos={products as never} />
      );
    }
    const sectionMode = resolveSectionMode(section);
    const isContained = sectionMode !== "all_products" && sectionMode !== "category_navigator" && section.layout_width === "contained";
    const sectionProducts = getSectionProducts(section);
    const categoryNavigatorItems = sectionMode === "category_navigator" ? getSectionCategoryNavigatorItems(section) : [];
    const viewMoreHref = getSectionViewMoreHref(section);
    const imageConfig = getSectionImageConfig(section);
    const showViewMore =
      Boolean(viewMoreHref) &&
      !(
        section.config &&
        typeof section.config === "object" &&
        "show_view_more" in (section.config as Record<string, unknown>) &&
        (section.config as Record<string, unknown>).show_view_more === false
      );
    
    const wrapperPadding = sectionMode === "all_products" ? "py-6 md:py-8" : sectionMode === "category_navigator" ? "py-4 md:py-5" : (sectionMode === "image_banner" && !isContained ? "py-0" : (isContained ? "py-0" : "py-12 md:py-16"));
    const wrapperMargin = sectionMode === "all_products" ? "mb-8 md:mb-12" : sectionMode === "category_navigator" ? "mt-6 md:mt-8 mb-6 md:mb-8" : "mt-12 md:mt-16 mb-12 md:mb-16"; 

    const isExpanded = expandedSectionIds.has(section.id);
    const hasMoreThanFourProducts = sectionProducts.length > 4;
    // Disable carousel/expansion logic for "all_products" mode or if forced by config
    const isCarouselEnabled = sectionMode !== "all_products"; 

    return (
      <div 
        key={section.id} 
        className={`catalog-section catalog-section-${sectionMode} ${wrapperPadding} ${wrapperMargin} ${sectionMode === "all_products" ? "scroll-mt-28" : ""}`}
        style={{ backgroundColor: sectionMode === "all_products" || sectionMode === "category_navigator" ? undefined : (sectionMode === "image_banner" && !isContained ? "transparent" : (isContained ? "transparent" : section.background_color)) }}
        id={sectionMode === "all_products" ? "produtos" : undefined}
        ref={sectionMode === "all_products" ? productsSectionRef : undefined}
      >
        <div className={sectionMode === "image_banner" && !isContained ? "" : "max-w-7xl mx-auto px-4 sm:px-6 lg:px-8"}>
          <div
            className={
              sectionMode === "image_banner" && !isContained 
                ? "catalog-section-shell catalog-section-shell-banner" 
                : (isContained 
                    ? (sectionMode === "image_banner" ? "catalog-section-shell rounded-none md:rounded-3xl p-0 md:p-10 shadow-sm overflow-hidden" : "catalog-section-shell rounded-3xl p-8 md:p-10 shadow-sm overflow-hidden")
                    : "catalog-section-shell")
            }
            style={{ backgroundColor: sectionMode === "image_banner" && !isContained ? undefined : (isContained ? section.background_color : undefined) }}
          >
            {sectionMode === "image_banner" ? (
              imageConfig.imageUrl ? (
                <div className={isContained ? (sectionMode === "image_banner" ? "md:-m-10" : "-m-8 md:-m-10") : ""}>
                {imageConfig.linkUrl ? (
                  <Link href={imageConfig.linkUrl} target={imageConfig.openInNewTab ? "_blank" : undefined} rel={imageConfig.openInNewTab ? "noopener noreferrer" : undefined} className="block">
                    <Image src={imageConfig.imageUrl} alt={section.title || "Banner"} width={1920} height={240} className="w-full h-auto object-cover block" unoptimized />
                  </Link>
                ) : (
                  <div className="block">
                    <Image src={imageConfig.imageUrl} alt={section.title || "Banner"} width={1920} height={240} className="w-full h-auto object-cover block" unoptimized />
                  </div>
                )}
                </div>
              ) : null
            ) : (
              <>
                <div className="mb-4 md:mb-8 flex items-center justify-between gap-4">
                  <h2 className={`catalog-section-title font-bold ${section.title_align === "left" ? "text-left" : section.title_align === "right" ? "text-right" : "text-center"} ${section.title_size === "sm" ? "text-xl md:text-2xl" : section.title_size === "md" ? "text-2xl md:text-3xl" : section.title_size === "lg" ? "text-3xl md:text-4xl" : "text-4xl md:text-5xl"}`} style={{ color: section.text_color }}>{section.title}</h2>
                  {showViewMore && viewMoreHref && (
                    <Link
                      href={viewMoreHref}
                      onClick={() =>
                        trackCatalogInteraction({
                          eventName: "view_more_click",
                          categoryId:
                            typeof section.config === "object" && section.config && "target_category_id" in section.config
                              ? String((section.config as Record<string, unknown>).target_category_id || "")
                              : null,
                          sectionId: section.id,
                        })
                      }
                      className="text-xs font-bold uppercase tracking-wide rounded-full px-4 py-2 border border-gray-200 bg-white text-gray-700 hover:bg-gray-50 hidden md:inline-block"
                    >
                      Ver mais
                    </Link>
                  )}
                </div>
                {sectionMode === "category_navigator" ? (
                  categoryNavigatorItems.length > 0 ? (
                    <div className="relative overflow-visible">
                      <div className="flex items-stretch overflow-x-auto snap-x snap-mandatory scroll-pl-4 -mx-4 px-4 pb-2 gap-2.5 scrollbar-hide sm:mx-0 sm:px-0 sm:flex-wrap sm:overflow-visible sm:gap-4 md:gap-5">
                        {categoryNavigatorItems.map((item, idx) => (
                          <Link
                            key={`${item.finalSlug}-${idx}`}
                            href={`/${slug}/c/${item.finalSlug}`}
                            onClick={() =>
                              trackCatalogInteraction({
                                eventName: "category_click",
                                categoryId: item.finalCategoryId || null,
                                sectionId: section.id,
                              })
                            }
                            className="min-w-[108px] w-[29.5%] sm:min-w-0 sm:w-[120px] md:w-[126px] snap-start flex flex-col items-center gap-2 group"
                          >
                            <div className="h-24 w-24 md:h-28 md:w-28 rounded-full bg-white overflow-hidden">
                              {item.imageUrl ? (
                                <Image src={item.imageUrl} alt={item.label} width={112} height={112} className="w-full h-full object-cover" unoptimized />
                              ) : (
                                <div className="w-full h-full flex items-center justify-center bg-gray-50">
                                  <Tag size={26} className="text-gray-300" />
                                </div>
                              )}
                            </div>
                            <span className="text-[12px] md:text-[13px] font-semibold text-center leading-tight line-clamp-2 text-gray-700 group-hover:text-gray-900">
                              {item.label}
                            </span>
                          </Link>
                        ))}
                      </div>
                      <div
                        className="pointer-events-none absolute -right-4 top-0 bottom-0 w-12 sm:hidden"
                        style={{
                          background: "linear-gradient(to left, rgba(0, 0, 0, 0.34) 0%, rgba(0, 0, 0, 0.18) 42%, rgba(0, 0, 0, 0) 100%)",
                          WebkitMaskImage: "linear-gradient(to bottom, transparent 0%, black 16%, black 84%, transparent 100%)",
                          maskImage: "linear-gradient(to bottom, transparent 0%, black 16%, black 84%, transparent 100%)",
                        }}
                      />
                    </div>
                  ) : (
                    <div className="text-center py-20 bg-white rounded-3xl shadow-sm border border-gray-100">
                      <h3 className="text-lg font-medium text-gray-900">Nenhuma categoria configurada</h3>
                      <p className="text-gray-500 mt-1">Adicione categorias no gadget para exibir aqui.</p>
                    </div>
                  )
                ) : sectionProducts.length === 0 ? (
                  <div className="text-center py-20 bg-white rounded-3xl shadow-sm border border-gray-100">
                    <div className="inline-flex items-center justify-center w-16 h-16 rounded-full bg-gray-100 mb-4">
                      <Search className="text-gray-400" size={32} />
                    </div>
                    <h3 className="text-lg font-medium text-gray-900">Nenhum produto encontrado</h3>
                    <p className="text-gray-500 mt-1">Tente mudar o filtro ou a busca.</p>
                  </div>
                ) : (
                <>
                  <div 
                    ref={(el) => {
                      if (el) carouselRefs.current.set(section.id, el);
                      else carouselRefs.current.delete(section.id);
                    }}
                    className={`catalog-section-grid ${isCarouselEnabled && !isExpanded ? "flex items-stretch overflow-x-auto snap-x snap-mandatory scroll-pl-4 -mx-4 px-4 pb-4 gap-3 scrollbar-hide" : "grid grid-cols-2 gap-2"} sm:grid-cols-2 lg:grid-cols-4 xl:grid-cols-5 md:grid md:gap-6`}
                    onTouchStart={() => handleTouchStart(section.id)}
                    onTouchEnd={() => handleTouchEnd(section.id)}
                  >
                    {(sectionMode === "all_products" ? sectionProducts.slice(0, quantosVisiveis(section.id)) : sectionProducts).map((product) => 
                      renderStandardProductCard(
                        product, 
                        section.id, 
                        isCarouselEnabled && !isExpanded 
                          ? "min-w-[150px] w-[42%] flex-shrink-0 snap-start self-stretch h-[270px] md:min-w-0 md:w-auto md:flex-shrink md:self-auto md:h-full" 
                          : "h-full"
                      )
                    )}
                  </div>

                  {sectionMode === "all_products" && sectionProducts.length > quantosVisiveis(section.id) && (
                    <div className="mt-6 flex justify-center">
                      <button
                        type="button"
                        onClick={() => mostrarMaisDaSecao(section.id)}
                        className="group inline-flex items-center gap-1.5 px-5 py-2.5 text-sm font-medium text-gray-700 bg-white border border-gray-200 rounded-full shadow-sm hover:bg-gray-50 hover:text-gray-900 transition-all duration-200 active:scale-95"
                      >
                        Ver mais produtos ({sectionProducts.length - quantosVisiveis(section.id)} restantes)
                        <ChevronDown size={13} className="opacity-70 group-hover:translate-y-0.5 transition-transform" />
                      </button>
                    </div>
                  )}

                  {/* Mobile Toggle Button - Only if carousel enabled */}
                  {isCarouselEnabled && hasMoreThanFourProducts && (
                    <div className="mt-3 flex justify-center md:hidden">
                      <button
                        onClick={() => toggleSectionExpansion(section.id)}
                        className="group inline-flex items-center gap-1.5 px-4 py-2.5 text-sm font-medium text-gray-700 bg-white/95 border border-white rounded-full shadow-[0_6px_16px_rgba(15,23,42,0.10)] hover:bg-white hover:text-gray-900 transition-all duration-200 active:scale-95"
                      >
                        {isExpanded ? (
                          <>
                            Ver menos <ChevronUp size={13} className="opacity-70 group-hover:-translate-y-0.5 transition-transform" />
                          </>
                        ) : (
                          <>
                            Ver mais produtos <ChevronDown size={13} className="opacity-70 group-hover:translate-y-0.5 transition-transform" />
                          </>
                        )}
                      </button>
                    </div>
                  )}
                </>
                )}
              </>
            )}
          </div>
        </div>
      </div>
    );
  };

  const slideBanners = useMemo(() => {
    return (banners || []).filter((b) => Boolean(b.image_url));
  }, [banners]);

  const activeBannerIndex = useMemo(() => {
    const count = slideBanners.length;
    if (count === 0) return 0;
    return ((currentBanner % count) + count) % count;
  }, [currentBanner, slideBanners.length]);

  const infoIconMap = useMemo(() => {
    return {
      truck: Truck,
      creditCard: CreditCard,
      shieldCheck: ShieldCheck,
      package: Package,
      clock: Clock,
      badgeCheck: BadgeCheck,
      mapPin: MapPin,
      headphones: Headphones,
    } as Record<string, React.ComponentType<{ size?: number; className?: string; style?: React.CSSProperties }>>;
  }, []);
  const vitrineInfoStripItems = useMemo(
    () =>
      (infoStripItems.length > 0
        ? infoStripItems.slice(0, 3)
        : [
            { icon: "truck", title: "Entrega Rápida", subtitle: "Para todo Brasil" },
            { icon: "shieldCheck", title: "Compra Segura", subtitle: "Ambiente protegido" },
            { icon: "creditCard", title: "Pagamento Facilitado", subtitle: "Em até 12x" },
          ]),
    [infoStripItems]
  );

  useEffect(() => {
    if (slideBanners.length <= 1) return;
    const t = window.setInterval(() => {
      setCurrentBanner((prev) => (prev + 1) % slideBanners.length);
    }, 6000);
    return () => window.clearInterval(t);
  }, [slideBanners.length]);

  useEffect(() => {
    if (!isDesktopCategoriesOpen) return;

    const handleClickOutside = (event: MouseEvent) => {
      if (!desktopCategoriesRef.current) return;
      if (!desktopCategoriesRef.current.contains(event.target as Node)) {
        setIsDesktopCategoriesOpen(false);
        setOpenDesktopSubmenuId(null);
      }
    };

    document.addEventListener("mousedown", handleClickOutside);
    return () => document.removeEventListener("mousedown", handleClickOutside);
  }, [isDesktopCategoriesOpen]);

  useEffect(() => {
    if (!announcementCountdownEnabled || !announcementCountdownEndAt) return;
    const timer = window.setInterval(() => setCurrentTimestamp(Date.now()), 1000);
    return () => window.clearInterval(timer);
  }, [announcementCountdownEnabled, announcementCountdownEndAt]);

  useEffect(() => {
    if (!announcementCouponCopied) return;
    const timer = window.setTimeout(() => setAnnouncementCouponCopied(false), 1800);
    return () => window.clearTimeout(timer);
  }, [announcementCouponCopied]);

  useEffect(() => {
    if (!announcementMarqueePaused) return;
    const timer = window.setTimeout(() => setAnnouncementMarqueePaused(false), 3200);
    return () => window.clearTimeout(timer);
  }, [announcementMarqueePaused]);

  useEffect(() => {
    const couponId = String(announcementCouponId || "").trim();
    if (!couponId) return;
    if (resolvedAnnouncementCoupon?.code || announcementCoupon?.code) return;
    let cancelled = false;
    const run = async () => {
      try {
        const userId = products[0]?.user_id;
        if (!userId) return;
        const supabase = getSupabaseClient();
        const { data } = await supabase
          .from("catalog_coupons")
          .select("id,code,type,value,active,starts_at,ends_at")
          .eq("id", couponId)
          .eq("user_id", userId)
          .maybeSingle();
        if (cancelled || !data || !String(data.code || "").trim()) return;
        setResolvedAnnouncementCoupon(data as AnnouncementCoupon);
      } catch {}
    };
    void run();
    return () => {
      cancelled = true;
    };
  }, [announcementCoupon?.code, announcementCouponId, resolvedAnnouncementCoupon?.code, products]);

  useEffect(() => {
    const enabled = Boolean(socialProofEnabled);
    const intervalMs = Math.min(120000, Math.max(5000, Number(socialProofIntervalSeconds || 18) * 1000));
    const durationMs = Math.min(20000, Math.max(2000, Number(socialProofDurationSeconds || 5) * 1000));
    const maxCount = Math.min(5, Math.max(1, Number(socialProofMaxVisible || 2)));
    if (!enabled || products.length === 0) return;
    let cancelled = false;
    let timeoutId: number | null = null;
    const pushToast = () => {
      if (cancelled) return;
      const randomName = BRAZILIAN_NAMES[Math.floor(Math.random() * BRAZILIAN_NAMES.length)] || "Cliente";
      const randomProduct = products[Math.floor(Math.random() * products.length)];
      if (!randomProduct) return;
      const randomMinutes = Math.floor(Math.random() * 7) + 1;
      const toastId = `${Date.now()}-${Math.random().toString(36).slice(2, 8)}`;
      setSocialProofToasts((prev) => {
        const next = [{ id: toastId, productId: String(randomProduct.id), name: randomName, productName: randomProduct.name, imageUrl: randomProduct.image_url, minutesAgo: randomMinutes }, ...prev];
        return next.slice(0, maxCount);
      });
      window.setTimeout(() => {
        setSocialProofToasts((prev) => prev.filter((toast) => toast.id !== toastId));
      }, durationMs);
      timeoutId = window.setTimeout(pushToast, intervalMs);
    };
    timeoutId = window.setTimeout(pushToast, 1600);
    return () => {
      cancelled = true;
      if (timeoutId !== null) window.clearTimeout(timeoutId);
    };
  }, [products, socialProofDurationSeconds, socialProofEnabled, socialProofIntervalSeconds, socialProofMaxVisible]);

  const dismissSocialProofToast = useCallback((toastId: string) => {
    setSocialProofToasts((prev) => prev.filter((toast) => toast.id !== toastId));
  }, []);

  const primaryBase = normalizeHexColor(primaryColor, "#4F46E5");
  const primaryText = getReadableTextColor(primaryBase);
  const primaryUsesLightText = primaryText === "#FFFFFF";
  
  // Refinando o contraste no Header
  const headerIconAndTextColor = catalogHeaderIconColor
    ? normalizeHexColor(catalogHeaderIconColor, primaryUsesLightText ? "#FFFFFF" : "#111827")
    : (primaryUsesLightText ? "#FFFFFF" : "#111827");
  
  const primaryPalette = {
    base: primaryBase,
    text: headerIconAndTextColor,
    hoverBg: primaryUsesLightText ? withAlpha("#FFFFFF", 0.14) : withAlpha("#111827", 0.1),
    onWhiteSurface: ensureColorContrast(primaryBase, "#FFFFFF", { minRatio: 4.5 }),
    onSoftSurface: ensureColorContrast(primaryBase, "#F3F4F6", { minRatio: 4.5 }),
    badgeBg: primaryUsesLightText ? "#FFFFFF" : "#111827",
    badgeText: primaryBase,
  };
  
  const resolvedHeaderBg = normalizeHexColor(headerColor || "", primaryPalette.base);
  const resolvedHeaderText = ensureColorContrast(
    normalizeHexColor(headerTextColor || catalogHeaderIconColor || "", primaryPalette.text),
    resolvedHeaderBg,
    { dark: "#111827", light: "#FFFFFF", minRatio: 4.5 }
  );
  const resolvedMenuBg = normalizeHexColor(menuColor || "", resolvedHeaderBg);
  const resolvedMenuText = ensureColorContrast(
    normalizeHexColor(menuTextColor || "", resolvedHeaderText),
    resolvedMenuBg,
    { dark: "#111827", light: "#FFFFFF", minRatio: 4.5 }
  );
  const headerUsesLightText = resolvedHeaderText === "#FFFFFF";
  const searchSurface = "#FFFFFF";
  const searchBorder = ensureColorContrast(
    headerUsesLightText ? "#FFFFFF" : "#E2E8F0",
    resolvedHeaderBg,
    { dark: "#CBD5E1", light: "#94A3B8", minRatio: 1.35 }
  );
  const searchText = ensureColorContrast(
    "#1E293B",
    normalizeHexColor(searchSurface, "#FFFFFF"),
    { dark: "#111827", light: "#FFFFFF", minRatio: 4.5 }
  );
  const searchIcon = ensureColorContrast(
    "#94A3B8",
    normalizeHexColor(searchSurface, "#FFFFFF"),
    { dark: "#64748B", light: "#94A3B8", minRatio: 3 }
  );

  const headerPalette = {
    bg: resolvedHeaderBg,
    text: resolvedHeaderText,
    menuBg: resolvedMenuBg,
    menuText: resolvedMenuText,
    searchBg: searchSurface,
    searchBorder,
    searchText,
    searchIcon,
  };
  const loggedClientFirstName = loggedClient?.name?.trim().split(/\s+/)[0] || "Cliente";


  const footerBg = normalizeHexColor((footerColor || "").trim(), primaryPalette.base);
  const footerText = ensureColorContrast(
    normalizeHexColor(footerTextColor || "", getReadableTextColor(footerBg)),
    footerBg,
    { dark: "#111827", light: "#FFFFFF", minRatio: 4.5 }
  );
  const footerUsesLightText = footerText === "#FFFFFF";
  const footerPalette = {
    bg: footerBg,
    text: footerText,
    muted: footerUsesLightText ? withAlpha("#FFFFFF", 0.82) : withAlpha("#111827", 0.78),
    subtleBg: footerUsesLightText ? withAlpha("#FFFFFF", 0.12) : withAlpha("#000000", 0.08),
    subtleBgHover: footerUsesLightText ? withAlpha("#FFFFFF", 0.18) : withAlpha("#000000", 0.12),
    divider: footerUsesLightText ? withAlpha("#FFFFFF", 0.18) : withAlpha("#111827", 0.14),
    chipBg: footerUsesLightText ? withAlpha("#FFFFFF", 0.14) : withAlpha("#FFFFFF", 0.65),
    chipText: footerUsesLightText ? withAlpha("#FFFFFF", 0.92) : "#111827",
    isLightText: footerUsesLightText,
  };
  /* Escolha do lojista vence; sem escolha, segue o calculo de contraste sobre
     a cor principal, que e o comportamento de sempre. */
  const cardAccentColor = cardButtonColor
    ? normalizeHexColor(cardButtonColor, primaryPalette.base)
    : ensureColorContrast(primaryPalette.base, "#FFFFFF", {
        dark: "#111827",
        light: "#FFFFFF",
        minRatio: 4.5,
      });
  const customHeaderNameColor = normalizeHexColor(storeNameColor || "");
  const customHeaderSloganColor = normalizeHexColor(storeSloganColor || "");
  const autoHeaderNameColor = ensureColorContrast(headerPalette.text, headerPalette.bg, {
    dark: "#111827",
    light: "#FFFFFF",
  });
  const headerNameTextColor = customHeaderNameColor || autoHeaderNameColor;
  const headerSloganTextColor = customHeaderSloganColor || withAlpha(autoHeaderNameColor, 0.82);
  const normalizedLogoEffectType = logoEffectType === "rotate_3d" || logoEffectType === "blink" || logoEffectType === "pulse_glow" ? logoEffectType : "none";
  const normalizedLogoEffectSpeed = Math.min(200, Math.max(50, Math.round(Number(logoEffectSpeed) || 100)));
  const normalizedLogoEffectIntensity = Math.min(180, Math.max(40, Math.round(Number(logoEffectIntensity) || 100)));
  const logoSpeedDurationMultiplier = 100 / normalizedLogoEffectSpeed;
  const logoIntensityMultiplier = normalizedLogoEffectIntensity / 100;
  const logoEffectClass = logoEffectEnabled
    ? normalizedLogoEffectType === "rotate_3d"
      ? "ks-logo-effect-rotate3d"
      : normalizedLogoEffectType === "blink"
        ? "ks-logo-effect-blink"
        : normalizedLogoEffectType === "pulse_glow"
          ? "ks-logo-effect-pulse"
          : ""
    : "";
  const shouldShowStoreName = Boolean(showStoreNameInHeader && String(storeName || "").trim());
  const shouldShowStoreSlogan = Boolean(showStoreSloganInHeader && String(storeSlogan || "").trim());
  const normalizedAnnouncementBackground = normalizeHexColor(announcementBackgroundColor || "", "#111827");
  const normalizedAnnouncementText = normalizeHexColor(announcementTextColor || "", "#FFFFFF");
  const normalizedAnnouncementBadgeBackground = normalizeHexColor(announcementCouponBadgeColor || "", "#FB7185");
  const normalizedAnnouncementBadgeText = getReadableTextColor(normalizedAnnouncementBadgeBackground);
  const announcementBadgeBorder = withAlpha(normalizedAnnouncementBadgeText, 0.45);
  const announcementTextResolved = String(announcementText || "").trim();
  const effectiveAnnouncementCoupon = resolvedAnnouncementCoupon || announcementCoupon || null;
  const announcementHasCoupon = Boolean(effectiveAnnouncementCoupon?.code);
  const announcementCouponText = announcementHasCoupon ? formatCouponPromoText(effectiveAnnouncementCoupon) : "";
  const announcementCountdownVisible = Boolean(announcementCountdownEnabled && announcementCountdownEndAt);
  const announcementCountdownParts = announcementCountdownVisible
    ? getCountdownParts(String(announcementCountdownEndAt || ""), currentTimestamp)
    : [];
  const announcementButtonHref = resolveAnnouncementButtonHref(announcementButtonUrl, slug);
  const announcementButtonVisible = Boolean(String(announcementButtonLabel || "").trim() && announcementButtonHref);
  const announcementBadgeVisible = Boolean(announcementShowCouponBadge !== false && announcementHasCoupon);
  const announcementHasVisibleContent = Boolean(announcementTextResolved || announcementCouponText || announcementBadgeVisible || announcementCountdownVisible || announcementButtonVisible);
  const announcementVisible = Boolean(announcementEnabled && announcementHasVisibleContent);
  const announcementStickyEnabled = announcementVisible && announcementSticky !== false;
  const socialProofEnabledResolved = Boolean(socialProofEnabled);
  const socialProofPositionResolved = socialProofPosition === "right" ? "right" : "left";

  const socialLinks = useMemo(() => {
    const ensureUrl = (value: string) => {
      const v = value.trim();
      if (!v) return "";
      if (v.startsWith("http://") || v.startsWith("https://")) return v;
      return `https://${v}`;
    };

    const resolvedInstagram = socialInstagram || companySocialInstagram || "";
    const resolvedFacebook = socialFacebook || companySocialFacebook || "";
    const resolvedLinkedin = socialLinkedin || companySocialLinkedin || "";
    const resolvedTwitter = socialTwitter || companySocialTwitter || "";
    const resolvedYoutube = socialYoutube || companySocialYoutube || "";

    return [
      { key: "instagram", label: "Instagram", href: ensureUrl(resolvedInstagram), Icon: Instagram },
      { key: "facebook", label: "Facebook", href: ensureUrl(resolvedFacebook), Icon: Facebook },
      { key: "linkedin", label: "LinkedIn", href: ensureUrl(resolvedLinkedin), Icon: Linkedin },
      { key: "twitter", label: "X (Twitter)", href: ensureUrl(resolvedTwitter), Icon: Twitter },
      { key: "youtube", label: "YouTube", href: ensureUrl(resolvedYoutube), Icon: Youtube },
    ].filter((x) => Boolean(x.href));
  }, [companySocialFacebook, companySocialInstagram, companySocialLinkedin, companySocialTwitter, companySocialYoutube, socialFacebook, socialInstagram, socialLinkedin, socialTwitter, socialYoutube]);

  const phoneDigits = (companyPhone || phone || "").replace(/\D/g, "");
  const catalogWhatsappDigits = normalizeWhatsappForLink(whatsapp);
  const companyWhatsappDigits = normalizeWhatsappForLink(companyWhatsapp);
  const bestWhatsappDigits = companyWhatsappDigits || catalogWhatsappDigits;
  const handleCopyAnnouncementCoupon = async () => {
    const code = effectiveAnnouncementCoupon?.code || "";
    if (!code || typeof navigator === "undefined" || !navigator.clipboard) return;
    setAnnouncementMarqueePaused(true);
    try {
      await navigator.clipboard.writeText(code);
      setAnnouncementCouponCopied(true);
    } catch {}
  };
  const renderAnnouncementDesktopFlowItems = () => (
    <>
      {announcementTextResolved ? <span className="text-sm font-medium leading-tight">{renderHighlightedText(announcementTextResolved)}</span> : null}
      {announcementCouponText ? (
        <>
          {announcementTextResolved ? <span className="text-white/65 text-sm">•</span> : null}
          <span className="text-sm font-semibold">{announcementCouponText}</span>
        </>
      ) : null}
      {announcementBadgeVisible ? (
        <>
          <span className="text-white/65 text-sm">•</span>
          <button
            type="button"
            onClick={handleCopyAnnouncementCoupon}
            onTouchStart={() => setAnnouncementMarqueePaused(true)}
            onMouseEnter={() => setAnnouncementMarqueePaused(true)}
            className="relative inline-flex items-center gap-1.5 rounded-md border-2 border-dashed px-2.5 py-1 text-[11px] font-extrabold tracking-wide"
            style={{ backgroundColor: normalizedAnnouncementBadgeBackground, color: normalizedAnnouncementBadgeText, borderColor: announcementBadgeBorder }}
          >
            <span>{effectiveAnnouncementCoupon?.code}</span>
            <span className="inline-flex h-3.5 w-px" style={{ backgroundColor: announcementBadgeBorder }} />
            {announcementCouponCopied ? <Check size={12} /> : <Copy size={12} />}
          </button>
        </>
      ) : null}
    </>
  );
  const renderAnnouncementMobileTextItems = () => (
    <div className="flex flex-col min-w-0">
      <span className="text-[14px] font-bold leading-tight">
        {announcementTextResolved ? renderHighlightedText(announcementTextResolved) : "Oferta especial!"}
      </span>
      {announcementCouponText && (
        <span className="text-[11px] font-medium leading-tight opacity-90 mt-0.5">
          {announcementCouponText}
        </span>
      )}
    </div>
  );

  useEffect(() => {
    const applyTopOffsetVar = (value: number) => {
      if (!headerRef.current) return;
      headerRef.current.style.setProperty("--ks-announcement-offset", `${Math.max(0, value)}px`);
    };
    if (!announcementStickyEnabled) {
      setAnnouncementStickyOffset(0);
      applyTopOffsetVar(0);
      return;
    }
    const measure = () => {
      const nextHeight = Math.round(announcementRef.current?.getBoundingClientRect().height || 0);
      setAnnouncementStickyOffset(nextHeight);
      applyTopOffsetVar(nextHeight);
    };
    measure();
    if (typeof ResizeObserver !== "undefined") {
      const observer = new ResizeObserver(() => measure());
      if (announcementRef.current) observer.observe(announcementRef.current);
      return () => observer.disconnect();
    }
    window.addEventListener("resize", measure);
    return () => window.removeEventListener("resize", measure);
  }, [announcementStickyEnabled, announcementTextResolved, announcementCouponText, announcementCountdownVisible, announcementButtonVisible, announcementBadgeVisible]);

  const scrollToProducts = () => {
    requestAnimationFrame(() => {
      productsSectionRef.current?.scrollIntoView({ behavior: "smooth", block: "start" });
    });
  };

  const heroCategories = rootCategories.slice(0, 6);

  /* Os itens do menu próprio, prontos (null = a lista de categorias de sempre). */
  const itensDoMenu = useMemo(
    () => (menuProprio && menuProprio.itens.length ? itensProntos(menuProprio.itens, { slug, categorias: categories, paginas: navegacao?.paginas }) : null),
    [menuProprio, slug, categories, navegacao?.paginas]
  );
  const regiaoDoRodape = marcaDeRegiao(noEditorDaNavegacao, "rodape");
  const propsDoRodapeProprio = (): PropsDoRodape | null => {
    if (!rodapeProprio) return null;
    return {
      regiao: regiaoDoRodape,
      paleta: footerPalette,
      nomeDaLoja: storeName,
      logoUrl,
      endereco: address,
      cnpj: catalogShowDocument !== false && cnpj ? cnpj : null,
      slogan: storeSlogan,
      sobre: rodapeProprio.sobre,
      colunas: rodapeProprio.colunas.map((coluna) => ({
        id: coluna.id,
        titulo: coluna.titulo,
        links: itensProntos(coluna.links, { slug, categorias: categories, paginas: navegacao?.paginas })
          .filter((link) => link.destino)
          .map((link) => ({ id: link.id, rotulo: link.rotulo, destino: link.destino! })),
      })),
      categorias: heroCategories.slice(0, 5).map((categoria) => ({ id: categoria.id, name: categoria.name, href: getCategoryHref(categoria) })),
      redes: socialLinks,
      whatsapp: bestWhatsappDigits || "",
      telefone: phoneDigits,
      mostrarContato: rodapeProprio.mostrar_contato,
      mostrarRedes: rodapeProprio.mostrar_redes,
      mostrarCategorias: rodapeProprio.mostrar_categorias,
    };
  };
  const heroProducts = filteredProducts.slice(0, 5);

  /* A caixa comum de toda seção (aparelho, fundo, espaço, agendada no
     editor, cliques): home/CaixaDaSecao. Sem nenhum ajuste, sai a seção
     sozinha, como sempre. Depois dela, a moldura do editor. */
  const vestirSecao = (section: CatalogSection, indice: number, desenhar: (secao: CatalogSection) => React.ReactNode) => {
    const conteudo = (
      <CaixaDaSecao key={section.id} secao={section} familia={catalogThemeId === "vitrine" ? "vitrine" : "padrao"} contarCliques={contarCliques}>
        {desenhar(semFundoDeSempre(section))}
      </CaixaDaSecao>
    );
    return envolverSecao ? envolverSecao(section, indice, conteudo) : conteudo;
  };

  const renderThemedSection = (section: CatalogSection, variant: "vitrine") => {
    if (ehSecaoNovaDaHome(section)) {
      return (
        <SecaoNovaDaHome key={section.id} secao={section} variante={variant} slug={slug} categorias={categories} corDaLoja={primaryPalette.base} produtos={products as never} />
      );
    }
    const sectionMode = resolveSectionMode(section);
    const sectionProducts = getSectionProducts(section);
    const categoryNavigatorItems = sectionMode === "category_navigator" ? getSectionCategoryNavigatorItems(section) : [];
    const viewMoreHref = getSectionViewMoreHref(section);
    const imageConfig = getSectionImageConfig(section);
    const visibleProducts =
      sectionMode === "all_products"
        ? sectionProducts.slice(0, quantosVisiveis(section.id))
        : expandedSectionIds.has(section.id)
          ? sectionProducts
          : sectionProducts.slice(0, 5);
    const hasMoreProducts = sectionProducts.length > visibleProducts.length;

    if (sectionMode === "image_banner" && imageConfig.imageUrl) {
      const bannerImage = (
        <Image
          src={imageConfig.imageUrl}
          alt={section.title || "Banner"}
          width={1920}
          height={560}
          className="w-full h-full object-cover"
          unoptimized
        />
      );

      return (
        <section key={section.id} className="mt-6 md:mt-10">
          <div className="mx-auto w-full">
            <div className="relative overflow-hidden rounded-none">
              {imageConfig.linkUrl ? (
                <Link href={imageConfig.linkUrl} target={imageConfig.openInNewTab ? "_blank" : undefined} rel={imageConfig.openInNewTab ? "noopener noreferrer" : undefined} className="block">
                  {bannerImage}
                </Link>
              ) : (
                bannerImage
              )}
            </div>
          </div>
        </section>
      );
    }

    return (
      <section
        key={section.id}
        id={sectionMode === "all_products" ? "produtos" : undefined}
        ref={sectionMode === "all_products" ? productsSectionRef : undefined}
        className="py-8 md:py-12 border-t border-gray-100 first:border-none"
        style={{ backgroundColor: section.background_color }}
      >
        <div className="mx-auto max-w-[1400px] px-4 md:px-8">
          <div className="flex flex-col gap-8">
            <div className="flex flex-col gap-3 md:flex-row md:items-end md:justify-between">
              <div className="max-w-3xl">
                {section.title ? (
                  <h2 className="font-semibold tracking-tight text-3xl" style={{ color: section.text_color }}>
                    {section.title}
                  </h2>
                ) : null}
              </div>
              {viewMoreHref ? (
                <Link
                  href={viewMoreHref}
                  className="inline-flex items-center gap-2 text-sm font-medium underline underline-offset-4 hover:opacity-80 transition-opacity"
                  style={{ color: section.text_color }}
                >
                  Ver todos
                </Link>
              ) : null}
            </div>

            {sectionMode === "category_navigator" && categoryNavigatorItems.length > 0 ? (
              <div className="grid grid-cols-2 gap-4 md:grid-cols-4 lg:grid-cols-6">
                {categoryNavigatorItems.map((item, idx) => (
                  <Link
                    key={idx}
                    href={item.finalSlug ? `/${slug}/c/${item.finalSlug}` : "#"}
                    onClick={() =>
                      trackCatalogInteraction({
                        eventName: "category_click",
                        categoryId: item.finalCategoryId || null,
                        sectionId: section.id,
                      })
                    }
                    className="group flex flex-col items-center gap-3"
                  >
                    <div className="relative w-full aspect-square overflow-hidden bg-gray-100 rounded-md">
                      {item.imageUrl ? (
                        <Image src={item.imageUrl} alt={item.label} fill className="object-cover transition-transform duration-500 group-hover:scale-105" unoptimized />
                      ) : (
                        <div className="flex h-full w-full items-center justify-center">
                          <ShoppingBag className="h-6 w-6 text-gray-300" />
                        </div>
                      )}
                    </div>
                    <span className="text-center font-medium text-base" style={{ color: section.text_color }}>
                      {item.label}
                    </span>
                  </Link>
                ))}
              </div>
            ) : (
              <>
                <div
                  className={`grid grid-cols-2 gap-4 md:gap-6 lg:grid-cols-4 xl:grid-cols-5 ${useVitrineMosaicLayout ? "grid-flow-row-dense" : ""}`}
                  style={useVitrineMosaicLayout ? { gridAutoRows: `${VITRINE_GRID_AUTO_ROW}px` } : undefined}
                >
                  {(
                    useVitrineMosaicLayout
                      ? buildVitrineCardVariants(visibleProducts)
                      : visibleProducts.map(() => "standard" as const)
                  ).map((cardVariant, index) => {
                    const product = visibleProducts[index];
                    const layoutClasses =
                      useVitrineMosaicLayout && cardVariant === "featuredEditorial"
                        ? "col-span-2 md:col-span-2"
                        : useVitrineMosaicLayout && cardVariant === "featuredCompact"
                          ? "md:col-span-2"
                          : "";
                    return renderStandardProductCard(
                      product,
                      section.id,
                      layoutClasses,
                      {
                        variant: cardVariant,
                        useVitrineMasonry: useVitrineMosaicLayout,
                      }
                    );
                  })}
                </div>

                {hasMoreProducts && (
                  <div className="mt-8 flex justify-center">
                    <button
                      onClick={() => (sectionMode === "all_products" ? mostrarMaisDaSecao(section.id) : toggleSectionExpansion(section.id))}
                      className="inline-flex items-center justify-center px-6 py-3 text-sm font-medium transition-colors rounded-md hover:opacity-90"
                      style={{ backgroundColor: primaryPalette.base, color: primaryPalette.text }}
                    >
                      Carregar mais produtos
                    </button>
                  </div>
                )}
              </>
            )}
          </div>
        </div>
      </section>
    );
  };

  const renderThemedHeroSlider = (variant: "vitrine") => {
    if (!slideEnabled || slideBanners.length === 0) return null;
    const frameClass = "relative overflow-hidden rounded-[18px] bg-gray-900 aspect-[21/9] md:aspect-[32/9] w-full";

    return (
      <div className={frameClass}>
        {slideBanners.map((banner, idx) => {
          const isActive = idx === activeBannerIndex;
          const linkType = banner.link_type || "none";
          const destino =
            linkType === "product" && banner.product_id
              ? { href: `/${slug}/p/${banner.product_id}`, externo: false }
              : linkType === "url"
                ? destinoDoLink(banner.link_url)
                : null;
          const href = destino?.href || "";
          const target = banner.open_in_new_tab ? "_blank" : undefined;
          const rel = banner.open_in_new_tab ? "noopener noreferrer" : undefined;
          const image = (
            <Image
              src={banner.image_url}
              alt=""
              className="w-full h-full object-cover"
              fill
              sizes="100vw"
              draggable={false}
              unoptimized
              priority={idx === 0}
            />
          );
          const content = href ? (
            destino?.externo ? (
              <a href={href} target={target} rel={rel} className="block w-full h-full">
                {image}
              </a>
            ) : (
              <Link href={href} target={target} rel={rel} className="block w-full h-full">
                {image}
              </Link>
            )
          ) : (
            image
          );

          return (
            <div
              key={banner.id}
              className={`absolute inset-0 transition-opacity duration-500 ${isActive ? "opacity-100" : "pointer-events-none opacity-0"}`}
            >
              {content}
              {/* Só enfeite: sem isto o escurecido ficava por cima do link e
                  engolia o clique do banner. */}
              <div className="pointer-events-none absolute inset-0 bg-gradient-to-t from-black/60 via-black/10 to-transparent" />
            </div>
          );
        })}

        <div className="absolute inset-x-0 bottom-4 flex justify-center gap-2">
          {slideBanners.length > 1 && slideBanners.map((_, idx) => (
            <button
              key={idx}
              type="button"
              onClick={() => setCurrentBanner(idx)}
              className={`h-2 transition-all rounded-full ${
                idx === activeBannerIndex ? "w-8 bg-white" : "w-2 bg-white/50 hover:bg-white/80"
              }`}
              aria-label={`Ir para o banner ${idx + 1}`}
            />
          ))}
        </div>
      </div>
    );
  };




  const renderVitrineHeader = () => (
    <header
      ref={headerRef}
      {...marcaDeRegiao(noEditorDaNavegacao, "cabecalho")}
      className={`relative ${cabecalhoFixo ? "md:sticky " : ""}top-0 z-50 ${!cabecalhoFixo || !announcementStickyEnabled ? "md:top-0" : "md:top-[var(--ks-announcement-offset)]"}`}
      style={{
        ["--ks-announcement-offset" as string]: "0px",
        backgroundColor: headerPalette.bg,
        color: headerPalette.text,
      }}
    >
      <div className="mx-auto max-w-[1400px] px-4 py-4 md:py-6">
        <div className="flex flex-wrap items-center justify-between gap-4 md:flex-nowrap">
          <div className="w-full md:hidden">
            <div className="relative flex min-h-[48px] items-center justify-center">
              <button
                type="button"
                onClick={() => setIsMobileCategoriesOpen(true)}
                className="absolute left-0 inline-flex h-10 w-10 shrink-0 items-center justify-center rounded"
                style={{ color: headerPalette.text, backgroundColor: withAlpha(headerPalette.text, 0.05) }}
              >
                <Menu size={20} />
              </button>
              <Link href={`/${slug}`} className="flex min-w-0 max-w-[78%] flex-col items-center justify-center text-center">
                {logoUrl ? (
                  <Image
                    src={logoUrl}
                    alt={storeName}
                    width={170}
                    height={54}
                    className={`h-10 w-auto max-w-full object-contain ${logoEffectClass}`}
                    style={{
                      "--ks-logo-effect-intensity": String(logoIntensityMultiplier),
                      "--ks-logo-effect-duration-rotate": `${(5.2 * logoSpeedDurationMultiplier).toFixed(2)}s`,
                      "--ks-logo-effect-duration-pulse": `${(3.2 * logoSpeedDurationMultiplier).toFixed(2)}s`,
                      "--ks-logo-effect-duration-blink": `${(2.4 * logoSpeedDurationMultiplier).toFixed(2)}s`,
                    } as CSSProperties}
                    unoptimized
                  />
                ) : (
                  <div className="min-w-0 flex flex-col items-center">
                    {shouldShowStoreName ? (
                      <div className="truncate text-xl font-bold tracking-tight" style={{ color: headerNameTextColor }}>
                        {storeName}
                      </div>
                    ) : null}
                    {shouldShowStoreSlogan ? (
                      <span className="mt-0.5 block truncate text-[11px] font-medium" style={{ color: headerSloganTextColor }}>
                        {storeSlogan}
                      </span>
                    ) : null}
                  </div>
                )}
                {logoUrl && (shouldShowStoreName || shouldShowStoreSlogan) ? (
                  <div className="mt-1 min-w-0 flex flex-col items-center">
                    {shouldShowStoreName ? (
                      <span
                        className="block max-w-[220px] truncate text-[0.95rem] font-semibold leading-tight tracking-[-0.02em]"
                        style={{ color: headerNameTextColor }}
                      >
                        {storeName}
                      </span>
                    ) : null}
                    {shouldShowStoreSlogan ? (
                      <span
                        className="mt-0.5 block max-w-[220px] truncate text-[11px] font-medium leading-tight"
                        style={{ color: headerSloganTextColor }}
                      >
                        {storeSlogan}
                      </span>
                    ) : null}
                  </div>
                ) : null}
              </Link>
            </div>

            <div className={`mt-3 grid ${mostrarBusca ? "grid-cols-3" : "grid-cols-2"} gap-2`}>
              {mostrarBusca ? (
              <button
                type="button"
                onClick={() => setIsMobileSearchOpen(true)}
                className="inline-flex h-11 w-full items-center justify-center rounded-lg"
                style={{ color: headerPalette.text, backgroundColor: withAlpha(headerPalette.text, 0.05) }}
              >
                <Search size={19} />
              </button>
              ) : null}

              <Link
                href={`/${slug}/cliente${loggedClient ? "" : "/login"}`}
                className="inline-flex h-11 w-full items-center justify-center rounded-lg"
                style={{ color: headerPalette.text, backgroundColor: withAlpha(headerPalette.text, 0.05) }}
              >
                {loggedClient?.avatar_url ? (
                  <Image src={loggedClient.avatar_url} alt={loggedClient.name} width={22} height={22} className="rounded-full object-cover" unoptimized />
                ) : (
                  <UserCircle2 size={19} />
                )}
              </Link>

              <div
                className="flex h-11 w-full items-center justify-center rounded-lg"
                style={{ backgroundColor: withAlpha(headerPalette.text, 0.05), color: headerPalette.text }}
              >
                <div className="scale-95">
                  <CartTrigger
                    primaryColor={primaryPalette.base}
                    iconColor={headerPalette.text}
                    badgeBackgroundColor={primaryPalette.badgeBg}
                    badgeTextColor={primaryPalette.badgeText}
                    hoverBackgroundColor="transparent"
                    surfaceColor="transparent"
                  />
                </div>
              </div>
            </div>
          </div>

          <div className="hidden w-full items-center gap-3 md:flex md:w-auto">
            <Link href={`/${slug}`} className="flex min-w-0 items-center gap-3 flex-1 md:flex-none">
              {logoUrl ? (
                <div className="flex min-w-0 items-center gap-3">
                  <Image 
                    src={logoUrl} 
                    alt={storeName} 
                    width={160} 
                    height={50} 
                    className={`h-10 object-contain ${tamanhoDaLogo === "pequeno" ? "md:h-10 w-auto" : tamanhoDaLogo === "grande" ? "md:h-16 w-auto" : "md:h-12"} ${logoEffectClass}`}
                    style={{
                      "--ks-logo-effect-intensity": String(logoIntensityMultiplier),
                      "--ks-logo-effect-duration-rotate": `${(5.2 * logoSpeedDurationMultiplier).toFixed(2)}s`,
                      "--ks-logo-effect-duration-pulse": `${(3.2 * logoSpeedDurationMultiplier).toFixed(2)}s`,
                      "--ks-logo-effect-duration-blink": `${(2.4 * logoSpeedDurationMultiplier).toFixed(2)}s`,
                    } as CSSProperties}
                    unoptimized 
                  />
                  {(shouldShowStoreName || shouldShowStoreSlogan) ? (
                    <div className="min-w-0 flex flex-col">
                      {shouldShowStoreName ? (
                        <span
                          className="block truncate text-[1rem] font-semibold leading-tight tracking-[-0.02em] md:text-[1.08rem]"
                          style={{ color: headerNameTextColor }}
                        >
                          {storeName}
                        </span>
                      ) : null}
                      {shouldShowStoreSlogan ? (
                        <span
                          className="mt-0.5 block truncate text-[11px] font-medium leading-tight md:text-[12px]"
                          style={{ color: headerSloganTextColor }}
                        >
                          {storeSlogan}
                        </span>
                      ) : null}
                    </div>
                  ) : null}
                </div>
              ) : (
                <div className="min-w-0 flex flex-col">
                  {shouldShowStoreName ? (
                    <div className="truncate text-xl font-bold tracking-tight md:text-2xl" style={{ color: headerNameTextColor }}>
                      {storeName}
                    </div>
                  ) : null}
                  {shouldShowStoreSlogan ? (
                    <span className="mt-0.5 block truncate text-[11px] font-medium md:text-[12px]" style={{ color: headerSloganTextColor }}>
                      {storeSlogan}
                    </span>
                  ) : null}
                </div>
              )}
            </Link>
          </div>

          {mostrarBusca ? (
          <div className="relative hidden w-full max-w-xl md:block">
            <div
              className="flex items-center gap-2 rounded px-4 py-2.5"
              style={{
                backgroundColor: headerPalette.searchBg || "#ffffff",
                border: `1px solid ${headerPalette.searchBorder || "#e2e8f0"}`,
                boxShadow: `0 1px 2px ${withAlpha(headerPalette.searchBorder || "#e2e8f0", 0.18)}`,
                color: headerPalette.searchText || "#1e293b",
              }}
            >
              <Search size={18} style={{ color: headerPalette.searchIcon || headerPalette.searchText || "#94a3b8" }} />
              <input
                type="text"
                placeholder="O que você está procurando?"
                value={searchTerm}
                onChange={(e) => {
                  setSearchTerm(e.target.value);
                  setIsSearchSuggestionsOpen(Boolean(e.target.value.trim()));
                }}
                onFocus={() => setIsSearchSuggestionsOpen(Boolean(normalizedSearchTerm))}
                onKeyDown={(event) => handleSearchInputKeyDown(event)}
                className="w-full bg-transparent text-sm outline-none"
                style={{
                  color: headerPalette.searchText || "#1e293b",
                }}
              />
            </div>
            {renderSearchSuggestions()}
          </div>
          ) : null}

          <div className="hidden md:flex items-center gap-4">
            {loggedClient ? (
              <Link href={`/${slug}/cliente?section=favorites`} className="flex flex-col items-center gap-1 hover:opacity-80 transition-opacity" style={{ color: headerPalette.text }}>
                <Heart size={20} />
                <span className="text-[10px] font-medium">Favoritos</span>
              </Link>
            ) : (
              <button type="button" onClick={() => openAuthModal({ type: "favorites_header" })} className="flex flex-col items-center gap-1 hover:opacity-80 transition-opacity" style={{ color: headerPalette.text }}>
                <Heart size={20} />
                <span className="text-[10px] font-medium">Favoritos</span>
              </button>
            )}
            
            {loggedClient ? (
              <div className="flex items-center gap-2.5" style={{ color: headerPalette.text }}>
                <Link
                  href={`/${slug}/cliente`}
                  className="hover:opacity-80 transition-opacity shrink-0"
                  aria-label="Abrir portal do cliente"
                  title="Minha conta"
                >
                  {loggedClient.avatar_url ? (
                    <Image src={loggedClient.avatar_url} alt={loggedClient.name} width={28} height={28} className="h-7 w-7 rounded-full object-cover bg-white/20" unoptimized />
                  ) : (
                    <UserCircle2 size={24} />
                  )}
                </Link>
                <div className="flex flex-col items-start justify-center">
                  <span className="text-[11px] font-medium leading-[1.2] opacity-80 whitespace-nowrap">Olá,</span>
                  <Link
                    href={`/${slug}/cliente`}
                    className="max-w-[92px] truncate text-[13px] font-bold leading-[1.15] whitespace-nowrap hover:opacity-80 transition-opacity"
                    title="Abrir portal do cliente"
                  >
                    {loggedClientFirstName}
                  </Link>
                  <button
                    onClick={handleLogout}
                    className="text-[11px] font-semibold underline underline-offset-2 hover:opacity-70 transition-opacity leading-none mt-[1px]"
                    title="Sair da conta"
                    type="button"
                  >
                    Sair
                  </button>
                </div>
              </div>
            ) : (
              <Link href={`/${slug}/cliente/login`} className="flex flex-col items-center gap-1 hover:opacity-80 transition-opacity" style={{ color: headerPalette.text }}>
                <UserCircle2 size={20} />
                <span className="text-[10px] font-medium">Entrar</span>
              </Link>
            )}

            <div className="ml-2 inline-flex h-12 items-center justify-center rounded px-3">
              <CartTrigger
                primaryColor={primaryPalette.base}
                iconColor={headerPalette.text}
                badgeBackgroundColor={primaryPalette.badgeBg}
                badgeTextColor={primaryPalette.badgeText}
                hoverBackgroundColor="transparent"
                surfaceColor={headerPalette.bg}
              />
            </div>
          </div>
        </div>
      </div>
      {heroCategories.length > 0 || itensDoMenu ? (
        <div style={{ backgroundColor: headerPalette.menuBg || headerPalette.bg, color: headerPalette.menuText || headerPalette.text, opacity: 0.98, borderTop: `1px solid ${withAlpha(headerPalette.menuText || headerPalette.text, 0.1)}` }} className="relative z-40">
          <div className="mx-auto flex max-w-[1400px] gap-6 overflow-x-auto md:overflow-visible px-4 py-3 scrollbar-hide items-center h-[52px]">
            <Link href={`/${slug}`} className="shrink-0 font-medium hover:opacity-70 transition-opacity" style={{ color: headerPalette.menuText || headerPalette.text }} aria-label="Início">
              <Home size={18} />
            </Link>
            
            {mostrarTodasAsCategorias ? (
            <div 
              className="shrink-0 relative h-full flex items-center min-w-max"
              onMouseEnter={() => {
                cancelDesktopSubmenuClose();
                openMegaMenu();
                if (!activeMegaMenuCategory && rootCategories.length > 0) {
                  const activeRoot = rootCategories.find(c => isCategoryActive(c.id));
                  setActiveMegaMenuCategory(activeRoot?.id || rootCategories[0].id);
                }
              }}
              onMouseLeave={() => {
                scheduleMegaMenuClose();
              }}
            >
              <button 
                type="button" 
                onClick={() => {
                  if (window.innerWidth < 768) {
                    setIsMobileCategoriesOpen(true);
                  } else {
                    scrollToProducts();
                  }
                }} 
                className="text-sm font-medium hover:opacity-70 transition-opacity flex items-center gap-1.5 h-full" 
                style={{ color: headerPalette.menuText || headerPalette.text }}
                aria-expanded={isDesktopCategoriesOpen}
              >
                Todos os Produtos
                <span className="hidden md:flex">
                  {isDesktopCategoriesOpen ? <ChevronUp size={14} className="opacity-70" /> : <ChevronDown size={14} className="opacity-70 transition-transform" />}
                </span>
                <ChevronDown size={14} className="opacity-70 transition-transform md:hidden" />
              </button>
              
              {/* Invisible hover bridge to prevent mega menu closing */}
              {isDesktopCategoriesOpen && (
                <div 
                  className="absolute top-full left-0 w-[800px] h-[10px] bg-transparent z-[60]" 
                  onMouseEnter={() => {
                    openMegaMenu();
                  }}
                />
              )}

              {/* Mega Menu Dropdown */}
              {isDesktopCategoriesOpen && (
                <div 
                  className="hidden absolute top-[calc(100%+8px)] left-0 w-[800px] h-[450px] bg-white rounded-xl shadow-[0_20px_60px_rgba(15,23,42,0.15)] border border-gray-100 md:flex overflow-hidden z-[60]"
                  style={{ 
                    backgroundColor: headerPalette.menuBg || headerPalette.bg,
                    borderColor: withAlpha(headerPalette.menuText || headerPalette.text, 0.1)
                  }}
                  onMouseEnter={() => {
                    openMegaMenu();
                  }}
                  onMouseLeave={() => {
                    scheduleMegaMenuClose();
                  }}
                >
                  {/* Left Column - Root Categories */}
                  <div className="w-[280px] overflow-y-auto py-3 border-r" style={{ backgroundColor: withAlpha(headerPalette.menuText || headerPalette.text, 0.03), borderColor: withAlpha(headerPalette.menuText || headerPalette.text, 0.1) }}>
                    {rootCategories.map(category => {
                      const isActive = activeMegaMenuCategory === category.id;
                      return (
                        <div 
                          key={category.id}
                          onMouseEnter={() => setActiveMegaMenuCategory(category.id)}
                          className="px-3 py-0.5"
                        >
                          <Link
                            href={getCategoryHref(category)}
                            onClick={() => {
                              closeCategoryMenus();
                              setLocalSelectedCategory(category.id);
                            }}
                            className={`block px-4 py-3 rounded-lg text-[14px] transition-all ${
                              isActive
                                ? "font-bold shadow-[0_1px_3px_rgba(0,0,0,0.05)] ring-1 ring-black/5" 
                                : "font-medium"
                            }`}
                            style={{
                              color: headerPalette.menuText || headerPalette.text,
                              backgroundColor: isActive ? (headerPalette.menuBg || headerPalette.bg) : "transparent",
                              opacity: isActive ? 1 : 0.8
                            }}
                          >
                            {category.name}
                          </Link>
                        </div>
                      );
                    })}
                  </div>

                  {/* Right Column - Subcategories */}
                  <div className="flex-1 p-8 overflow-y-auto" style={{ backgroundColor: headerPalette.menuBg || headerPalette.bg }}>
                    {(() => {
                      const activeCategory = rootCategories.find(c => c.id === activeMegaMenuCategory);
                      if (!activeCategory) return null;
                      const subs = subcategoriesByParent.get(activeCategory.id) || [];
                      
                      if (subs.length === 0) {
                        return (
                          <div className="h-full flex items-center justify-center text-sm font-medium opacity-50" style={{ color: headerPalette.menuText || headerPalette.text }}>
                            Sem subcategorias
                          </div>
                        );
                      }

                      return (
                        <div className="grid grid-cols-2 gap-x-8 gap-y-4 content-start">
                          {subs.map(sub => (
                            <Link
                              key={sub.id}
                              href={getCategoryHref(sub)}
                              onClick={() => {
                                closeCategoryMenus();
                                setLocalSelectedCategory(sub.id);
                              }}
                              className="text-[14px] transition-colors font-medium hover:underline underline-offset-4"
                              style={{
                                color: headerPalette.menuText || headerPalette.text,
                                opacity: selectedCategory === sub.id ? 1 : 0.8
                              }}
                            >
                              {sub.name}
                            </Link>
                          ))}
                        </div>
                      );
                    })()}
                  </div>
                </div>
              )}
            </div>
            ) : null}

            {itensDoMenu ? (
              <ItensDoMenuNaFaixa
                itens={itensDoMenu}
                variante="vitrine"
                corDaMarca={primaryPalette.base}
                corDoTextoNaMarca={primaryPalette.text}
                corDoTexto={headerPalette.menuText || headerPalette.text}
                fundoDaLista={headerPalette.menuBg || headerPalette.bg}
              />
            ) : heroCategories.map((category) => {
              const isActive = selectedCategory === category.id || activeMegaMenuCategory === category.id;
              return (
                <Link 
                  key={category.id} 
                  href={getCategoryHref(category)} 
                  className={`shrink-0 text-sm hover:opacity-100 transition-opacity py-1 ${isActive ? "font-bold" : "font-medium opacity-70"}`} 
                  style={{ 
                    color: headerPalette.menuText || headerPalette.text,
                    borderBottom: isActive ? `2px solid ${headerPalette.menuText || headerPalette.text}` : "2px solid transparent"
                  }}
                >
                  {category.name}
                </Link>
              );
            })}
          </div>
        </div>
      ) : null}
    </header>
  );

  const renderVitrineContent = () => {
    const isHome = !isSearchResultsPage && (selectedCategory === "all" || !selectedCategory);
    const vitrineResultsTitle = isSearchResultsPage
      ? `Resultados para "${appliedSearchTerm}"`
      : selectedCategory === "all"
        ? "Todos os Produtos"
        : categoryById.get(selectedCategory)?.name || "";
    const vitrineResultsHint = isSearchResultsPage
      ? `${filteredProducts.length} resultado${filteredProducts.length === 1 ? "" : "s"} encontrado${filteredProducts.length === 1 ? "" : "s"}`
      : `${filteredProducts.length} produtos encontrados`;
    const vitrineEmptyHint = isSearchResultsPage ? "Tente buscar com outro termo." : "Tente buscar em outra categoria.";
    
    return (
    <>
      {isHome && (
        <>
          <div className="bg-transparent">
            <div className="mx-auto max-w-[1400px] px-4 pt-10 pb-2 md:pt-14 md:pb-4">
              {slideBanners.length > 0 && (
                <div className="mb-8 md:mb-12">
                  {renderThemedHeroSlider("vitrine")}
                </div>
              )}
              <CatalogInfoStripMobile
                items={vitrineInfoStripItems.map((item) => ({
                  title: item.title,
                  subtitle: item.subtitle,
                  Icon: infoIconMap[item.icon] ?? Truck,
                }))}
                accentColor={primaryPalette.onWhiteSurface}
                tintColor={withAlpha(primaryPalette.base, 0.16)}
                borderColor={withAlpha(primaryPalette.base, 0.28)}
              />

              <div className="hidden md:grid md:grid-cols-3 gap-4 lg:gap-6">
                {vitrineInfoStripItems.map((item, index) => {
                  const Icon = infoIconMap[item.icon] ?? Truck;
                  return (
                    <div
                      key={`${item.title}-${index}`}
                      className="group relative flex items-center gap-4 overflow-hidden rounded-xl border p-5 transition-all hover:-translate-y-0.5 hover:shadow-[0_8px_24px_-18px_rgba(15,23,42,0.28)] hover:bg-[var(--info-hover-bg)] hover:border-[var(--info-hover-border)]"
                      style={{
                        ["--info-hover-bg" as string]: withAlpha(primaryPalette.base, 0.04),
                        ["--info-hover-border" as string]: withAlpha(primaryPalette.base, 0.14),
                        backgroundColor: primaryPalette.base,
                        borderColor: primaryPalette.base,
                      }}
                    >
                      <div className="pointer-events-none absolute -right-5 top-1/2 -translate-y-1/2 opacity-[0.14] transition-opacity duration-300 group-hover:opacity-[0.22]">
                        <Icon size={90} style={{ color: primaryPalette.text, transform: "rotate(35deg)" }} />
                      </div>
                      <div
                        className="relative z-10 flex h-12 w-12 shrink-0 items-center justify-center rounded-lg transition-colors"
                        style={{
                          backgroundColor: withAlpha("#FFFFFF", 0.16),
                          color: primaryPalette.text,
                        }}
                      >
                        <Icon size={20} />
                      </div>
                      <div className="relative z-10 min-w-0 flex-1">
                        <h3 className="text-[14px] font-semibold tracking-tight transition-colors group-hover:text-[var(--info-hover-text)]" style={{ color: primaryPalette.text, ["--info-hover-text" as string]: primaryPalette.onWhiteSurface }}>
                          {item.title}
                        </h3>
                        <p
                          className="mt-0.5 text-[13px] transition-colors group-hover:text-[var(--info-hover-subtext)]"
                          style={{
                            color: withAlpha(primaryPalette.text, 0.82),
                            ["--info-hover-subtext" as string]: withAlpha(primaryPalette.onWhiteSurface, 0.72),
                          }}
                        >
                          {item.subtitle}
                        </p>
                      </div>
                    </div>
                  );
                })}
              </div>
            </div>
          </div>
        </>
      )}

      {!isHome && (
        <div className="bg-white border-b border-gray-100 py-4 px-4">
          <div className="mx-auto max-w-[1400px] flex items-center gap-2 text-sm text-gray-500">
            <Link href={`/${slug}`} onClick={() => setLocalSelectedCategory("all")} className="hover:text-gray-900 transition-colors">Home</Link>
            <span className="opacity-50">/</span>
            {(() => {
              const category = categoryById.get(selectedCategory);
              if (!category) return null;
              
              const parentId = category.parent_id;
              const parent = parentId ? categoryById.get(parentId) : null;
              
              return (
                <>
                  {parent && (
                    <>
                      <Link href={`/${slug}/c/${parent.slug}`} onClick={() => setLocalSelectedCategory(parent.id)} className="hover:text-gray-900 transition-colors">{parent.name}</Link>
                      <span className="opacity-50">/</span>
                    </>
                  )}
                  <span className="font-medium text-gray-900">{category.name}</span>
                </>
              );
            })()}
          </div>
        </div>
      )}

      <div className="bg-white">
        {!isHome ? (
          <div className="mx-auto max-w-[1400px] px-4 py-6 md:py-8">
            <div className="md:hidden">
              <main className="space-y-5">
                <div
                  className="-mx-4 sticky z-40 border-b px-4 py-3 backdrop-blur"
                  style={{
                    top: `${Math.max(0, announcementStickyOffset)}px`,
                    backgroundColor: withAlpha("#FFFFFF", 0.94),
                    borderColor: withAlpha(primaryPalette.base, 0.12),
                  }}
                >
                  <div className="grid grid-cols-2 gap-3">
                  <div className="relative">
                    <button
                      type="button"
                      onClick={() => {
                        setIsVitrineMobileFiltersOpen((prev) => !prev);
                        setIsVitrineMobileCategoriesMenuOpen(false);
                      }}
                      className="flex h-11 w-full items-center justify-center gap-2 rounded-xl border px-3 text-[13px] font-semibold shadow-[0_10px_24px_rgba(15,23,42,0.05)]"
                      style={{
                        borderColor: withAlpha(primaryPalette.base, 0.18),
                        backgroundColor: withAlpha(primaryPalette.base, 0.06),
                        color: primaryPalette.onWhiteSurface,
                      }}
                    >
                      <DollarSign size={16} style={{ color: primaryPalette.base }} />
                      <span className="whitespace-nowrap">Ordenação por preço</span>
                    </button>

                    {isVitrineMobileFiltersOpen ? (
                      <div
                        className="absolute left-0 top-[calc(100%+10px)] z-20 w-[calc(100vw-2rem)] rounded-[24px] border bg-white p-4 shadow-[0_22px_50px_rgba(15,23,42,0.14)]"
                        style={{
                          borderColor: withAlpha(primaryPalette.base, 0.16),
                          backgroundColor: "#FFFFFF",
                        }}
                      >
                        <div className="space-y-4">
                          <div>
                            <label className="mb-2 block text-sm font-medium" style={{ color: primaryPalette.onWhiteSurface }}>Ordenar por</label>
                            <select
                              value={sortOrder}
                              onChange={(e) => setSortOrder(e.target.value)}
                              className="h-11 w-full rounded-xl border bg-white px-3 text-sm outline-none"
                              style={{
                                borderColor: withAlpha(primaryPalette.base, 0.16),
                                color: primaryPalette.onWhiteSurface,
                                boxShadow: `0 0 0 0 ${withAlpha(primaryPalette.base, 0)}`,
                              }}
                            >
                              <option value="relevance">Relevância</option>
                              {visao.mostrarPreco ? <option value="price_asc">Menor Preço</option> : null}
                              {visao.mostrarPreco ? <option value="price_desc">Maior Preço</option> : null}
                              <option value="name_asc">A a Z</option>
                              <option value="name_desc">Z a A</option>
                            </select>
                          </div>

                          {visao.mostrarPreco ? (
                          <div>
                            <label className="mb-2 block text-sm font-medium" style={{ color: primaryPalette.onWhiteSurface }}>Faixa de Preço</label>
                            <div className="mt-2 flex items-center gap-2">
                              <div className="relative flex-1">
                                <span className="absolute left-3 top-1/2 -translate-y-1/2 text-sm text-gray-500">R$</span>
                                <input
                                  type="text"
                                  inputMode="decimal"
                                  value={priceFilterDraft.min}
                                  onChange={(e) => handlePriceInputChange("min", e.target.value)}
                                  placeholder="Mín"
                                  className="h-11 w-full rounded-xl border pl-8 pr-3 text-sm outline-none"
                                  style={{ borderColor: withAlpha(primaryPalette.base, 0.16) }}
                                  disabled={!priceBounds.hasRange}
                                />
                              </div>
                              <span className="text-gray-400">-</span>
                              <div className="relative flex-1">
                                <span className="absolute left-3 top-1/2 -translate-y-1/2 text-sm text-gray-500">R$</span>
                                <input
                                  type="text"
                                  inputMode="decimal"
                                  value={priceFilterDraft.max}
                                  onChange={(e) => handlePriceInputChange("max", e.target.value)}
                                  placeholder="Máx"
                                  className="h-11 w-full rounded-xl border pl-8 pr-3 text-sm outline-none"
                                  style={{ borderColor: withAlpha(primaryPalette.base, 0.16) }}
                                  disabled={!priceBounds.hasRange}
                                />
                              </div>
                            </div>
                          </div>
                          ) : null}

                          <div className="flex flex-col gap-2">
                            <button
                              type="button"
                              onClick={() => {
                                applyPriceFilterDraft();
                                setIsVitrineMobileFiltersOpen(false);
                              }}
                              className="h-11 w-full rounded-xl text-sm font-bold transition-colors"
                              style={{ backgroundColor: primaryPalette.base, color: primaryPalette.text }}
                            >
                              Aplicar filtro
                            </button>
                            {activeFilterCount > 0 ? (
                              <button
                                type="button"
                                onClick={() => {
                                  resetCatalogFilters();
                                  setIsVitrineMobileFiltersOpen(false);
                                }}
                                className="h-11 w-full rounded-xl border border-gray-200 bg-white text-sm font-semibold text-gray-700"
                              >
                                Limpar filtros
                              </button>
                            ) : null}
                          </div>
                        </div>
                      </div>
                    ) : null}
                  </div>

                  <div className="relative">
                    <button
                      type="button"
                      onClick={() => {
                        setIsVitrineMobileCategoriesMenuOpen((prev) => !prev);
                        setIsVitrineMobileFiltersOpen(false);
                      }}
                      className="flex h-11 w-full items-center justify-center gap-2 rounded-xl border px-3 text-[13px] font-semibold shadow-[0_10px_24px_rgba(15,23,42,0.05)]"
                      style={{
                        borderColor: withAlpha(primaryPalette.base, 0.18),
                        backgroundColor: withAlpha(primaryPalette.base, 0.06),
                        color: primaryPalette.onWhiteSurface,
                      }}
                    >
                      <LayoutGrid size={16} style={{ color: primaryPalette.base }} />
                      <span className="whitespace-nowrap">Categorias</span>
                    </button>

                    {isVitrineMobileCategoriesMenuOpen ? (
                      <div
                        className="absolute right-0 top-[calc(100%+10px)] z-20 max-h-[60vh] w-[calc(100vw-2rem)] overflow-y-auto rounded-[24px] border bg-white p-3 shadow-[0_22px_50px_rgba(15,23,42,0.14)]"
                        style={{ borderColor: withAlpha(primaryPalette.base, 0.16) }}
                      >
                        <div className="space-y-1">
                          <Link
                            href={`/${slug}`}
                            onClick={() => {
                              setLocalSelectedCategory("all");
                              setIsVitrineMobileCategoriesMenuOpen(false);
                            }}
                            className={`block rounded-xl px-3 py-2.5 text-sm transition-colors ${
                              selectedCategory === "all" ? "font-semibold" : "text-gray-700 hover:bg-gray-50"
                            }`}
                            style={
                              selectedCategory === "all"
                                ? { backgroundColor: withAlpha(primaryPalette.base, 0.1), color: primaryPalette.onWhiteSurface }
                                : undefined
                            }
                          >
                            Todos os Produtos
                          </Link>

                          {rootCategories.map((category) => {
                            const subs = subcategoriesByParent.get(category.id) || [];
                            const isParentActive = isCategoryActive(category.id);
                            return (
                              <div key={category.id} className="rounded-xl border border-transparent">
                                <Link
                                  href={getCategoryHref(category)}
                                  onClick={() => {
                                    setLocalSelectedCategory(category.id);
                                    setIsVitrineMobileCategoriesMenuOpen(false);
                                  }}
                                  className={`block rounded-xl px-3 py-2.5 text-sm transition-colors ${
                                    isParentActive ? "font-semibold" : "text-gray-700 hover:bg-gray-50"
                                  }`}
                                  style={
                                    isParentActive
                                      ? { backgroundColor: withAlpha(primaryPalette.base, 0.1), color: primaryPalette.onWhiteSurface }
                                      : undefined
                                  }
                                >
                                  {category.name}
                                </Link>

                                {isParentActive && subs.length > 0 ? (
                                  <div className="mt-1 space-y-1 pl-3">
                                    {subs.map((subcategory) => (
                                      <Link
                                        key={subcategory.id}
                                        href={getCategoryHref(subcategory)}
                                        onClick={() => {
                                          setLocalSelectedCategory(subcategory.id);
                                          setIsVitrineMobileCategoriesMenuOpen(false);
                                        }}
                                        className={`block rounded-lg px-3 py-2 text-[13px] transition-colors ${
                                          selectedCategory === subcategory.id
                                            ? "font-semibold"
                                            : "text-gray-600 hover:bg-gray-50"
                                        }`}
                                        style={
                                          selectedCategory === subcategory.id
                                            ? { backgroundColor: withAlpha(primaryPalette.base, 0.08), color: primaryPalette.onWhiteSurface }
                                            : undefined
                                        }
                                      >
                                        {subcategory.name}
                                      </Link>
                                    ))}
                                  </div>
                                ) : null}
                              </div>
                            );
                          })}
                        </div>
                      </div>
                    ) : null}
                  </div>
                </div>
                </div>

                <div>
                  <h1 className="text-2xl font-bold text-gray-900">
                    {vitrineResultsTitle}
                  </h1>
                  <p className="mt-1 text-sm text-gray-500">{vitrineResultsHint}</p>
                </div>

                {filteredProducts.length === 0 ? (
                  <div className="rounded-2xl border border-gray-100 bg-gray-50 px-6 py-14 text-center">
                    <div className="mb-4 inline-flex h-16 w-16 items-center justify-center rounded-full bg-white shadow-sm">
                      <Search className="text-gray-400" size={32} />
                    </div>
                    <h3 className="text-lg font-medium text-gray-900">Nenhum produto encontrado</h3>
                    <p className="mt-1 text-sm text-gray-500">{vitrineEmptyHint}</p>
                  </div>
                ) : (
                  <div className="grid grid-cols-2 gap-3">
                    {filteredProducts.map((product) => renderStandardProductCard(product, "__category_vitrine__", "h-full"))}
                  </div>
                )}
              </main>
            </div>

            <div className="hidden items-start gap-8 md:flex">
              {/* Sidebar */}
              <aside className="sticky top-24 w-64 shrink-0 space-y-8">
                <div>
                  <h3 className="mb-4 text-sm font-bold uppercase tracking-wider text-gray-900">Filtros</h3>

                  <div className="space-y-6">
                    <div>
                      <label className="mb-2 block text-sm font-medium text-gray-700">Ordenar por</label>
                      <select
                        value={sortOrder}
                        onChange={(e) => setSortOrder(e.target.value)}
                        className="h-10 w-full rounded-lg border border-gray-200 bg-white px-3 text-sm outline-none focus:border-black focus:ring-1 focus:ring-black"
                      >
                        <option value="relevance">Relevância</option>
                        {visao.mostrarPreco ? <option value="price_asc">Menor Preço</option> : null}
                        {visao.mostrarPreco ? <option value="price_desc">Maior Preço</option> : null}
                        <option value="name_asc">A a Z</option>
                        <option value="name_desc">Z a A</option>
                      </select>
                    </div>

                    {visao.mostrarPreco ? (
                    <div>
                      <label className="mb-2 block text-sm font-medium text-gray-700">Faixa de Preço</label>

                      <div className="mb-3 mt-2 flex items-center gap-2">
                        <div className="relative flex-1">
                          <span className="absolute left-3 top-1/2 -translate-y-1/2 text-sm text-gray-500">R$</span>
                          <input
                            type="text"
                            inputMode="decimal"
                            value={priceFilterDraft.min}
                            onChange={(e) => handlePriceInputChange("min", e.target.value)}
                            placeholder="Mín"
                            className="h-10 w-full rounded-lg border border-gray-200 pl-8 pr-3 text-sm outline-none focus:border-black focus:ring-1 focus:ring-black"
                            disabled={!priceBounds.hasRange}
                          />
                        </div>
                        <span className="text-gray-400">-</span>
                        <div className="relative flex-1">
                          <span className="absolute left-3 top-1/2 -translate-y-1/2 text-sm text-gray-500">R$</span>
                          <input
                            type="text"
                            inputMode="decimal"
                            value={priceFilterDraft.max}
                            onChange={(e) => handlePriceInputChange("max", e.target.value)}
                            placeholder="Máx"
                            className="h-10 w-full rounded-lg border border-gray-200 pl-8 pr-3 text-sm outline-none focus:border-black focus:ring-1 focus:ring-black"
                            disabled={!priceBounds.hasRange}
                          />
                        </div>
                      </div>

                      <button
                        type="button"
                        onClick={applyPriceFilterDraft}
                        className="h-10 w-full rounded-lg text-sm font-bold tracking-wide transition-colors"
                        style={{ backgroundColor: primaryPalette.base, color: primaryPalette.text }}
                      >
                        APLICAR FILTRO
                      </button>
                    </div>
                    ) : null}

                    {activeFilterCount > 0 && (
                      <button
                        type="button"
                        onClick={resetCatalogFilters}
                        className="mt-2 w-full text-center text-sm font-medium text-red-600 underline underline-offset-2 hover:text-red-700"
                      >
                        Limpar Filtros
                      </button>
                    )}
                  </div>
                </div>

                <div className="border-t border-gray-100 pt-8">
                  <h3 className="mb-4 text-lg font-bold text-gray-900">Categorias</h3>
                  <div className="space-y-1">
                    <Link
                      href={`/${slug}`}
                      onClick={() => setLocalSelectedCategory("all")}
                      className={`block w-full rounded-lg px-3 py-2 text-left text-sm transition-colors ${
                        selectedCategory === "all" ? "bg-gray-100 font-bold text-gray-900" : "text-gray-600 hover:bg-gray-50"
                      }`}
                    >
                      Todos os Produtos
                    </Link>
                    {rootCategories.map((category) => {
                      const isActive = selectedCategory === category.id;
                      const subs = subcategoriesByParent.get(category.id) || [];
                      const isParentActive = isActive || subs.some((sub) => sub.id === selectedCategory);

                      return (
                        <div key={category.id} className="space-y-1">
                          <Link
                            href={getCategoryHref(category)}
                            onClick={() => setLocalSelectedCategory(category.id)}
                            className={`block w-full rounded-lg px-3 py-2 text-left text-sm transition-colors ${
                              isActive ? "bg-gray-100 font-bold text-gray-900" : "text-gray-600 hover:bg-gray-50"
                            } ${isParentActive && !isActive ? "font-semibold text-gray-900" : ""}`}
                          >
                            {category.name}
                          </Link>
                          {isParentActive && subs.length > 0 && (
                            <div className="ml-4 mt-1 space-y-1 border-l-2 border-gray-100 pl-4">
                              {subs.map((sub) => (
                                <Link
                                  key={sub.id}
                                  href={getCategoryHref(sub)}
                                  onClick={() => setLocalSelectedCategory(sub.id)}
                                  className={`block w-full rounded-lg px-3 py-1.5 text-left text-sm transition-colors ${
                                    selectedCategory === sub.id ? "bg-gray-100 font-bold text-gray-900" : "text-gray-500 hover:bg-gray-50 hover:text-gray-900"
                                  }`}
                                >
                                  {sub.name}
                                </Link>
                              ))}
                            </div>
                          )}
                        </div>
                      );
                    })}
                  </div>
                </div>
              </aside>

              <main className="min-w-0 w-full flex-1">
                <div className="mb-6">
                  <h1 className="text-2xl font-bold text-gray-900">
                    {vitrineResultsTitle}
                  </h1>
                  <p className="mt-1 text-sm text-gray-500">{vitrineResultsHint}</p>
                </div>

                {filteredProducts.length === 0 ? (
                  <div className="rounded-2xl border border-gray-100 bg-gray-50 py-20 text-center">
                    <div className="mb-4 inline-flex h-16 w-16 items-center justify-center rounded-full bg-white shadow-sm">
                      <Search className="text-gray-400" size={32} />
                    </div>
                    <h3 className="text-lg font-medium text-gray-900">Nenhum produto encontrado</h3>
                    <p className="mt-1 text-gray-500">{vitrineEmptyHint}</p>
                  </div>
                ) : (
                  <div className="grid grid-cols-2 gap-4 md:grid-cols-3 lg:grid-cols-4">
                    {filteredProducts.map((product) => renderStandardProductCard(product, "__category_vitrine__", "h-full"))}
                  </div>
                )}
              </main>
            </div>
          </div>
        ) : (
          sortedSections.map((section, indice) => vestirSecao(section, indice, (s) => renderThemedSection(s, "vitrine")))
        )}
      </div>
    </>
  )};

  /* A página extra no Vitrine: a trilha e o título, e as seções dela. */
  const renderVitrinePaginaExtra = () => (
    <>
      {paginaExtra?.mostrarTitulo ? (
        <>
          <div className="bg-white border-b border-gray-100 py-4 px-4">
            <div className="mx-auto max-w-[1400px] flex items-center gap-2 text-sm text-gray-500">
              <Link href={`/${slug}`} className="hover:text-gray-900 transition-colors">Home</Link>
              <span className="opacity-50">/</span>
              <span className="font-medium text-gray-900">{paginaExtra.titulo}</span>
            </div>
          </div>
          <div className="bg-white">
            <div className="mx-auto max-w-[1400px] px-4 pt-8 pb-2 md:pt-10">
              <h1 className="text-2xl md:text-3xl font-bold tracking-tight text-gray-900">{paginaExtra.titulo}</h1>
            </div>
          </div>
        </>
      ) : null}
      <div className="bg-white">
        {sortedSections.length === 0 ? paginaExtra?.vazio : null}
        {sortedSections.map((section, indice) => vestirSecao(section, indice, (s) => renderThemedSection(s, "vitrine")))}
      </div>
    </>
  );

  const renderSearchResultsContent = () => (
    <div className="mx-auto w-full max-w-[1400px] px-4 py-8 md:py-10">
      <div className="mb-6 md:mb-8">
        <h1 className="text-2xl font-bold text-gray-900 md:text-3xl">{`Resultados para "${appliedSearchTerm}"`}</h1>
        <p className="mt-1 text-sm text-gray-500">
          {filteredProducts.length} resultado{filteredProducts.length === 1 ? "" : "s"} encontrado{filteredProducts.length === 1 ? "" : "s"}
        </p>
      </div>

      {filteredProducts.length === 0 ? (
        <div className="rounded-2xl border border-gray-100 bg-gray-50 px-6 py-14 text-center md:py-20">
          <div className="mb-4 inline-flex h-16 w-16 items-center justify-center rounded-full bg-white shadow-sm">
            <Search className="text-gray-400" size={32} />
          </div>
          <h3 className="text-lg font-medium text-gray-900">Nenhum produto encontrado</h3>
          <p className="mt-1 text-sm text-gray-500">Tente buscar com outro termo.</p>
        </div>
      ) : (
        <div className="grid grid-cols-2 gap-4 md:grid-cols-3 lg:grid-cols-4">
          {filteredProducts.map((product) => renderStandardProductCard(product, "__search_results__", "h-full"))}
        </div>
      )}
    </div>
  );

  const renderVitrineFooter = () => {
    const doRodapeProprio = propsDoRodapeProprio();
    if (doRodapeProprio) return <RodapeProprioVitrine {...doRodapeProprio} />;
    const currentFooterBg = footerPalette.bg;
    const currentFooterText = footerPalette.text;
    const currentFooterMuted = footerPalette.muted;
    const currentFooterSubtleBg = footerPalette.subtleBg;
    const currentFooterSubtleBgHover = footerPalette.subtleBgHover;

    return (
      <footer {...regiaoDoRodape} className="catalog-footer mt-auto pt-12 pb-24 md:py-16" style={{ backgroundColor: currentFooterBg, color: currentFooterText }}>
        <div className="mx-auto max-w-[1400px] px-4">
          <div className="grid gap-8 md:grid-cols-4">
            <div className="md:col-span-2 flex flex-col items-start">
              {logoUrl && (
                <img
                  src={logoUrl}
                  alt={storeName}
                  className="h-16 w-auto object-contain mb-4"
                />
              )}
              {!logoUrl && (
                <div className="mb-3 text-lg font-semibold" style={{ color: currentFooterText }}>
                  {storeName}
                </div>
              )}
              {address && (
                <div className="text-sm max-w-sm mb-2" style={{ color: currentFooterMuted }}>
                  {address}
                </div>
              )}
              {catalogShowDocument !== false && cnpj && (
                <div className="text-sm mb-4" style={{ color: currentFooterMuted }}>
                  CNPJ: {cnpj}
                </div>
              )}
              {storeSlogan && (
                <p className="max-w-sm text-sm" style={{ color: currentFooterMuted }}>
                  {storeSlogan}
                </p>
              )}

              {socialLinks.length > 0 && (
                <div className="mt-6 flex flex-wrap items-center gap-3">
                  {socialLinks.map(({ key, href, Icon }) => {
                    if (!Icon) return null;
                    return (
                      <a
                        key={`footer-social-${key}`}
                        href={href}
                        target="_blank"
                        rel="noopener noreferrer"
                        aria-label={`Siga-nos no ${key}`}
                        className="flex h-10 w-10 items-center justify-center rounded-full transition-all hover:scale-110"
                        style={{ backgroundColor: currentFooterSubtleBg, color: currentFooterText }}
                        onMouseEnter={(e) => { (e.currentTarget as HTMLAnchorElement).style.backgroundColor = currentFooterSubtleBgHover; }}
                        onMouseLeave={(e) => { (e.currentTarget as HTMLAnchorElement).style.backgroundColor = currentFooterSubtleBg; }}
                      >
                        <Icon className="w-5 h-5" />
                      </a>
                    );
                  })}
                </div>
              )}
            </div>
            <div>
              <h4 className="text-sm font-bold" style={{ color: currentFooterText }}>Categorias</h4>
              <div className="mt-4 space-y-3 text-sm" style={{ color: currentFooterMuted }}>
                {heroCategories.slice(0, 5).map((category) => (
                  <Link key={category.id} href={getCategoryHref(category)} className="block hover:opacity-100 transition-opacity">
                    {category.name}
                  </Link>
                ))}
              </div>
            </div>
            <div>
              <h4 className="text-sm font-bold" style={{ color: currentFooterText }}>Atendimento</h4>
              <div className="mt-4 flex gap-3 text-sm" style={{ color: currentFooterMuted }}>
                {bestWhatsappDigits && (
                  <a
                    href={`https://wa.me/${bestWhatsappDigits}`}
                    target="_blank"
                    rel="noopener noreferrer"
                    className="flex h-10 w-10 items-center justify-center rounded-full transition-all hover:scale-110"
                    style={{ backgroundColor: currentFooterSubtleBg, color: currentFooterText }}
                    onMouseEnter={(e) => { (e.currentTarget as HTMLAnchorElement).style.backgroundColor = currentFooterSubtleBgHover; }}
                    onMouseLeave={(e) => { (e.currentTarget as HTMLAnchorElement).style.backgroundColor = currentFooterSubtleBg; }}
                    aria-label="WhatsApp"
                  >
                    <MessageCircle className="w-5 h-5" />
                  </a>
                )}
                {phoneDigits && (
                  <a
                    href={`tel:${phoneDigits}`}
                    className="flex h-10 w-10 items-center justify-center rounded-full transition-all hover:scale-110"
                    style={{ backgroundColor: currentFooterSubtleBg, color: currentFooterText }}
                    onMouseEnter={(e) => { (e.currentTarget as HTMLAnchorElement).style.backgroundColor = currentFooterSubtleBgHover; }}
                    onMouseLeave={(e) => { (e.currentTarget as HTMLAnchorElement).style.backgroundColor = currentFooterSubtleBg; }}
                    aria-label="Telefone"
                  >
                    <Phone className="w-5 h-5" />
                  </a>
                )}
              </div>
            </div>
          </div>
          <div className="mt-12 border-t pt-8 flex flex-col md:flex-row items-center justify-between gap-4 text-sm" style={{ borderColor: footerPalette.divider, color: currentFooterMuted }}>
            <p>© {new Date().getFullYear()} {storeName}. Todos os direitos reservados.</p>
            <div className="flex items-center gap-1.5 text-xs">
              <span>Tecnologia</span>
              <Link
                href="https://ktalogu.com.br"
                target="_blank"
                rel="noopener noreferrer"
                aria-label="Ktalogu"
                className="font-bold px-2 py-0.5 rounded-full inline-flex items-center opacity-60 hover:opacity-100 transition-opacity"
                style={{ backgroundColor: footerPalette.chipBg }}
              >
                <Image
                  src="/brand-logo.svg"
                  alt="Ktalogu"
                  className="h-3.5 w-auto"
                  width={56}
                  height={14}
                  style={{
                    filter: footerPalette.isLightText
                      ? "brightness(0) invert(1) contrast(1.15)"
                      : "brightness(0) contrast(1.25)",
                  }}
                />
              </Link>
            </div>
          </div>
        </div>
      </footer>
    );
  };

  return (
    <div
      className={`catalog-shell min-h-screen bg-gray-50 font-sans flex flex-col${
        fontHeadingFamily ? " ks-catalog-typography" : ""
      }`}
      /*
        Estilo inline so entra quando existe escolha: sem isso o `bg-gray-50` e
        a fonte padrao continuam valendo e a loja fica identica ao que era.
      */
      style={{
        ...(pageBgColor ? { backgroundColor: pageBgColor } : {}),
        ...(fontBodyFamily
          ? ({
              fontFamily: fontBodyFamily,
              ["--ks-catalog-font-body" as string]: fontBodyFamily,
            } as Record<string, string>)
          : {}),
        ...(fontHeadingFamily
          ? ({ ["--ks-catalog-font-heading" as string]: fontHeadingFamily } as Record<string, string>)
          : {}),
      }}
    >
      <style jsx global>{`
        /* Titulos seguem a fonte escolhida; o resto herda a fonte do corpo
           aplicada na raiz. So vale quando a loja escolheu uma fonte. */
        .ks-catalog-typography h1,
        .ks-catalog-typography h2,
        .ks-catalog-typography h3,
        .ks-catalog-typography h4 {
          font-family: var(--ks-catalog-font-heading);
        }
        @keyframes ksLogoRotate3D {
          0% { transform: perspective(800px) rotateY(0deg) rotateX(0deg); }
          30% { transform: perspective(800px) rotateY(calc(-16deg * var(--ks-logo-effect-intensity, 1))) rotateX(calc(3deg * var(--ks-logo-effect-intensity, 1))); }
          60% { transform: perspective(800px) rotateY(calc(14deg * var(--ks-logo-effect-intensity, 1))) rotateX(calc(-3deg * var(--ks-logo-effect-intensity, 1))); }
          100% { transform: perspective(800px) rotateY(0deg) rotateX(0deg); }
        }
        @keyframes ksLogoPulse {
          0% { transform: scale(1); filter: drop-shadow(0 0 0 rgba(255,255,255,0)); }
          50% { transform: scale(calc(1 + 0.045 * var(--ks-logo-effect-intensity, 1))); filter: drop-shadow(0 0 calc(14px * var(--ks-logo-effect-intensity, 1)) rgba(255,255,255,0.42)); }
          100% { transform: scale(1); filter: drop-shadow(0 0 0 rgba(255,255,255,0)); }
        }
        @keyframes ksLogoBlink {
          0%, 100% { opacity: 1; filter: brightness(1); }
          45% { opacity: calc(1 - (0.25 * var(--ks-logo-effect-intensity, 1))); filter: brightness(calc(1 + (0.18 * var(--ks-logo-effect-intensity, 1)))); }
          55% { opacity: 1; filter: brightness(calc(1 + (0.05 * var(--ks-logo-effect-intensity, 1)))); }
        }
        @keyframes ksAnnouncementMarquee {
          0% { transform: translate3d(0, 0, 0); }
          100% { transform: translate3d(-50%, 0, 0); }
        }
        .ks-logo-effect-rotate3d { animation: ksLogoRotate3D var(--ks-logo-effect-duration-rotate, 5.2s) ease-in-out infinite; transform-style: preserve-3d; transform-origin: center center; }
        .ks-logo-effect-pulse { animation: ksLogoPulse var(--ks-logo-effect-duration-pulse, 3.2s) ease-in-out infinite; }
        .ks-logo-effect-blink { animation: ksLogoBlink var(--ks-logo-effect-duration-blink, 2.4s) ease-in-out infinite; }
        .ks-announcement-marquee-track { display: inline-flex; width: max-content; min-width: 100%; }
        .ks-announcement-marquee { animation: ksAnnouncementMarquee 24s linear infinite; will-change: transform; }
        @keyframes ksPremiumShine {
          0% { background-position: 200% center; }
          100% { background-position: -200% center; }
        }
        .ks-premium-button {
          background-size: 200% auto;
          animation: ksPremiumShine 4s linear infinite;
        }
        .ks-price-range-input {
          -webkit-appearance: none;
          appearance: none;
          background: transparent;
          pointer-events: none;
        }
        .ks-price-range-input::-webkit-slider-runnable-track {
          height: 24px;
          background: transparent;
        }
        .ks-price-range-input::-webkit-slider-thumb {
          -webkit-appearance: none;
          appearance: none;
          width: 18px;
          height: 18px;
          margin-top: 3px;
          border-radius: 9999px;
          border: 1px solid #d1d5db;
          background: #ffffff;
          box-shadow: 0 2px 8px rgba(15, 23, 42, 0.15);
          cursor: pointer;
          pointer-events: auto;
        }
        .ks-price-range-input::-moz-range-track {
          height: 24px;
          background: transparent;
        }
        .ks-price-range-input::-moz-range-thumb {
          width: 18px;
          height: 18px;
          border-radius: 9999px;
          border: 1px solid #d1d5db;
          background: #ffffff;
          box-shadow: 0 2px 8px rgba(15, 23, 42, 0.15);
          cursor: pointer;
          pointer-events: auto;
        }
      `}</style>
      {announcementVisible ? (
        <div
          ref={announcementRef}
          className={`catalog-announcement relative overflow-hidden ${announcementStickyEnabled ? "sticky top-0 z-[70]" : ""}`}
          style={{ backgroundColor: normalizedAnnouncementBackground, color: normalizedAnnouncementText }}
        >
          {/* Watermark Background */}
          {announcementHasCoupon && (
            <div className="absolute inset-0 pointer-events-none flex items-center justify-center opacity-10 overflow-hidden">
              <Percent size={140} className="text-white transform rotate-12" />
            </div>
          )}
          
          <div className="max-w-7xl mx-auto px-3 sm:px-5 py-1.5 relative z-10">
            <div className="flex flex-col gap-1.5 md:flex-row md:items-center md:justify-center md:gap-2.5">
              {/* Desktop View */}
              <div className="hidden md:flex min-w-0 items-center justify-center gap-2.5 text-center w-full">
                {renderAnnouncementDesktopFlowItems()}
                {announcementCountdownVisible && (
                  <div className="inline-flex shrink-0 items-center gap-1 ml-2" suppressHydrationWarning>
                    {announcementCountdownParts.map((part) => (
                      <span key={part.label} className="inline-flex items-center gap-0.5">
                        <span className="inline-flex h-8 w-8 items-center justify-center rounded-md border border-white/45 bg-white/14 text-[12px] font-bold tabular-nums shadow-[inset_0_1px_0_rgba(255,255,255,0.2)]">
                          {part.value}
                        </span>
                        <span className="text-[9px] font-semibold uppercase tracking-wide text-white/80">{part.label}</span>
                      </span>
                    ))}
                  </div>
                )}
                {announcementButtonVisible && (
                  <a
                    href={announcementButtonHref}
                    className="shrink-0 items-center rounded-full border border-white/30 bg-white/20 px-4 py-1.5 text-[11px] font-bold uppercase tracking-wide hover:bg-white/30 transition-colors ml-2"
                  >
                    {String(announcementButtonLabel || "").trim()}
                  </a>
                )}
              </div>
              
              {/* Mobile View - Rebuilt Layout */}
              <div className="md:hidden flex flex-col gap-2 w-full py-0.5">
                {/* Top Row: Icon + Marquee + Countdown */}
                <div className="flex items-center gap-2.5 w-full">
                  {announcementHasCoupon && (
                    <div className="shrink-0 flex items-center justify-center w-7 h-7 rounded-full bg-white/15 text-yellow-300 shadow-sm">
                      <Flame size={14} className="fill-yellow-400" />
                    </div>
                  )}
                  
                  <div className="flex-1 min-w-0 overflow-hidden relative" style={{ WebkitMaskImage: 'linear-gradient(90deg, transparent, #000 10%, #000 90%, transparent)' }}>
                    <div className={`ks-announcement-marquee-track ${announcementMarqueePaused ? "" : "ks-announcement-marquee"}`} style={{ animationPlayState: announcementMarqueePaused ? "paused" : "running" }}>
                      <div className="inline-flex items-center whitespace-nowrap pr-8">
                        {renderAnnouncementMobileTextItems()}
                      </div>
                      <div className="inline-flex items-center whitespace-nowrap pr-8">
                        {renderAnnouncementMobileTextItems()}
                      </div>
                    </div>
                  </div>
                  
                  {announcementCountdownVisible && (
                    <div className="inline-flex shrink-0 items-center gap-1" suppressHydrationWarning>
                      {announcementCountdownParts.map((part) => (
                        <div key={part.label} className="flex flex-col items-center">
                          <span className="inline-flex h-[26px] w-[26px] items-center justify-center rounded-[4px] border border-white/20 bg-black/20 text-[11px] font-bold tabular-nums shadow-inner">
                            {part.value}
                          </span>
                          <span className="text-[7px] font-bold uppercase mt-0.5 opacity-80">{part.label}</span>
                        </div>
                      ))}
                    </div>
                  )}
                </div>

                {/* Bottom Row: Ticket Coupon & Action Button */}
                <div className="flex items-center justify-between gap-2 w-full mt-0.5">
                  {announcementHasCoupon && announcementBadgeVisible ? (
                    <button
                      type="button"
                      onClick={handleCopyAnnouncementCoupon}
                      className="relative flex items-center shrink-0 rounded-md border-2 border-dashed p-1 overflow-hidden group active:scale-[0.97] transition-transform"
                      style={{ 
                        backgroundColor: normalizedAnnouncementBadgeBackground, 
                        color: normalizedAnnouncementBadgeText, 
                        borderColor: announcementBadgeBorder,
                        boxShadow: `0 4px 12px ${withAlpha(normalizedAnnouncementBadgeBackground, 0.2)}`
                      }}
                    >
                      <div className="absolute inset-0 bg-gradient-to-r from-white/0 via-white/30 to-white/0 translate-x-[-100%] group-hover:translate-x-[100%] transition-transform duration-1000" />
                      <div className="flex items-center gap-1.5 px-1.5 z-10 min-w-0" style={{ color: normalizedAnnouncementBadgeText }}>
                        <Tag size={12} className="opacity-80 shrink-0" />
                        <span className="font-extrabold text-[12px] tracking-widest truncate">{effectiveAnnouncementCoupon?.code}</span>
                      </div>
                      <div className="flex items-center justify-center z-10 bg-black/10 w-6 h-6 rounded-[4px] ml-1.5 shrink-0" style={{ color: normalizedAnnouncementBadgeText }}>
                        {announcementCouponCopied ? <Check size={12} /> : <Copy size={12} />}
                      </div>
                    </button>
                  ) : (
                    <div className="flex-1"></div>
                  )}

                  {announcementButtonVisible && (
                    <a
                      href={announcementButtonHref}
                      className="ks-premium-button shrink-0 inline-flex items-center gap-1 rounded-full border border-white/20 px-3.5 py-1.5 text-[9px] font-bold uppercase tracking-wide transition-all ml-auto shadow-sm relative overflow-hidden"
                      style={{ 
                        backgroundColor: 'rgba(255,255,255,0.15)',
                        backgroundImage: 'linear-gradient(90deg, rgba(255,255,255,0) 0%, rgba(255,255,255,0.3) 50%, rgba(255,255,255,0) 100%)',
                        backdropFilter: 'blur(4px)'
                      }}
                    >
                      <span className="relative z-10 drop-shadow-sm">{String(announcementButtonLabel || "Ver Ofertas").trim()}</span>
                      <ChevronRight size={12} className="relative z-10" />
                    </a>
                  )}
                </div>
              </div>
            </div>
          </div>
        </div>
      ) : null}
      {catalogThemeId === "default" ? (
      <header
        ref={headerRef}
        {...marcaDeRegiao(noEditorDaNavegacao, "cabecalho")}
        className={`catalog-header relative ${cabecalhoFixo ? "md:sticky " : ""}z-50 shadow-[0_10px_24px_rgba(15,23,42,0.18)] transition-all top-0 ${!cabecalhoFixo || !announcementStickyEnabled ? "md:top-0" : "md:top-[var(--ks-announcement-offset)]"}`}
        style={{ backgroundColor: primaryPalette.base, ["--ks-announcement-offset" as string]: "0px" }}
      >
        <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-4 md:py-3">
          <div className="flex flex-col md:flex-row md:items-center md:justify-between w-full">
            {/* Topo no Mobile: Logo na esquerda, Ações na Direita */}
            <div className="flex flex-col md:hidden w-full gap-3">
              <div className="flex items-center justify-between w-full">
                <div className="flex items-center gap-3 min-w-0 flex-1">
                  <button
                    type="button"
                    onClick={() => setIsMobileCategoriesOpen(true)}
                    className="flex items-center justify-center shrink-0"
                    style={{ color: primaryPalette.text }}
                  >
                    <Menu size={28} strokeWidth={2} />
                  </button>
                  {logoUrl ? (
                    <div className="h-10 w-auto max-w-[140px] flex items-center justify-start shrink-0">
                      <Image
                        src={logoUrl}
                        alt={storeName}
                        className={`max-h-full w-auto object-contain object-left ${logoEffectClass}`}
                        style={{
                          "--ks-logo-effect-intensity": String(logoIntensityMultiplier),
                          "--ks-logo-effect-duration-rotate": `${(5.2 * logoSpeedDurationMultiplier).toFixed(2)}s`,
                          "--ks-logo-effect-duration-pulse": `${(3.2 * logoSpeedDurationMultiplier).toFixed(2)}s`,
                          "--ks-logo-effect-duration-blink": `${(2.4 * logoSpeedDurationMultiplier).toFixed(2)}s`,
                        } as CSSProperties}
                        width={180}
                        height={40}
                        unoptimized
                      />
                    </div>
                  ) : (
                    <div className="h-8 w-8 flex items-center justify-center shrink-0">
                      <ShoppingBag size={24} strokeWidth={2} style={{ color: primaryPalette.text }} />
                    </div>
                  )}
                  {(!logoUrl && (shouldShowStoreName || shouldShowStoreSlogan)) && (
                    <div className="min-w-0 flex flex-col flex-1">
                      {shouldShowStoreName ? (
                        <span
                          className="block text-[1.1rem] font-extrabold tracking-tight leading-tight truncate"
                          style={{ color: headerNameTextColor }}
                        >
                          {storeName}
                        </span>
                      ) : null}
                    </div>
                  )}
                </div>

                {/* Ações Mobile */}
                <div className="flex items-center gap-3 shrink-0">
                  {loggedClient ? (
                    <Link
                      href={`/${slug}/cliente?section=favorites`}
                      className="flex items-center justify-center cursor-pointer"
                      style={{ color: primaryPalette.text }}
                      title="Meus Favoritos"
                    >
                      <Heart size={26} strokeWidth={1.9} />
                    </Link>
                  ) : (
                    <button
                      type="button"
                      onClick={() => openAuthModal({ type: "favorites_header" })}
                      className="flex items-center justify-center cursor-pointer hover:opacity-80 transition-opacity"
                      style={{ color: primaryPalette.text }}
                      title="Entrar para ver favoritos"
                    >
                      <Heart size={26} strokeWidth={1.9} />
                    </button>
                  )}
                  <div className="flex items-center justify-center cursor-pointer" style={{ color: primaryPalette.text }}>
                    <CartTrigger
                      primaryColor={primaryPalette.base}
                      iconColor={primaryPalette.text}
                      badgeBackgroundColor={primaryPalette.badgeBg}
                      badgeTextColor={primaryPalette.badgeText}
                      hoverBackgroundColor="transparent"
                      surfaceColor={primaryPalette.base}
                      iconSize={26}
                      iconStrokeWidth={1.9}
                    />
                  </div>
                  {loggedClient ? (
                    <div className="flex items-center gap-2 min-w-0" style={{ color: primaryPalette.text }}>
                      <Link
                        href={`/${slug}/cliente`}
                        className="shrink-0 hover:opacity-80 transition-opacity"
                        title="Minha conta"
                      >
                        {loggedClient.avatar_url ? (
                          <Image
                            src={loggedClient.avatar_url}
                            alt={loggedClient.name}
                            width={28}
                            height={28}
                            className="rounded-full object-cover shrink-0 bg-white/20 h-7 w-7"
                            unoptimized
                          />
                        ) : (
                          <UserCircle2 size={26} strokeWidth={1.9} />
                        )}
                      </Link>
                      <div className="flex min-w-0 flex-col items-start leading-none">
                        <Link
                          href={`/${slug}/cliente`}
                          className="max-w-[74px] truncate text-[11px] font-semibold hover:opacity-80 transition-opacity"
                          title="Abrir portal do cliente"
                        >
                          {loggedClientFirstName}
                        </Link>
                        <button
                          onClick={handleLogout}
                          className="mt-1 text-[10px] font-medium underline underline-offset-2 hover:opacity-70 transition-opacity"
                          title="Sair da conta"
                          type="button"
                        >
                          Sair
                        </button>
                      </div>
                    </div>
                  ) : (
                    <Link
                      href={`/${slug}/cliente/login`}
                      className="flex items-center justify-center cursor-pointer"
                      style={{ color: primaryPalette.text }}
                      title="Entrar / cadastrar"
                    >
                      <UserCircle2 size={26} strokeWidth={1.9} />
                    </Link>
                  )}
                </div>
              </div>

              {/* Busca Fixa Mobile */}
              {mostrarBusca ? (
              <div className="w-full">
                <div className="relative">
                  <input
                    type="text"
                    placeholder={`Busque na ${storeName}`}
                    value={searchTerm}
                    onChange={(e) => setSearchTerm(e.target.value)}
                    onKeyDown={(event) => handleSearchInputKeyDown(event, { closeMobileSearch: true })}
                    className="w-full pl-4 pr-11 py-3 rounded-xl border-none focus:ring-2 focus:ring-white/50 transition-all bg-white text-gray-800 placeholder-gray-400 text-[15px] shadow-sm"
                  />
                  <Search size={20} strokeWidth={2.5} className="absolute right-4 top-1/2 -translate-y-1/2 text-primary/70" style={{ color: primaryPalette.base }} />
                </div>
              </div>
              ) : null}
            </div>

            {/* Desktop Layout Original (Oculto no Mobile) */}
            <div className="hidden md:flex min-w-0 shrink items-center">
              <div className="flex flex-col items-center text-center gap-1.5 md:flex-row md:items-center md:text-left md:gap-5 min-w-0">
                  {logoUrl ? (
                    <div className={`h-16 w-auto min-w-[100px] ${tamanhoDaLogo === "pequeno" ? "md:h-16" : tamanhoDaLogo === "grande" ? "md:h-28" : "md:h-24"} md:min-w-[148px] flex items-center justify-center shrink-0`}>
                      <Image
                        src={logoUrl}
                        alt={storeName}
                      className={`h-full w-auto object-contain ${logoEffectClass}`}
                      style={{
                        "--ks-logo-effect-intensity": String(logoIntensityMultiplier),
                        "--ks-logo-effect-duration-rotate": `${(5.2 * logoSpeedDurationMultiplier).toFixed(2)}s`,
                        "--ks-logo-effect-duration-pulse": `${(3.2 * logoSpeedDurationMultiplier).toFixed(2)}s`,
                        "--ks-logo-effect-duration-blink": `${(2.4 * logoSpeedDurationMultiplier).toFixed(2)}s`,
                      } as CSSProperties}
                      width={280}
                      height={96}
                      unoptimized
                    />
                  </div>
                ) : (
                  <div className="h-12 w-12 flex items-center justify-center shrink-0">
                    <ShoppingBag size={24} style={{ color: primaryPalette.text }} />
                  </div>
                )}
                {(shouldShowStoreName || shouldShowStoreSlogan) && (
                  <div className="min-w-0 text-center md:text-left shrink">
                    {shouldShowStoreName ? (
                      <span
                        className="block text-[1.2rem] md:text-[1.7rem] font-extrabold tracking-tight leading-tight line-clamp-2"
                        style={{ color: headerNameTextColor }}
                      >
                        {storeName}
                      </span>
                    ) : null}
                    {shouldShowStoreSlogan ? (
                      <span className="block text-[11px] md:text-[13px] mt-0.5 font-medium tracking-[0.02em] line-clamp-1" style={{ color: headerSloganTextColor }}>
                        {storeSlogan}
                      </span>
                    ) : null}
                  </div>
                )}
              </div>
            </div>

            <div className="hidden md:flex items-center gap-6 lg:gap-8 shrink-0 relative">
              {mostrarBusca ? (
              <>
              {/* Ícone de Busca - Toggle */}
              <button
                type="button"
                onClick={() => setIsDesktopSearchOpen(!isDesktopSearchOpen)}
                className="flex items-center justify-center hover:opacity-80 transition-opacity shrink-0 cursor-pointer"
                style={{ color: primaryPalette.text }}
                title="Buscar produtos"
              >
                <Search size={24} strokeWidth={1.5} />
              </button>

              {/* Input de Busca Dropdown */}
              <AnimatePresence>
                {isDesktopSearchOpen && (
                  <motion.div
                    initial={{ opacity: 0, y: -10 }}
                    animate={{ opacity: 1, y: 0 }}
                    exit={{ opacity: 0, y: -10 }}
                    transition={{ duration: 0.2 }}
                    className="absolute top-[calc(100%+16px)] right-0 w-[380px] bg-white rounded-2xl shadow-[0_10px_40px_rgba(0,0,0,0.1)] border border-gray-100 p-2 z-[60]"
                  >
                    <div className="relative">
                      <input
                        type="text"
                        placeholder={`Busque na ${storeName}`}
                        value={searchTerm}
                        onChange={(e) => {
                          setSearchTerm(e.target.value);
                          setIsSearchSuggestionsOpen(Boolean(e.target.value.trim()));
                        }}
                        onFocus={() => setIsSearchSuggestionsOpen(Boolean(normalizedSearchTerm))}
                        onKeyDown={(event) => handleSearchInputKeyDown(event, { closeDesktopSearch: true })}
                        autoFocus
                        className="w-full pl-11 pr-4 py-3 rounded-xl border border-gray-200 focus:border-gray-300 focus:ring-4 focus:ring-gray-100 transition-all bg-gray-50 text-gray-800 placeholder-gray-400 text-sm font-medium"
                      />
                      <Search size={18} className="absolute left-4 top-1/2 -translate-y-1/2 text-gray-400" />
                      {renderSearchSuggestions({ insidePopover: true })}
                    </div>
                  </motion.div>
                )}
              </AnimatePresence>
              </>
              ) : null}

              {loggedClient ? (
                <div className="flex items-center gap-2.5 shrink-0">
                  <Link
                    href={`/${slug}/cliente`}
                    className="hover:opacity-80 transition-opacity shrink-0"
                    style={{ color: primaryPalette.text }}
                    aria-label="Abrir portal do cliente"
                    title="Minha conta"
                  >
                    {loggedClient.avatar_url ? (
                      <Image
                        src={loggedClient.avatar_url}
                        alt={loggedClient.name}
                        width={28}
                        height={28}
                        className="rounded-full object-cover shrink-0 bg-white/20 h-7 w-7"
                        unoptimized
                      />
                    ) : (
                      <UserCircle2 size={24} strokeWidth={1.5} className="shrink-0" />
                    )}
                  </Link>

                  <div className="flex flex-col items-start justify-center" style={{ color: primaryPalette.text }}>
                    <span className="text-[11px] font-medium leading-[1.2] opacity-80 whitespace-nowrap">Olá,</span>
                    <Link
                      href={`/${slug}/cliente`}
                      className="text-[14px] font-bold leading-[1.15] max-w-[100px] truncate whitespace-nowrap hover:opacity-80 transition-opacity"
                      title="Abrir portal do cliente"
                    >
                      {loggedClient.name.split(" ")[0]}
                    </Link>
                    <button
                      onClick={handleLogout}
                      className="text-[11px] font-semibold underline underline-offset-2 hover:opacity-70 transition-opacity leading-none mt-[1px]"
                      title="Sair da conta"
                      type="button"
                    >
                      Sair
                    </button>
                  </div>
                </div>
              ) : (
                <Link
                  href={`/${slug}/cliente/login`}
                  className="flex items-center gap-2.5 hover:opacity-80 transition-opacity shrink-0"
                  style={{ color: primaryPalette.text }}
                >
                  <UserCircle2 size={24} strokeWidth={1.5} className="shrink-0" />
                  <div className="flex flex-col items-start justify-center">
                    <span className="text-[11px] font-medium leading-[1.2] opacity-80 whitespace-nowrap">Minha conta</span>
                    <span className="text-[14px] font-bold leading-[1.2] whitespace-nowrap">Entrar / Cadastrar</span>
                  </div>
                </Link>
              )}

              {loggedClient ? (
                <Link
                  href={`/${slug}/cliente?section=favorites`}
                  className="flex items-center justify-center hover:opacity-80 transition-opacity shrink-0"
                  style={{ color: primaryPalette.text }}
                  title="Meus Favoritos"
                >
                  <Heart size={24} strokeWidth={1.5} />
                </Link>
              ) : (
                <button
                  type="button"
                  onClick={() => openAuthModal({ type: "favorites_header" })}
                  className="flex items-center justify-center hover:opacity-80 transition-opacity shrink-0"
                  style={{ color: primaryPalette.text }}
                  title="Entrar para ver favoritos"
                >
                  <Heart size={24} strokeWidth={1.5} />
                </button>
              )}

              <div className="flex items-center gap-1 hover:opacity-80 transition-opacity shrink-0" style={{ color: primaryPalette.text }}>
                <div className="-ml-2 shrink-0">
                  <CartTrigger
                    primaryColor={primaryPalette.base}
                    iconColor={primaryPalette.text}
                    badgeBackgroundColor={primaryPalette.badgeBg}
                    badgeTextColor={primaryPalette.badgeText}
                    hoverBackgroundColor="transparent"
                    surfaceColor={primaryPalette.base}
                  />
                </div>
                <span className="hidden sm:block text-[14px] font-bold tracking-tight pr-2 whitespace-nowrap">R$ 0,00</span>
              </div>
            </div>
          </div>

        </div>

        {/* 2. Stories Mobile */}
        {catalogStoriesEnabled && storiesGroups && storiesGroups.length > 0 && (
          <div className="md:hidden">
            <StoriesCarousel groups={storiesGroups} primaryColor={primaryPalette.base} slug={slug} />
          </div>
        )}

        {/* 3. Categories Strip (Desktop Only) */}
        <div className="hidden md:block bg-white border-b border-gray-100 relative z-30">
          <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8" ref={desktopCategoriesRef}>
            <div className="h-[60px] flex items-center justify-start gap-4 xl:gap-6 relative min-w-0">
              <Link
                href={`/${slug}`}
                onClick={() => {
                  closeCategoryMenus();
                  setLocalSelectedCategory("all");
                }}
                aria-label="Ir para página inicial"
                title="Página inicial"
                className="h-9 w-9 shrink-0 rounded-lg flex items-center justify-center transition-colors"
                style={{
                  color: selectedCategory === "all" ? primaryPalette.base : "#334155",
                  backgroundColor: selectedCategory === "all" ? withAlpha(primaryPalette.base, 0.08) : "transparent",
                }}
              >
                <House size={18} />
              </Link>

              {/* Mega Menu Toggle */}
              {mostrarTodasAsCategorias ? (
              <div 
                className="relative h-full flex items-center min-w-[200px] shrink-0"
                onMouseEnter={() => {
                  cancelDesktopSubmenuClose();
                  openMegaMenu();
                  if (!activeMegaMenuCategory && rootCategories.length > 0) {
                    const activeRoot = rootCategories.find(c => isCategoryActive(c.id));
                    setActiveMegaMenuCategory(activeRoot?.id || rootCategories[0].id);
                  }
                }}
                onMouseLeave={() => {
                  scheduleMegaMenuClose();
                }}
              >
                <button
                  type="button"
                  className="flex items-center gap-2 text-[15px] font-bold transition-colors cursor-pointer whitespace-nowrap shrink-0"
                  style={{
                    color: isDesktopCategoriesOpen ? primaryPalette.base : "#1e293b",
                  }}
                  aria-expanded={isDesktopCategoriesOpen}
                >
                  <Menu size={20} />
                  <span className="whitespace-nowrap">Todas as Categorias</span>
                  {isDesktopCategoriesOpen ? <ChevronUp size={18} /> : <ChevronDown size={18} />}
                </button>

                {/* Invisible hover bridge to prevent mega menu closing */}
                {isDesktopCategoriesOpen && (
                  <div 
                    className="absolute top-[calc(100%-10px)] left-0 w-[800px] h-[20px] bg-transparent z-[60]" 
                    onMouseEnter={() => {
                      openMegaMenu();
                    }}
                  />
                )}

                {/* Mega Menu Dropdown */}
                {isDesktopCategoriesOpen && (
                  <div 
                    className="absolute top-full left-0 w-[800px] h-[450px] bg-white rounded-xl shadow-[0_20px_60px_rgba(15,23,42,0.15)] border border-gray-100 flex overflow-hidden z-[60] mt-1"
                    onMouseEnter={() => {
                      openMegaMenu();
                    }}
                    onMouseLeave={() => {
                      scheduleMegaMenuClose();
                    }}
                  >
                    {/* Left Column - Root Categories */}
                    <div className="w-[280px] bg-[#f8fafc] overflow-y-auto py-3 border-r border-gray-100">
                      {rootCategories.map(category => (
                        <div 
                          key={category.id}
                          onMouseEnter={() => setActiveMegaMenuCategory(category.id)}
                          className="px-3 py-0.5"
                        >
                          <Link
                            href={getCategoryHref(category)}
                            onClick={() => {
                              closeCategoryMenus();
                              setLocalSelectedCategory(category.id);
                            }}
                            className={`block px-4 py-3 rounded-lg text-[14px] transition-all ${
                              activeMegaMenuCategory === category.id 
                                ? "bg-white font-bold text-slate-900 shadow-[0_1px_3px_rgba(0,0,0,0.05)] ring-1 ring-black/5" 
                                : "text-slate-600 hover:text-slate-900 hover:bg-slate-100 font-medium"
                            }`}
                          >
                            {category.name}
                          </Link>
                        </div>
                      ))}
                    </div>

                    {/* Right Column - Subcategories */}
                    <div className="flex-1 bg-white p-8 overflow-y-auto">
                      {(() => {
                        const activeCategory = rootCategories.find(c => c.id === activeMegaMenuCategory);
                        if (!activeCategory) return null;
                        const subs = subcategoriesByParent.get(activeCategory.id) || [];
                        
                        if (subs.length === 0) {
                          return (
                            <div className="h-full flex items-center justify-center text-sm text-slate-400 font-medium">
                              Sem subcategorias
                            </div>
                          );
                        }

                        return (
                          <div className="grid grid-cols-2 gap-x-8 gap-y-4 content-start">
                            {subs.map(sub => (
                              <Link
                                key={sub.id}
                                href={getCategoryHref(sub)}
                                onClick={() => {
                                  closeCategoryMenus();
                                  setLocalSelectedCategory(sub.id);
                                }}
                                className="text-[14px] text-slate-600 hover:text-slate-900 transition-colors font-medium hover:underline underline-offset-4"
                                style={{
                                  textDecorationColor: selectedCategory === sub.id ? primaryPalette.base : undefined,
                                  color: selectedCategory === sub.id ? primaryPalette.base : undefined,
                                }}
                              >
                                {sub.name}
                              </Link>
                            ))}
                          </div>
                        );
                      })()}
                    </div>
                  </div>
                )}
              </div>
              ) : null}

              {/* Horizontal Root Categories */}
              <nav
                ref={desktopMenuNavRef}
                className="flex-1 min-w-0 flex items-center justify-start gap-3 xl:gap-4 overflow-visible h-full"
              >
                {itensDoMenu ? (
                  <ItensDoMenuNaFaixa
                    itens={itensDoMenu}
                    variante="padrao"
                    corDaMarca={primaryPalette.base}
                    corDoTextoNaMarca={primaryPalette.text}
                    corDoTexto="#334155"
                    fundoDaLista="#ffffff"
                  />
                ) : desktopVisibleCategories.map((category) => (
                  <div
                    key={category.id}
                    className="relative h-full flex items-center group shrink-0"
                    onMouseEnter={() => openDesktopSubmenu(category.id)}
                    onMouseLeave={() => scheduleDesktopSubmenuClose(category.id)}
                  >
                    <Link
                      href={getCategoryHref(category)}
                      onClick={() => {
                        cancelDesktopSubmenuClose();
                        closeCategoryMenus();
                        setLocalSelectedCategory(category.id);
                      }}
                      className="text-[14px] font-semibold transition-colors whitespace-nowrap h-full flex items-center gap-1"
                      style={{
                        color: isCategoryActive(category.id) ? primaryPalette.base : "#334155",
                      }}
                    >
                      <span className="group-hover:opacity-80 transition-opacity">{category.name}</span>
                      {Boolean((subcategoriesByParent.get(category.id) || []).length) && (
                        <ChevronDown size={14} className="opacity-50 group-hover:opacity-100 transition-opacity" />
                      )}
                      <span 
                        className={`absolute bottom-0 left-0 w-full h-0.5 rounded-t-full transition-transform origin-left ${isCategoryActive(category.id) ? 'scale-x-100' : 'scale-x-0 group-hover:scale-x-100'}`}
                        style={{ backgroundColor: primaryPalette.base, opacity: isCategoryActive(category.id) ? 1 : 0.5 }}
                      />
                    </Link>

                    {/* Invisible hover bridge to prevent submenu closing when moving mouse */}
                    {(subcategoriesByParent.get(category.id) || []).length > 0 &&
                      openDesktopSubmenuId === category.id &&
                      !isDesktopCategoriesOpen && (
                        <div 
                          className="absolute top-[calc(100%-10px)] left-0 w-full h-[20px] bg-transparent z-[60]" 
                          onMouseEnter={() => cancelDesktopSubmenuClose()}
                        />
                    )}

                    {/* Simple Submenu for horizontal items */}
                    {(subcategoriesByParent.get(category.id) || []).length > 0 &&
                      openDesktopSubmenuId === category.id &&
                      !isDesktopCategoriesOpen && (
                        <div
                          className="absolute top-full left-0 z-[60] w-64 rounded-xl border bg-white py-2 shadow-[0_10px_30px_rgba(15,23,42,0.1)] pointer-events-auto"
                          style={{ borderColor: withAlpha(primaryPalette.base, 0.14) }}
                          onMouseEnter={cancelDesktopSubmenuClose}
                          onMouseLeave={() => scheduleDesktopSubmenuClose(category.id)}
                        >
                          {(subcategoriesByParent.get(category.id) || []).map((subcategory) => (
                            <Link
                              key={subcategory.id}
                              href={getCategoryHref(subcategory)}
                              onClick={() => {
                                cancelDesktopSubmenuClose();
                                closeCategoryMenus();
                                setLocalSelectedCategory(subcategory.id);
                              }}
                              className="block px-5 py-2.5 text-[14px] transition-colors"
                              style={{
                                backgroundColor:
                                  selectedCategory === subcategory.id
                                    ? withAlpha(primaryPalette.base, 0.05)
                                    : "transparent",
                                color: selectedCategory === subcategory.id ? primaryPalette.base : "#475569",
                                fontWeight: selectedCategory === subcategory.id ? 600 : 500,
                              }}
                            >
                              <span className="truncate block hover:text-slate-900">{subcategory.name}</span>
                            </Link>
                          ))}
                        </div>
                      )}
                  </div>
                ))}

              </nav>

              <div className="pointer-events-none absolute left-0 top-0 -z-10 h-0 overflow-hidden whitespace-nowrap opacity-0">
                {rootCategories.map((category) => (
                  <span
                    key={`measure-${category.id}`}
                    ref={(element) => {
                      if (element) {
                        desktopCategoryMeasureRefs.current.set(category.id, element);
                        return;
                      }
                      desktopCategoryMeasureRefs.current.delete(category.id);
                    }}
                    className="inline-flex items-center gap-1 text-[14px] font-semibold"
                  >
                    <span>{category.name}</span>
                    {Boolean((subcategoriesByParent.get(category.id) || []).length) && <ChevronDown size={14} />}
                  </span>
                ))}
              </div>

            </div>
          </div>
        </div>
      </header>
      ) : catalogThemeId === "vitrine" ? renderVitrineHeader() : null}

      {catalogThemeId === "default" ? (
      <>
      {paginaExtra?.mostrarTitulo ? (
        <div className="bg-white border-b border-gray-100">
          <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-6 md:py-8">
            <nav className="mb-2 flex items-center gap-1.5 text-xs text-slate-500">
              <Link href={`/${slug}`} className="hover:text-slate-900 transition-colors">Início</Link>
              <ChevronRight size={12} className="opacity-60" />
              <span className="truncate font-medium text-slate-700">{paginaExtra.titulo}</span>
            </nav>
            <h1 className="text-2xl md:text-3xl font-extrabold tracking-tight text-slate-900">{paginaExtra.titulo}</h1>
          </div>
        </div>
      ) : null}
      {slideEnabled && (
        <div className="catalog-hero w-full bg-gray-100 overflow-hidden relative">
          {slideBanners.length > 0 ? (
            <div className="catalog-hero-banner relative mx-auto w-full max-w-[1920px] aspect-[32/9]">
              {slideBanners.map((banner, idx) => {
                const isActive = idx === activeBannerIndex;
                const linkType = banner.link_type || "none";
                const destino =
                  linkType === "product" && banner.product_id
                    ? { href: `/${slug}/p/${banner.product_id}`, externo: false }
                    : linkType === "url"
                      ? destinoDoLink(banner.link_url)
                      : null;
                const href = destino?.href || "";
                const target = banner.open_in_new_tab ? "_blank" : undefined;
                const rel = banner.open_in_new_tab ? "noopener noreferrer" : undefined;

                const image = (
                  <Image
                    src={banner.image_url}
                    alt=""
                    className="w-full h-full object-contain"
                    fill
                    sizes="100vw"
                    draggable={false}
                    unoptimized
                  />
                );

                const content = href ? (
                  destino?.externo ? (
                    <a href={href} target={target} rel={rel} className="block w-full h-full">
                      {image}
                    </a>
                  ) : (
                    <Link href={href} target={target} rel={rel} className="block w-full h-full">
                      {image}
                    </Link>
                  )
                ) : (
                  image
                );

                return (
                  <div
                    key={banner.id}
                    className={`absolute inset-0 transition-opacity duration-500 ${isActive ? "opacity-100" : "opacity-0 pointer-events-none"}`}
                  >
                    {content}
                  </div>
                );
              })}

              {slideBanners.length > 1 && (
                <>
                  <button
                    type="button"
                    onClick={() => setCurrentBanner((prev) => (prev - 1 + slideBanners.length) % slideBanners.length)}
                    className="absolute left-3 top-1/2 -translate-y-1/2 bg-white/70 hover:bg-white text-gray-900 rounded-full p-2 shadow-sm"
                    aria-label="Banner anterior"
                  >
                    <ChevronLeft size={20} />
                  </button>
                  <button
                    type="button"
                    onClick={() => setCurrentBanner((prev) => (prev + 1) % slideBanners.length)}
                    className="absolute right-3 top-1/2 -translate-y-1/2 bg-white/70 hover:bg-white text-gray-900 rounded-full p-2 shadow-sm"
                    aria-label="Próximo banner"
                  >
                    <ChevronRight size={20} />
                  </button>
                  <div className="absolute bottom-3 left-0 right-0 flex items-center justify-center gap-2">
                    {slideBanners.map((b, idx) => (
                      <button
                        key={b.id}
                        type="button"
                        onClick={() => setCurrentBanner(idx)}
                        className={`h-2.5 rounded-full transition-all ${idx === activeBannerIndex ? "w-8 bg-white" : "w-2.5 bg-white/60"}`}
                        aria-label={`Ir para banner ${idx + 1}`}
                      />
                    ))}
                  </div>
                </>
              )}
            </div>
          ) : (
            <div
              className="catalog-hero-banner mx-auto w-full max-w-[1920px] aspect-[32/9] flex items-center justify-center relative"
              style={{
                backgroundImage: `linear-gradient(135deg, ${primaryPalette.base}15, ${primaryPalette.base}40)`,
              }}
            >
              <div className="absolute top-10 left-10 w-20 h-20 rounded-full bg-white/30 blur-xl animate-pulse" />
              <div className="absolute bottom-10 right-10 w-32 h-32 rounded-full bg-white/30 blur-xl animate-pulse delay-700" />
              <div className="text-center px-4">
                <h1 className="text-4xl md:text-6xl font-black text-gray-900/10 uppercase tracking-widest select-none">
                  {storeName}
                </h1>
              </div>
            </div>
          )}
        </div>
      )}

      {infoStripEnabled && infoStripItems.length > 0 && (
        <div className="catalog-info-strip bg-white py-4 border-b border-gray-100">
          <div className="catalog-info-strip-inner max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
            <div className="flex flex-row items-stretch justify-between md:grid md:grid-cols-3 gap-2 md:gap-4 overflow-hidden divide-x divide-gray-100">
              {infoStripItems.slice(0, 3).map((item, idx) => {
                const Icon = infoIconMap[item.icon] ?? Truck;
                return (
                  <div
                    key={idx}
                    className={`group relative flex flex-col items-center justify-center gap-2 overflow-hidden rounded-2xl border p-3 text-center transition-all hover:bg-[var(--info-hover-bg)] hover:border-[var(--info-hover-border)] md:flex-row md:justify-start md:gap-4 md:text-left ${
                      idx === 0 ? "" : ""
                    }`}
                    style={{
                      ["--info-hover-bg" as string]: withAlpha(primaryPalette.base, 0.04),
                      ["--info-hover-border" as string]: withAlpha(primaryPalette.base, 0.14),
                      backgroundColor: primaryPalette.base,
                      borderColor: primaryPalette.base,
                    }}
                  >
                    <div className="pointer-events-none absolute -right-4 top-1/2 -translate-y-1/2 opacity-[0.14] transition-opacity duration-300 group-hover:opacity-[0.22]">
                      <Icon size={68} style={{ color: primaryPalette.text, transform: "rotate(35deg)" }} />
                    </div>
                    <div
                      className="relative z-10 shrink-0 rounded-full p-2 md:p-3"
                      style={{ backgroundColor: withAlpha("#FFFFFF", 0.16), color: primaryPalette.text }}
                    >
                      <Icon size={20} className="md:w-6 md:h-6" style={{ color: primaryPalette.text }} />
                    </div>
                    <div className="relative z-10 min-w-0 flex-1">
                      <h3
                        className="text-[10px] font-bold leading-tight transition-colors group-hover:text-[var(--info-hover-text)] md:text-sm md:leading-normal line-clamp-2 md:line-clamp-1"
                        style={{ color: primaryPalette.text, ["--info-hover-text" as string]: primaryPalette.onWhiteSurface }}
                      >
                        {item.title}
                      </h3>
                      <p
                        className="hidden text-[9px] transition-colors group-hover:text-[var(--info-hover-subtext)] md:block md:text-xs"
                        style={{
                          color: withAlpha(primaryPalette.text, 0.82),
                          ["--info-hover-subtext" as string]: withAlpha(primaryPalette.onWhiteSurface, 0.72),
                        }}
                      >
                        {item.subtitle}
                      </p>
                    </div>
                  </div>
                );
              })}
            </div>
          </div>
        </div>
      )}

      {paginaExtra && sortedSections.length === 0 ? paginaExtra.vazio : null}
      {isSearchResultsPage && !hideSections ? (
        renderSearchResultsContent()
      ) : sortedSections.length > 0 && (
        <div className="w-full">
          {sortedSections.map((section, indice) => vestirSecao(section, indice, renderSection))}
        </div>
      )}
      </>
      ) : catalogThemeId === "vitrine" ? (
        isProductPage ? children : paginaExtra ? renderVitrinePaginaExtra() : renderVitrineContent()
      ) : null}

      <CatalogMobileBottomNav
        slug={slug}
        primaryColor={primaryPalette.base}
        categoriesHref={`/${slug}`}
        whatsappDigits={bestWhatsappDigits}
        isSearchActive={isMobileSearchOpen}
        isCategoriesActive={isMobileCategoriesOpen}
        onHomeClick={() => {
          closeCategoryMenus();
          setIsMobileSearchOpen(false);
          setLocalSelectedCategory("all");
          if (isSearchResultsPage) {
            router.push(`/${slug}`);
          }
        }}
        onSearchClick={() => {
          setIsMobileCategoriesOpen(false);
          setIsMobileSearchOpen(true);
        }}
        onCategoriesClick={() => {
          if (isMobileCategoriesOpen) {
            setIsMobileCategoriesOpen(false);
          } else {
            setIsMobileSearchOpen(false);
            setIsMobileCategoriesOpen(true);
          }
        }}
      />

      {/* Mobile Search Overlay */}
      {isMobileSearchOpen && (
        <div className="catalog-mobile-search md:hidden fixed inset-0 z-[80] bg-black/50 backdrop-blur-sm animate-in fade-in duration-200">
           <div className="bg-white rounded-b-2xl shadow-xl w-full p-4 pt-6 animate-in slide-in-from-top-4 duration-300">
               <div className="flex items-center gap-3 mb-4">
                 <div className="relative flex-1 group">
                    <input 
                      type="text" 
                      placeholder={`Busque em ${storeName}...`}
                      value={searchTerm}
                      onChange={(e) => setSearchTerm(e.target.value)}
                      onKeyDown={(event) => handleSearchInputKeyDown(event, { closeMobileSearch: true })}
                      autoFocus
                      className="w-full pl-10 pr-4 py-3 rounded-xl bg-gray-100 border-transparent focus:bg-white focus:ring-2 focus:border-transparent transition-all text-sm outline-none"
                      style={{
                        '--tw-ring-color': primaryPalette.base,
                      } as React.CSSProperties}
                    />
                    <Search className="absolute left-3 top-1/2 -translate-y-1/2 text-gray-400" size={18} style={{ color: searchTerm ? primaryPalette.onWhiteSurface : '#9CA3AF' }} />
                 </div>
                 <button 
                   onClick={() => setIsMobileSearchOpen(false)}
                   className="p-2 text-gray-500 font-medium text-sm"
                 >
                   Cancelar
                 </button>
               </div>
               
               {normalizedSearchTerm.length > 0 && (
                 <div className="max-h-[60vh] overflow-y-auto custom-scrollbar">
                  <p className="text-sm text-gray-500 mb-4">Resultados para &quot;{normalizedSearchTerm}&quot;</p>
                   {allSearchSuggestionProducts.length === 0 ? (
                     <div className="text-center py-10">
                       <p className="text-gray-400">Nenhum produto encontrado.</p>
                     </div>
                   ) : (
                     <div className="space-y-4 pb-4">
                         {searchPreviewProducts.map(p => (
                           <Link 
                             key={p.id} 
                             href={`/${slug}/p/${p.id}`}
                             onClick={() => {
                               trackCatalogInteraction({
                                 eventName: "product_click",
                                 productId: p.id,
                                 categoryId: p.category_id || null,
                               });
                               setIsMobileSearchOpen(false);
                             }}
                             className="flex items-center gap-4 p-3 bg-gray-50 hover:bg-gray-100 transition-colors rounded-xl border border-gray-100"
                           >
                           <div className="w-12 h-12 bg-white rounded-lg flex items-center justify-center shrink-0">
                             {p.image_url ? (
                               <Image src={p.image_url} alt="" width={48} height={48} className="w-full h-full object-cover rounded-lg" unoptimized />
                             ) : (
                               <ShoppingBag size={20} className="text-gray-300" />
                             )}
                           </div>
                           <div>
                             <p className="font-medium text-gray-900 line-clamp-1 text-sm">{p.name}</p>
                             <p className="text-sm text-gray-500 font-bold mt-0.5">
                               {formatProductPrice(p, textoSemPreco)}
                             </p>
                           </div>
                         </Link>
                       ))}
                      {normalizedSearchTerm && (
                         <button 
                           onClick={() => {
                             executeCatalogSearch({ closeMobileSearch: true });
                           }}
                           className="w-full py-3 text-center text-sm font-bold rounded-xl mt-2"
                            style={{ backgroundColor: primaryPalette.base, color: primaryPalette.text }}
                          >
                           {allSearchSuggestionProducts.length > 0
                             ? `Ver todos os resultados (${allSearchSuggestionProducts.length})`
                             : "Ver todos os resultados"}
                         </button>
                       )}
                     </div>
                   )}
                 </div>
               )}
           </div>
        </div>
      )}

      {/* Mobile Categories Sheet */}
      <AnimatePresence initial={false}>
      {isMobileCategoriesOpen && (
        <div className="md:hidden fixed inset-0 z-[80] h-[100dvh]">
          <motion.div
            initial={{ opacity: 0 }}
            animate={{ opacity: 1 }}
            exit={{ opacity: 0 }}
            transition={{ duration: 0.22, ease: "easeOut" }}
            className="absolute inset-0 bg-black/52"
            onClick={closeCategoryMenus}
          />
          <motion.aside
            initial={{ x: "-100%" }}
            animate={{ x: 0 }}
            exit={{ x: "-100%" }}
            transition={{ type: "tween", duration: 0.34, ease: [0.22, 1, 0.36, 1] }}
            className="absolute left-0 top-0 bottom-0 flex h-full w-[86%] max-w-[330px] transform-gpu flex-col overflow-hidden bg-white shadow-[16px_0_48px_rgba(15,23,42,0.28)] will-change-transform"
          >
            {/* Faixa da marca: largura inteira e na cor do header de proposito.
                A logo do lojista foi desenhada para aquele fundo — sobre branco
                ela perde contorno ou some. */}
            <div
              className="relative flex shrink-0 items-center justify-between gap-3 px-5 pb-5 pt-5"
              style={{ backgroundColor: headerPalette.bg, color: headerPalette.text }}
            >
              {logoUrl ? (
                <Image
                  src={logoUrl}
                  alt={storeName}
                  width={220}
                  height={72}
                  className="h-11 w-auto max-w-[180px] object-contain object-left"
                />
              ) : (
                <div
                  className="flex h-11 w-11 items-center justify-center rounded-2xl"
                  style={{ backgroundColor: withAlpha(headerPalette.text, 0.16) }}
                >
                  <ShoppingBag size={20} />
                </div>
              )}
              <button
                type="button"
                onClick={closeCategoryMenus}
                aria-label="Fechar menu"
                className="-mr-1 flex h-9 w-9 shrink-0 items-center justify-center rounded-full transition active:scale-90"
                style={{ backgroundColor: withAlpha(headerPalette.text, 0.14) }}
              >
                <X size={17} />
              </button>
            </div>

            {/* Perfil: logado mostra foto e nome; deslogado vira o convite para
                entrar. E o mesmo bloco nos dois casos para o menu nao "pular"
                de layout depois do login. */}
            <Link
              href={loggedClient ? `/${slug}/cliente` : `/${slug}/cliente/login`}
              onClick={closeCategoryMenus}
              className="flex shrink-0 items-center gap-3 border-b border-slate-100 px-4 py-3.5 transition active:bg-slate-50"
            >
              {loggedClient?.avatar_url ? (
                <Image
                  src={loggedClient.avatar_url}
                  alt={loggedClient.name}
                  width={40}
                  height={40}
                  className="h-10 w-10 shrink-0 rounded-full object-cover"
                  unoptimized
                />
              ) : (
                <span
                  className="flex h-10 w-10 shrink-0 items-center justify-center rounded-full text-[15px] font-bold"
                  style={{
                    backgroundColor: withAlpha(primaryPalette.base, 0.12),
                    color: primaryPalette.onWhiteSurface,
                  }}
                >
                  {loggedClient ? (
                    loggedClient.name.trim().charAt(0).toUpperCase()
                  ) : (
                    <User size={19} />
                  )}
                </span>
              )}
              <span className="min-w-0 flex-1">
                <span className="block truncate text-[14px] font-semibold text-slate-900">
                  {loggedClient ? loggedClient.name : "Entrar na minha conta"}
                </span>
                <span className="mt-0.5 block truncate text-[12px] text-slate-500">
                  {loggedClient ? "Ver meus pedidos e favoritos" : "Acompanhe pedidos e favoritos"}
                </span>
              </span>
              <ChevronRight size={17} className="shrink-0 text-slate-300" />
            </Link>

            <nav className="flex-1 overflow-y-auto overscroll-contain px-2.5 py-3">
              {itensDoMenu ? (
                <div className={mostrarTodasAsCategorias ? "mb-3" : undefined}>
                  <div className="px-2 pb-2 text-[10px] font-bold uppercase tracking-[0.16em] text-slate-400">Menu</div>
                  <ItensDoMenuNoCelular
                    itens={itensDoMenu}
                    corDaMarca={primaryPalette.base}
                    fundoAtivo={withAlpha(primaryPalette.base, 0.1)}
                    corAtiva={primaryPalette.onWhiteSurface}
                    aoEscolher={closeCategoryMenus}
                  />
                </div>
              ) : null}
              {mostrarTodasAsCategorias ? (
              <>
              <div className="px-2 pb-2 text-[10px] font-bold uppercase tracking-[0.16em] text-slate-400">
                Categorias
              </div>

              <div className="space-y-0.5">
                {(() => {
                  const todosAtivo = selectedCategory === "all";

                  const classeLinha =
                    "flex items-center gap-2.5 rounded-xl px-3 py-2.5 transition active:bg-slate-100";

                  return (
                    <>
                      <Link
                        href={`/${slug}`}
                        onClick={() => {
                          closeCategoryMenus();
                          setLocalSelectedCategory("all");
                        }}
                        className={classeLinha}
                        style={
                          todosAtivo
                            ? {
                                backgroundColor: withAlpha(primaryPalette.base, 0.1),
                                color: primaryPalette.onWhiteSurface,
                              }
                            : undefined
                        }
                      >
                        <ShoppingBag
                          size={17}
                          className="shrink-0"
                          style={{ color: todosAtivo ? primaryPalette.base : "#94a3b8" }}
                        />
                        <span
                          className={`min-w-0 flex-1 truncate text-[14px] ${
                            todosAtivo ? "font-semibold" : "font-medium text-slate-700"
                          }`}
                        >
                          Todos os Produtos
                        </span>
                        <ChevronRight size={16} className="shrink-0 text-slate-300" />
                      </Link>

                      {rootCategories.map((category) => {
                        const filhas = subcategoriesByParent.get(category.id) || [];
                        const temFilhas = filhas.length > 0;
                        const expandida = expandedMobileParentIds.has(category.id);
                        const ativa = isCategoryActive(category.id);

                        return (
                          <div key={category.id}>
                            <div
                              className="flex items-center rounded-xl transition"
                              style={
                                ativa
                                  ? {
                                      backgroundColor: withAlpha(primaryPalette.base, 0.1),
                                      color: primaryPalette.onWhiteSurface,
                                    }
                                  : undefined
                              }
                            >
                              <Link
                                href={getCategoryHref(category)}
                                onClick={() => {
                                  closeCategoryMenus();
                                  setLocalSelectedCategory(category.id);
                                }}
                                className="min-w-0 flex-1 py-2.5 pl-3 pr-1"
                              >
                                <span
                                  className={`block truncate text-[14px] ${
                                    ativa ? "font-semibold" : "font-medium text-slate-700"
                                  }`}
                                >
                                  {category.name}
                                </span>
                              </Link>
                              {temFilhas ? (
                                <button
                                  type="button"
                                  aria-label={expandida ? "Recolher subcategorias" : "Expandir subcategorias"}
                                  aria-expanded={expandida}
                                  onClick={(event) => {
                                    event.preventDefault();
                                    event.stopPropagation();
                                    toggleMobileParentCategory(category.id);
                                  }}
                                  className="mr-1 flex h-9 w-9 shrink-0 items-center justify-center rounded-lg transition active:bg-slate-100"
                                >
                                  <ChevronDown
                                    size={16}
                                    className={`transition-transform duration-200 ${expandida ? "rotate-180" : ""}`}
                                    style={{ color: ativa ? primaryPalette.base : "#94a3b8" }}
                                  />
                                </button>
                              ) : (
                                <span className="mr-1 flex h-9 w-9 shrink-0 items-center justify-center">
                                  <ChevronRight size={16} className="text-slate-300" />
                                </span>
                              )}
                            </div>

                            <AnimatePresence initial={false}>
                              {temFilhas && expandida ? (
                                <motion.div
                                  initial={{ height: 0, opacity: 0 }}
                                  animate={{ height: "auto", opacity: 1 }}
                                  exit={{ height: 0, opacity: 0 }}
                                  transition={{ duration: 0.22, ease: [0.22, 1, 0.36, 1] }}
                                  className="overflow-hidden"
                                >
                                  <div className="ml-[18px] space-y-0.5 border-l border-slate-200 py-1 pl-2.5">
                                    {filhas.map((subcategory) => {
                                      const subAtiva = selectedCategory === subcategory.id;
                                      return (
                                        <Link
                                          key={subcategory.id}
                                          href={getCategoryHref(subcategory)}
                                          onClick={() => {
                                            closeCategoryMenus();
                                            setLocalSelectedCategory(subcategory.id);
                                          }}
                                          className="block truncate rounded-lg px-3 py-2 text-[13px] transition active:bg-slate-100"
                                          style={
                                            subAtiva
                                              ? {
                                                  backgroundColor: withAlpha(primaryPalette.base, 0.1),
                                                  color: primaryPalette.onWhiteSurface,
                                                  fontWeight: 600,
                                                }
                                              : undefined
                                          }
                                        >
                                          <span className={subAtiva ? undefined : "text-slate-500"}>
                                            {subcategory.name}
                                          </span>
                                        </Link>
                                      );
                                    })}
                                  </div>
                                </motion.div>
                              ) : null}
                            </AnimatePresence>
                          </div>
                        );
                      })}
                    </>
                  );
                })()}
              </div>
              </>
              ) : null}
            </nav>

            {/* Rodape fixo: as duas acoes que o cliente procura com o menu ja
                aberto — falar com a loja e entrar/sair. Fica fora da area de
                rolagem para nao sumir no meio de uma lista longa. */}
            <div className="flex shrink-0 items-center border-t border-slate-100 bg-white px-2 py-1.5 pb-[calc(6px+env(safe-area-inset-bottom))]">
              {bestWhatsappDigits ? (
                <>
                  <a
                    href={`https://wa.me/${bestWhatsappDigits}`}
                    target="_blank"
                    rel="noopener noreferrer"
                    onClick={closeCategoryMenus}
                    className="flex flex-1 items-center justify-center gap-1.5 rounded-lg py-2 text-[12.5px] font-semibold text-slate-600 transition active:bg-slate-50"
                  >
                    <span className="shrink-0 text-[#25D366]">
                      <WhatsAppGlyph size={15} />
                    </span>
                    WhatsApp
                  </a>
                  <span aria-hidden className="h-4 w-px shrink-0 bg-slate-200" />
                </>
              ) : null}

              {loggedClient ? (
                <button
                  type="button"
                  onClick={() => {
                    closeCategoryMenus();
                    handleLogout();
                  }}
                  className="flex flex-1 items-center justify-center gap-1.5 rounded-lg py-2 text-[12.5px] font-semibold text-slate-600 transition active:bg-slate-50"
                >
                  <LogOut size={15} className="shrink-0 text-slate-400" />
                  Sair
                </button>
              ) : (
                <Link
                  href={`/${slug}/cliente/login`}
                  onClick={closeCategoryMenus}
                  className="flex flex-1 items-center justify-center gap-1.5 rounded-lg py-2 text-[12.5px] font-semibold text-slate-600 transition active:bg-slate-50"
                >
                  <User size={15} className="shrink-0 text-slate-400" />
                  Entrar
                </Link>
              )}
            </div>
          </motion.aside>
        </div>
      )}
      </AnimatePresence>

      {/* Footer */}
      {catalogThemeId === "default" ? (
      rodapeProprio ? (
        <RodapeProprioPadrao {...(propsDoRodapeProprio() as PropsDoRodape)} />
      ) : (
      <footer {...regiaoDoRodape} className="catalog-footer pt-10 pb-48 md:py-10" style={{ backgroundColor: footerPalette.bg || footerBg, color: footerPalette.text }}>
        <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
          <div className="grid grid-cols-1 md:grid-cols-3 gap-8">
            <div className="space-y-3">
              <div className="flex items-center gap-2">
                <Building2 className="w-5 h-5" />
                <h3 className="text-base font-bold">Empresa</h3>
              </div>
              <div className="space-y-2 text-sm" style={{ color: footerPalette.muted }}>
                <div className="font-semibold" style={{ color: footerPalette.text }}>{storeName}</div>
                {catalogShowDocument !== false && cnpj && <div>CNPJ: {cnpj}</div>}
                {address && (
                  <div className="flex items-start gap-2">
                    <MapPin className="w-4 h-4 mt-0.5" style={{ color: footerPalette.muted }} />
                    <span>{address}</span>
                  </div>
                )}
              </div>
            </div>

            <div className="space-y-3">
              <div className="flex items-center gap-2">
                <Phone className="w-5 h-5" />
                <h3 className="text-base font-bold">Contatos</h3>
              </div>
              <div className="space-y-2 text-sm" style={{ color: footerPalette.muted }}>
                {bestWhatsappDigits && (
                  <a
                    href={`https://wa.me/${bestWhatsappDigits}`}
                    target="_blank"
                    rel="noopener noreferrer"
                    className="inline-flex items-center gap-2 transition-colors"
                    style={{ color: footerPalette.text }}
                  >
                    <MessageCircle className="w-4 h-4" style={{ color: footerPalette.muted }} />
                    <span>WhatsApp</span>
                  </a>
                )}
                {phoneDigits && (
                  <a
                    href={`tel:${phoneDigits}`}
                    className="inline-flex items-center gap-2 transition-colors"
                    style={{ color: footerPalette.text }}
                  >
                    <Phone className="w-4 h-4" style={{ color: footerPalette.muted }} />
                    <span>Telefone</span>
                  </a>
                )}
              </div>
            </div>

            <div className="space-y-3">
              <div className="flex items-center gap-2">
                <h3 className="text-base font-bold">Redes Sociais</h3>
              </div>
              {socialLinks.length > 0 ? (
                <div className="flex items-center gap-3">
                  {socialLinks.map(({ key, href, label, Icon }) => (
                    <a
                      key={key}
                      href={href}
                      target="_blank"
                      rel="noopener noreferrer"
                      aria-label={label}
                      className="p-2 rounded-full transition-colors"
                      style={{ backgroundColor: footerPalette.subtleBg, color: footerPalette.text }}
                      onMouseEnter={(e) => { (e.currentTarget as HTMLAnchorElement).style.backgroundColor = footerPalette.subtleBgHover; }}
                      onMouseLeave={(e) => { (e.currentTarget as HTMLAnchorElement).style.backgroundColor = footerPalette.subtleBg; }}
                    >
                      <Icon className="w-5 h-5" />
                    </a>
                  ))}
                </div>
              ) : (
                <p className="text-sm" style={{ color: footerPalette.muted }}>Nenhuma rede cadastrada.</p>
              )}
            </div>
          </div>

          <div className="mt-10 pt-6 flex flex-col items-center gap-2 text-center" style={{ borderTop: `1px solid ${footerPalette.divider}` }}>
            <p className="text-xs" style={{ color: footerPalette.muted }}>
              &copy; {new Date().getFullYear()} Todos os direitos reservados.
            </p>
            <div className="flex items-center gap-1.5 text-xs" style={{ color: footerPalette.muted }}>
              <span>Tecnologia</span>
              <Link
                href="https://ktalogu.com.br"
                target="_blank"
                rel="noopener noreferrer"
                aria-label="Ktalogu"
                className="font-bold px-2 py-0.5 rounded-full inline-flex items-center"
                style={{ backgroundColor: footerPalette.chipBg }}
              >
                <Image
                  src="/brand-logo.svg"
                  alt="Ktalogu"
                  className="h-3.5 w-auto"
                  width={56}
                  height={14}
                  style={{
                    filter: footerPalette.isLightText
                      ? "brightness(0) invert(1) contrast(1.15)"
                      : "brightness(0) contrast(1.25)",
                  }}
                />
              </Link>
            </div>
          </div>
        </div>
      </footer>
      )
      ) : catalogThemeId === "vitrine" ? renderVitrineFooter() : null}

      {/*
        As notificacoes ficavam ao lado do botao do WhatsApp, com 4px de folga,
        e por cima da barra de compra. Agora empilham ACIMA do botao: sobra a
        largura inteira para o texto e nada disputa espaco com o "Comprar".
        Quando a loja nao tem WhatsApp o botao nao existe, entao elas descem.
      */}
      <div
        className={`pointer-events-none fixed z-[75] flex w-[min(330px,calc(100vw-2rem))] flex-col gap-2 ${
          catalogWhatsappDigits
            ? isProductPage
              ? "bottom-[calc(14.75rem+env(safe-area-inset-bottom))] md:bottom-[13.25rem]"
              : "bottom-[10.25rem] md:bottom-[5.75rem]"
            : isProductPage
              ? "bottom-[calc(10.5rem+env(safe-area-inset-bottom))] md:bottom-28"
              : "bottom-24 md:bottom-6"
        } ${socialProofPositionResolved === "right" ? "right-4 md:right-6" : "left-4 md:left-6"}`}
      >
        <AnimatePresence mode="popLayout" initial={false}>
          {socialProofEnabledResolved &&
            socialProofToasts.map((toast) => (
              <motion.div
                key={toast.id}
                layout
                initial={{ opacity: 0, y: 22, scale: 0.97 }}
                animate={{ opacity: 1, y: 0, scale: 1 }}
                exit={{ opacity: 0, y: 16, scale: 0.97 }}
                transition={{ duration: 0.26, ease: "easeOut" }}
                /* Arrasta para o lado e some, como notificacao de celular.
                   `dragSnapToOrigin` devolve o cartao ao lugar quando o gesto
                   nao chega ao limite, entao um toque torto nao o deixa
                   pendurado no meio do caminho. */
                drag="x"
                dragDirectionLock
                dragSnapToOrigin
                dragElastic={0.55}
                dragConstraints={{ left: 0, right: 0 }}
                onDragEnd={(_evento, info) => {
                  const passouDistancia = Math.abs(info.offset.x) > 90;
                  const passouVelocidade = Math.abs(info.velocity.x) > 420;
                  if (passouDistancia || passouVelocidade) dismissSocialProofToast(toast.id);
                }}
                className="pointer-events-auto cursor-grab overflow-hidden rounded-xl border border-slate-200/70 bg-white/95 shadow-[0_12px_28px_rgba(15,23,42,0.16)] backdrop-blur active:cursor-grabbing md:rounded-2xl md:shadow-[0_14px_36px_rgba(15,23,42,0.16)]"
              >
                <Link
                  href={`/${slug}/p/${toast.productId}`}
                  onClick={() => dismissSocialProofToast(toast.id)}
                  className="flex items-center gap-2.5 p-2.5 md:gap-3 md:p-3"
                  draggable={false}
                >
                  {toast.imageUrl ? (
                    <div className="h-10 w-10 overflow-hidden rounded-lg border border-slate-100 bg-slate-50 shrink-0 md:h-12 md:w-12 md:rounded-xl">
                      <Image
                        src={toast.imageUrl}
                        alt={toast.productName}
                        width={48}
                        height={48}
                        className="h-full w-full object-cover"
                        unoptimized
                      />
                    </div>
                  ) : (
                    <div className="h-10 w-10 rounded-lg border border-slate-100 bg-slate-50 text-slate-500 flex items-center justify-center shrink-0 md:h-12 md:w-12 md:rounded-xl">
                      <ShoppingBag size={16} />
                    </div>
                  )}
                  <div className="min-w-0">
                    <p className="text-[12px] font-semibold text-slate-900 leading-tight line-clamp-2 md:text-[13px]">
                      {toast.name} acabou de comprar {toast.productName}
                    </p>
                    <p className="mt-0.5 text-[10px] text-slate-500 md:mt-1 md:text-[11px]">há {toast.minutesAgo} min</p>
                  </div>
                </Link>
              </motion.div>
            ))}
        </AnimatePresence>
      </div>

      <AnimatePresence>
        {quickViewProduct && (
          <motion.div
            className="fixed inset-0 z-[100] flex items-center justify-center px-4"
            initial={{ opacity: 0 }}
            animate={{ opacity: 1 }}
            exit={{ opacity: 0 }}
          >
            <motion.button
              type="button"
              aria-label="Fechar"
              className="absolute inset-0 bg-black/60 backdrop-blur-sm"
              initial={{ opacity: 0 }}
              animate={{ opacity: 1 }}
              exit={{ opacity: 0 }}
              onClick={() => {
                setQuickViewProduct(null);
                setQuickViewActiveImageIndex(0);
              }}
            />
            <motion.div
              className="relative w-full max-w-[900px] max-h-[90vh] overflow-hidden rounded-2xl bg-white shadow-2xl flex flex-col md:flex-row"
              initial={{ opacity: 0, y: 20, scale: 0.95 }}
              animate={{ opacity: 1, y: 0, scale: 1 }}
              exit={{ opacity: 0, y: 20, scale: 0.95 }}
              transition={{ duration: 0.2 }}
            >
              <button
                type="button"
                onClick={() => {
                  setQuickViewProduct(null);
                  setQuickViewActiveImageIndex(0);
                }}
                className="absolute top-4 right-4 z-10 h-8 w-8 rounded-full bg-white/90 shadow-sm border border-gray-100 flex items-center justify-center text-gray-500 hover:text-gray-900 transition-colors"
              >
                <X size={18} />
              </button>
              
              <div className="w-full md:w-1/2 bg-gray-50 relative aspect-square md:aspect-auto md:h-[600px] flex flex-col items-center justify-center p-4">
                {(() => {
                  const images = quickViewProduct.product_images ? [...quickViewProduct.product_images].sort((a, b) => (a.sort_order || 0) - (b.sort_order || 0)) : [];
                  const mainImage = quickViewProduct.image_url;
                  const allImages = mainImage ? [{ id: 'main', image_url: mainImage }, ...images.filter(img => img.image_url !== mainImage)] : images;
                  
                  return allImages.length > 0 ? (
                    <>
                      <div className="relative w-full h-full max-h-[350px] md:max-h-[450px] mb-4">
                        <Image
                          src={allImages[quickViewActiveImageIndex]?.image_url || allImages[0].image_url}
                          alt={quickViewProduct.name}
                          fill
                          className="object-contain"
                          unoptimized
                        />
                      </div>
                      
                      {allImages.length > 1 && (
                        <div className="flex items-center gap-2 overflow-x-auto pb-2 px-2 w-full max-w-full hide-scrollbar snap-x">
                          {allImages.map((img, idx) => (
                            <button
                              key={img.id}
                              onClick={() => setQuickViewActiveImageIndex(idx)}
                              className={`relative w-16 h-16 shrink-0 rounded-lg overflow-hidden border-2 transition-all snap-start ${
                                idx === quickViewActiveImageIndex ? 'border-gray-900 opacity-100' : 'border-transparent opacity-60 hover:opacity-100'
                              }`}
                            >
                              <Image
                                src={img.image_url}
                                alt={`Thumb ${idx + 1}`}
                                fill
                                className="object-cover"
                                unoptimized
                              />
                            </button>
                          ))}
                        </div>
                      )}
                    </>
                  ) : (
                    <div className="w-full h-full flex items-center justify-center">
                      <ShoppingBag className="text-gray-300 w-16 h-16" />
                    </div>
                  );
                })()}
              </div>
              
              <div className="w-full md:w-1/2 p-6 md:p-8 flex flex-col overflow-y-auto md:h-[600px] custom-scrollbar">
                <div className="mb-4">
                  <h2 className="text-xl md:text-2xl font-bold text-gray-900 mb-2 leading-tight">
                    {quickViewProduct.name}
                  </h2>
                  <div className="inline-flex items-center rounded-full bg-gray-100 px-2.5 py-0.5 text-xs font-medium text-gray-600">
                    Ref: {quickViewProduct.id.slice(0, 8).toUpperCase()}
                  </div>
                </div>
                
                <div className="flex-1">
                  {quickViewProduct.product_kind === "digital" ? (
                    /* O digital não entra no carrinho: a compra rápida mora na
                       página dele, e entrega na hora. */
                    <div className="space-y-4">
                      <div className="inline-flex items-center gap-1.5 rounded-full bg-slate-900 px-3 py-1 text-xs font-semibold text-white">
                        <Download size={12} strokeWidth={2.5} />
                        Produto digital
                      </div>
                      <p className="text-sm leading-6 text-gray-600">
                        Você recebe na hora, nesta tela e no seu e-mail, assim que o pagamento for confirmado.
                      </p>
                      <Link
                        href={`/${slug}/p/${quickViewProduct.id}`}
                        className="inline-flex h-12 w-full items-center justify-center rounded-xl px-5 text-sm font-bold shadow-md transition-opacity hover:opacity-90"
                        style={{ backgroundColor: primaryPalette.base, color: getReadableTextColor(primaryPalette.base) }}
                      >
                        Ver e comprar
                      </Link>
                    </div>
                  ) : (
                  <ProductPurchaseCard 
                    product={{
                      ...quickViewProduct,
                      user_id: quickViewProduct.user_id || "",
                      product_images: quickViewProduct.product_images || [],
                      product_attributes: (quickViewProduct.product_attributes || []).map((attr: any) => ({
                        id: attr.name || '',
                        name: attr.name || '',
                        is_required: attr.is_required || false,
                        allow_multiple: false,
                        position: 0,
                        options: (attr.options || []).map((opt: any) => {
                          if (typeof opt === 'string') {
                            return { label: opt, price: 0 };
                          }
                          return {
                            label: opt.label || '',
                            price: opt.price || 0
                          };
                        })
                      }))
                    }}
                    whatsappNumber={whatsapp}
                    storeSlug={slug}
                    primaryColor={primaryPalette.base}
                  />
                  )}
                </div>
              </div>
            </motion.div>
          </motion.div>
        )}
      </AnimatePresence>

      <AnimatePresence>
        {isAuthModalOpen ? (
          <motion.div
            className="fixed inset-0 z-[90] flex items-center justify-center px-4"
            initial={{ opacity: 0 }}
            animate={{ opacity: 1 }}
            exit={{ opacity: 0 }}
          >
            <motion.button
              type="button"
              aria-label="Fechar"
              className="absolute inset-0 bg-black/55"
              initial={{ opacity: 0 }}
              animate={{ opacity: 1 }}
              exit={{ opacity: 0 }}
              onClick={closeAuthModal}
            />
            <motion.div
              className="relative w-full max-w-[420px] overflow-hidden rounded-3xl border border-zinc-200 bg-white shadow-[0_24px_70px_rgba(0,0,0,0.28)]"
              initial={{ opacity: 0, y: 18, scale: 0.98 }}
              animate={{ opacity: 1, y: 0, scale: 1 }}
              exit={{ opacity: 0, y: 18, scale: 0.98 }}
              transition={{ duration: 0.22, ease: "easeOut" }}
            >
              <div className="flex items-center justify-between gap-4 border-b border-zinc-100 px-5 py-4">
                <div className="min-w-0">
                  <div className="text-sm font-semibold text-zinc-900">Entrar na loja</div>
                  <div className="text-xs text-zinc-500 truncate">{storeName}</div>
                </div>
                <button
                  type="button"
                  onClick={closeAuthModal}
                  className="h-9 w-9 rounded-full border border-zinc-200 bg-white text-zinc-700 hover:bg-zinc-50 transition-colors inline-flex items-center justify-center"
                  aria-label="Fechar"
                >
                  <X size={18} />
                </button>
              </div>

              <div className="p-5">
                {visao.regras.modoDeCadastro === "closed" ? (
                  <p className="mb-4 rounded-2xl border border-zinc-200 bg-zinc-50 px-4 py-3 text-center text-xs text-zinc-600">
                    Esta loja libera o acesso por convite. Se você ainda não tem conta, peça o seu acesso à loja.
                  </p>
                ) : (
                <div className="mb-4 grid grid-cols-2 rounded-2xl border border-zinc-200 bg-zinc-50 p-1">
                  <button
                    type="button"
                    onClick={() => {
                      setAuthMode("login");
                      setAuthError("");
                      setAuthSuccess("");
                    }}
                    className="h-10 rounded-xl text-sm font-semibold transition-colors"
                    style={{
                      backgroundColor: authMode === "login" ? primaryPalette.base : "transparent",
                      color: authMode === "login" ? primaryPalette.text : "#52525b",
                    }}
                  >
                    Entrar
                  </button>
                  <button
                    type="button"
                    onClick={() => {
                      setAuthMode("register");
                      setAuthError("");
                      setAuthSuccess("");
                    }}
                    className="h-10 rounded-xl text-sm font-semibold transition-colors"
                    style={{
                      backgroundColor: authMode === "register" ? primaryPalette.base : "transparent",
                      color: authMode === "register" ? primaryPalette.text : "#52525b",
                    }}
                  >
                    Primeiro acesso
                  </button>
                </div>
                )}
                {visao.regras.mensagemDeLogin ? (
                  <p className="mb-3 rounded-2xl px-4 py-3 text-sm" style={{ backgroundColor: withAlpha(primaryPalette.base, 0.08), color: primaryPalette.onWhiteSurface }}>
                    {visao.regras.mensagemDeLogin}
                  </p>
                ) : null}

                {authSuccess ? (
                  <div className="mb-3 rounded-2xl border border-emerald-200 bg-emerald-50 px-4 py-3 text-sm text-emerald-800">
                    {authSuccess}
                  </div>
                ) : null}

                {authError ? (
                  <div className="mb-3 rounded-2xl border border-rose-200 bg-rose-50 px-4 py-3 text-sm text-rose-800">
                    {authError}
                  </div>
                ) : null}

                <button
                  type="button"
                  onClick={async () => {
                    if (authLoading) return;
                    setAuthLoading(true);
                    setAuthError("");
                    try {
                      /* O mesmo comeco da tela de entrar: em dominio proprio a
                         sessao volta para ca por uma passagem, com o carrinho. */
                      const { entrarComGoogle } = await import("@/lib/login-com-google");
                      await entrarComGoogle({ slug, next: window.location.pathname });
                    } catch (err) {
                      setAuthError("Não foi possível iniciar o login com Google.");
                      setAuthLoading(false);
                    }
                  }}
                  disabled={authLoading}
                  className="mb-6 flex w-full items-center justify-center gap-3 rounded-xl border border-zinc-200 bg-white py-3 text-sm font-medium text-zinc-700 transition-colors hover:bg-zinc-50 focus:outline-none focus:ring-2 focus:ring-zinc-200 focus:ring-offset-2 disabled:opacity-60"
                >
                  <svg aria-hidden="true" width="18" height="18" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg" className="shrink-0">
                    <path d="M23.5 12.27c0-.82-.07-1.61-.22-2.36H12v4.47h6.45a5.51 5.51 0 0 1-2.39 3.62v3h3.87c2.26-2.08 3.57-5.15 3.57-8.73z" fill="#4285F4" />
                    <path d="M12 24c3.24 0 5.96-1.07 7.95-2.9l-3.87-3A7.2 7.2 0 0 1 12 19.26a7.18 7.18 0 0 1-6.76-4.95H1.24v3.1A12 12 0 0 0 12 24z" fill="#34A853" />
                    <path d="M5.24 14.31A7.2 7.2 0 0 1 4.86 12c0-.8.14-1.58.38-2.31v-3.1H1.24A12 12 0 0 0 0 12c0 1.93.46 3.76 1.24 5.41l4-3.1z" fill="#FBBC05" />
                    <path d="M12 4.74c1.77 0 3.35.61 4.6 1.8l3.44-3.44C17.95 1.14 15.23 0 12 0 7.31 0 3.27 2.69 1.24 6.59l4 3.1A7.18 7.18 0 0 1 12 4.74z" fill="#EA4335" />
                  </svg>
                  Continuar com Google
                </button>

                <div className="mb-6 flex items-center gap-4">
                  <div className="h-px flex-1 bg-zinc-200" />
                  <span className="text-xs text-zinc-400">ou com e-mail/telefone</span>
                  <div className="h-px flex-1 bg-zinc-200" />
                </div>

                <form onSubmit={handleAuthSubmit} className="space-y-3">
                  {authMode === "register" ? (
                    <div className="space-y-3">
                      <label className="block">
                        <span className="text-[11px] font-semibold uppercase tracking-[0.18em] text-zinc-400">
                          Nome completo
                        </span>
                        <input
                          value={authName}
                          onChange={(e) => setAuthName(e.target.value)}
                          className="mt-1.5 h-12 w-full rounded-2xl border border-zinc-200 bg-white px-4 text-sm text-zinc-900 outline-none focus:ring-4 focus:ring-zinc-100"
                          placeholder="Como quer ser chamado?"
                          required
                        />
                      </label>
                      <label className="block">
                        <span className="text-[11px] font-semibold uppercase tracking-[0.18em] text-zinc-400">
                          CPF ou CNPJ
                        </span>
                        <input
                          value={authDocument}
                          onChange={(e) => setAuthDocument(formatCpfCnpj(e.target.value))}
                          className="mt-1.5 h-12 w-full rounded-2xl border border-zinc-200 bg-white px-4 text-sm text-zinc-900 outline-none focus:ring-4 focus:ring-zinc-100"
                          placeholder="Somente números ou formatado"
                          inputMode="numeric"
                          autoComplete="off"
                          required
                        />
                      </label>
                    </div>
                  ) : null}

                  <label className="block">
                    <span className="text-[11px] font-semibold uppercase tracking-[0.18em] text-zinc-400">
                      E-mail ou Telefone
                    </span>
                    <input
                      value={authIdentifier}
                      onChange={(e) => {
                        const next = e.target.value;
                        if (looksLikeEmail(next)) {
                          setAuthIdentifier(next);
                          return;
                        }
                        const nextDigits = digitsOnly(next);
                        if (nextDigits.length === 14) {
                          setAuthIdentifier(formatCpfCnpj(next));
                          return;
                        }
                        if (nextDigits.length === 11 && !looksLikePhone(nextDigits)) {
                          setAuthIdentifier(formatCpfCnpj(next));
                          return;
                        }
                        setAuthIdentifier(formatBrazilianPhone(next));
                      }}
                      onBlur={() => {
                        if (looksLikeEmail(authIdentifier)) setAuthIdentifier(normalizeEmail(authIdentifier));
                      }}
                      className="mt-1.5 h-12 w-full rounded-2xl border border-zinc-200 bg-white px-4 text-sm text-zinc-900 outline-none focus:ring-4 focus:ring-zinc-100"
                      placeholder="nome@email.com, (11) 99999-9999 ou CPF/CNPJ"
                      inputMode="text"
                      autoComplete={authMode === "login" ? "username" : "email"}
                      required
                    />
                  </label>

                  <label className="block">
                    <span className="text-[11px] font-semibold uppercase tracking-[0.18em] text-zinc-400">
                      Senha
                    </span>
                    <input
                      type="password"
                      value={authPassword}
                      onChange={(e) => setAuthPassword(e.target.value)}
                      className="mt-1.5 h-12 w-full rounded-2xl border border-zinc-200 bg-white px-4 text-sm text-zinc-900 outline-none focus:ring-4 focus:ring-zinc-100"
                      placeholder="Mínimo 8 caracteres"
                      minLength={8}
                      required
                    />
                  </label>

                  <button
                    type="submit"
                    disabled={authLoading}
                    className="mt-2 h-12 w-full rounded-2xl text-sm font-bold transition-all disabled:opacity-60"
                    style={{ backgroundColor: primaryPalette.base, color: primaryPalette.text }}
                  >
                    {authLoading ? "Aguarde..." : authMode === "login" ? "Entrar" : "Criar acesso"}
                  </button>
                </form>
              </div>
            </motion.div>
          </motion.div>
        ) : null}
      </AnimatePresence>

      {/*
        Botão flutuante do WhatsApp.

        Só aparece se a loja quiser: o número serve para o rodapé, a ficha do
        produto e o pedido, e nem toda loja quer o botão verde no canto — ainda
        mais quem atende pelo Ktalogu Chats, que já tem um balão ali. Vem ligado
        para ninguém perder o que já tinha.
      */}
      {catalogWhatsappDigits && whatsappFloat !== false && (
        <a
          data-flutuante-da-loja=""
          href={`https://wa.me/${catalogWhatsappDigits}`}
          target="_blank"
          rel="noopener noreferrer"
          /* Na pagina de produto existe a barra de compra fixa embaixo, e o
             botao ficava por cima do "Comprar". Aqui ele sobe acima dela.
             A reserva cobre a barra com a linha extra de combo, que e o caso
             mais alto que ela assume. */
          className={`fixed right-4 z-50 group inline-flex w-fit md:right-6 ${
            isProductPage
              ? "bottom-[calc(10.5rem+env(safe-area-inset-bottom))] md:bottom-28"
              : "bottom-24 md:bottom-6"
          }`}
          aria-label="Fale conosco no WhatsApp"
        >
          <span
            aria-hidden="true"
            className="pointer-events-none absolute -inset-2 rounded-full bg-[#25D366]/18 blur-lg animate-pulse"
          />
          <span
            aria-hidden="true"
            className="pointer-events-none absolute -inset-1 rounded-full bg-[#25D366]/20 animate-ping"
          />
          <span className="relative inline-flex items-center justify-center w-14 h-14 bg-[#16A34A] hover:bg-[#15803D] text-white rounded-full shadow-lg group-hover:shadow-xl transition-all group-hover:scale-[1.05] focus:outline-none focus-visible:ring-4 focus-visible:ring-[#25D366]/30">
            <WhatsAppGlyph size={28} />
          </span>
        </a>
      )}
    </div>
  );
}
