"use client";

import { useCallback, useEffect, useMemo, useRef, useState } from "react";
import Image from "next/image";
import Link from "next/link";
import { CheckCircle2, ChevronDown, Clock3, Download, ExternalLink, Info, Star } from "lucide-react";
import { AnimatePresence, motion } from "framer-motion";
import ProductPurchaseCard, { type BuyBarColors } from "@/components/ProductPurchaseCard";
import type { ProductCombo } from "@/components/ProductCombosWidget";
import ClientPortalFavoriteButton from "@/components/ClientPortalFavoriteButton";
import { getAccessibleAccent, normalizeHexColor, withAlpha } from "@/lib/color-contrast";
import {
  getPrimaryProductImageId,
  normalizeProductImages,
  type ProductImageItem,
} from "@/lib/product-images";

type ProductAttributeOption =
  | string
  | {
      label: string;
      price: number;
      stock?: number;
      is_required?: boolean;
      position?: number;
      image_id?: string | null;
    };

interface ProductShowcaseProps {
  product: {
    id: string;
    name: string;
    description?: string | null;
    price: number;
    image_url?: string | null;
    stock: number;
    track_inventory?: boolean | null;
    user_id: string;
    unit_type?: string | null;
    price_on_request?: 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;
    production_time_value?: number | null;
    production_time_unit?: "hours" | "days" | "business_days" | "weeks" | null;
    production_template_url?: string | null;
    production_template_name?: string | null;
    production_template_format?: "pdf" | "ai" | "cdr" | null;
    production_templates?: Array<{
      format?: "pdf" | "ai" | "cdr" | "canva" | null;
      url?: string | null;
      name?: string | null;
    }> | null;
    product_price_tiers?: Array<{
      min_qty: number;
      max_qty: number | null;
      unit_price: number;
      sort_order?: number | null;
      active?: boolean | null;
    }> | null;
    product_images?: Array<{
      id: string;
      image_url: string;
      sort_order?: number | null;
      is_primary?: boolean | null;
    }> | null;
    product_attributes?: Array<{
      id: string;
      name: string;
      options: ProductAttributeOption[];
      allow_multiple?: boolean | null;
      is_required?: boolean | null;
      position?: number | null;
      /* Como a vitrine desenha, e se ela mostra. */
      display_style?: string | null;
      show_in_store?: boolean | null;
    }> | null;
    product_variations?: Array<{
      id: string;
      combination: Record<string, string>;
      price: number | null;
      stock: number;
      sku?: string;
    }> | null;
    custom_fields_config?: Array<{
      id?: string | null;
      title?: string | null;
      field_type?: "text" | "textarea" | "number" | null;
      placeholder?: string | null;
      required?: boolean | null;
      variation_signature?: string | null;
      position?: number | null;
      active?: boolean | null;
    }> | null;
  };
  primaryColor: string;
  buyBarColors?: BuyBarColors | null;
  storeSlug: string;
  whatsappNumber?: string | null;
  categoryName: string;
  /* Para o link da categoria na trilha; sem ele, a categoria vira só texto. */
  categorySlug?: string | null;
  productDescriptionHtml: string;
  productTrustItems?: Array<{ icon?: string | null; title?: string | null }> | null;
  combosData?: ProductCombo[];
  loggedClient?: { id: string; name: string; avatar_url: string | null; favorites?: string[] | null } | null;
  isVitrine?: boolean;
  averageRating?: number;
  reviewCount?: number;
}

const TEMPLATE_ICON_SRC: Record<"ai" | "canva" | "cdr" | "pdf", string> = {
  ai: "/icons/templates/ai.svg",
  canva: "/icons/templates/canva.svg",
  cdr: "/icons/templates/cdr.svg",
  pdf: "/icons/templates/pdf.svg",
};

function formatProductionLeadTime(
  value: number | null,
  unit: "hours" | "days" | "business_days" | "weeks" | null | undefined
) {
  if (!Number.isFinite(value) || value === null || value <= 0 || !unit) return "";
  const normalizedValue = Number(value);
  const displayValue = Number.isInteger(normalizedValue)
    ? String(normalizedValue)
    : normalizedValue.toFixed(2).replace(/\.?0+$/, "");
  const singular = normalizedValue === 1;

  const label =
    unit === "hours"
      ? singular
        ? "hora"
        : "horas"
      : unit === "days"
        ? singular
          ? "dia corrido"
          : "dias corridos"
        : unit === "weeks"
          ? singular
            ? "semana"
            : "semanas"
          : singular
            ? "dia útil"
            : "dias úteis";

  return `${displayValue} ${label}`;
}

function getTemplateFormatLabel(format: "ai" | "canva" | "cdr" | "pdf") {
  return format === "ai"
    ? "Illustrator"
    : format === "canva"
      ? "Canva"
      : format === "cdr"
        ? "CorelDRAW"
        : "PDF";
}

export default function ProductShowcase({
  product,
  primaryColor,
  buyBarColors = null,
  storeSlug,
  whatsappNumber,
  categoryName,
  categorySlug,
  productDescriptionHtml,
  productTrustItems,
  combosData,
  loggedClient,
  isVitrine = false,
  averageRating = 0,
  reviewCount = 0,
}: ProductShowcaseProps) {
  const storeAccent = useMemo(() => normalizeHexColor(primaryColor, "#4F46E5"), [primaryColor]);
  const storeAccentSoft = useMemo(() => withAlpha(storeAccent, 0.1), [storeAccent]);
  const storeAccentBorder = useMemo(() => withAlpha(storeAccent, 0.2), [storeAccent]);
  /* Versao legivel da cor da loja para texto e icone sobre fundo claro: a cor
     crua some quando o lojista escolhe um tom pastel. */
  const storeAccentText = useMemo(
    () => getAccessibleAccent(storeAccent, "#FFFFFF", { minRatio: 4.5 }),
    [storeAccent]
  );
  const productionTimeLabel = useMemo(() => {
    const rawValue = Number(product.production_time_value);
    if (!Number.isFinite(rawValue) || rawValue <= 0) return "";
    return formatProductionLeadTime(rawValue, product.production_time_unit);
  }, [product.production_time_unit, product.production_time_value]);

  const productionTemplates = useMemo(() => {
    const source = Array.isArray(product.production_templates) ? product.production_templates : [];
    const normalized = source
      .map((item) => {
        const format =
          item?.format === "ai" || item?.format === "canva" || item?.format === "cdr" || item?.format === "pdf"
            ? item.format
            : null;
        const url = typeof item?.url === "string" ? item.url.trim() : "";
        const name = typeof item?.name === "string" ? item.name.trim() : "";
        if (!format || !url) return null;
        return { format, url, name: name || "Gabarito" };
      })
      .filter(
        (item): item is { format: "pdf" | "ai" | "cdr" | "canva"; url: string; name: string } => Boolean(item)
      );

    if (normalized.length > 0) {
      const order = { ai: 0, canva: 1, cdr: 2, pdf: 3 } as const;
      return normalized.sort((a, b) => order[a.format] - order[b.format]);
    }

    if (product.production_template_url) {
      return [
        {
          format: product.production_template_format || "pdf",
          url: product.production_template_url,
          name: product.production_template_name || "Gabarito",
        },
      ];
    }

    return [];
  }, [
    product.production_template_format,
    product.production_template_name,
    product.production_template_url,
    product.production_templates,
  ]);
  const [isTemplateMenuOpen, setIsTemplateMenuOpen] = useState(false);
  const [isProductionInfoOpen, setIsProductionInfoOpen] = useState(false);
  const [isTemplateInfoOpen, setIsTemplateInfoOpen] = useState(false);
  const templateMenuRef = useRef<HTMLDivElement | null>(null);
  const productionInfoRef = useRef<HTMLDivElement | null>(null);
  const templateInfoRef = useRef<HTMLDivElement | null>(null);
  const templateMenuOpen = productionTemplates.length > 0 && isTemplateMenuOpen;

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

    function handlePointerDown(event: MouseEvent) {
      if (!templateMenuRef.current?.contains(event.target as Node)) {
        setIsTemplateMenuOpen(false);
      }
    }

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

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

    function handlePointerDown(event: MouseEvent) {
      if (!productionInfoRef.current?.contains(event.target as Node)) {
        setIsProductionInfoOpen(false);
      }
    }

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

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

    function handlePointerDown(event: MouseEvent) {
      if (!templateInfoRef.current?.contains(event.target as Node)) {
        setIsTemplateInfoOpen(false);
      }
    }

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

  const galleryImages = useMemo(
    () => normalizeProductImages(product.product_images, product.image_url),
    [product.product_images, product.image_url]
  );

  const defaultImageId = useMemo(() => getPrimaryProductImageId(galleryImages), [galleryImages]);
  const [activeImageId, setActiveImageId] = useState<string | null>(defaultImageId);
  const [preferredImageId, setPreferredImageId] = useState<string | null>(null);
  const [isGalleryHovered, setIsGalleryHovered] = useState(false);
  const [slideDirection, setSlideDirection] = useState<1 | -1>(1);

  const activeImage = useMemo(() => {
    if (!galleryImages.length) return null;
    return (
      galleryImages.find((image) => image.id === activeImageId) ||
      galleryImages.find((image) => image.is_primary) ||
      galleryImages[0]
    );
  }, [activeImageId, galleryImages]);

  const imageById = useMemo(() => {
    const map = new Map<string, ProductImageItem>();
    galleryImages.forEach((image) => map.set(image.id, image));
    return map;
  }, [galleryImages]);

  const imageIndexById = useMemo(() => {
    const map = new Map<string, number>();
    galleryImages.forEach((image, index) => map.set(image.id, index));
    return map;
  }, [galleryImages]);

  const changeActiveImage = useCallback(
    (nextImageId: string | null, directionHint?: 1 | -1) => {
      setActiveImageId((currentImageId) => {
        if (currentImageId === nextImageId) return currentImageId;

        const currentIndex = currentImageId ? (imageIndexById.get(currentImageId) ?? -1) : -1;
        const nextIndex = nextImageId ? (imageIndexById.get(nextImageId) ?? -1) : -1;
        const nextDirection =
          directionHint ?? (currentIndex >= 0 && nextIndex >= 0 && nextIndex < currentIndex ? -1 : 1);

        setSlideDirection(nextDirection);
        return nextImageId;
      });
    },
    [imageIndexById]
  );

  const handlePreferredImageChange = useCallback(
    (imageId: string | null) => {
      if (!imageId) {
        setPreferredImageId(null);
        changeActiveImage(defaultImageId);
        return;
      }
      if (imageById.has(imageId)) {
        setPreferredImageId(imageId);
        changeActiveImage(imageId);
      }
    },
    [changeActiveImage, defaultImageId, imageById]
  );

  const hasLockedPreferredImage = Boolean(preferredImageId && imageById.has(preferredImageId));
  const shouldAutoPlay = galleryImages.length > 1 && !hasLockedPreferredImage && !isGalleryHovered;

  useEffect(() => {
    if (!shouldAutoPlay) return;
    const timer = window.setInterval(() => {
      setActiveImageId((currentImageId) => {
        if (!galleryImages.length) return null;
        const currentIndex = galleryImages.findIndex((image) => image.id === currentImageId);
        const fallbackIndex = galleryImages.findIndex((image) => image.id === defaultImageId);
        const safeIndex = currentIndex >= 0 ? currentIndex : fallbackIndex >= 0 ? fallbackIndex : 0;
        const nextIndex = (safeIndex + 1) % galleryImages.length;
        setSlideDirection(1);
        return galleryImages[nextIndex]?.id || galleryImages[0]?.id || null;
      });
    }, 3500);

    return () => window.clearInterval(timer);
  }, [shouldAutoPlay, galleryImages, defaultImageId]);

  const productHeader = (
    <div>
      {/*
        A trilha, no lugar do antigo selo de categoria: dizia a mesma coisa e
        ocupava mais. Aqui ela também leva de volta — para a loja e para a
        categoria — sem gastar a primeira dobra da página.
      */}
      <nav aria-label="Você está em" className={`flex min-w-0 items-center gap-1.5 text-[12px] text-zinc-500 ${isVitrine ? "mb-3" : "mb-2"}`}>
        <Link href={`/${storeSlug}`} className="shrink-0 transition-colors hover:text-zinc-900">
          Início
        </Link>
        <span className="shrink-0 text-zinc-300">›</span>
        {categorySlug ? (
          <Link href={`/${storeSlug}/c/${categorySlug}`} className="shrink-0 transition-colors hover:text-zinc-900">
            {categoryName}
          </Link>
        ) : (
          <span className="shrink-0">{categoryName}</span>
        )}
        <span className="shrink-0 text-zinc-300">›</span>
        <span className="min-w-0 truncate font-medium text-zinc-700">{product.name}</span>
        {product.unit_type === "square_meter" && (
          <span className="ml-1 shrink-0 rounded-full border border-zinc-200 bg-white px-1.5 py-0.5 text-[10px] font-bold uppercase text-zinc-700">
            m²
          </span>
        )}
      </nav>
      <h1
        className={
          isVitrine
            ? "w-full max-w-none text-[2.2rem] font-semibold leading-[0.96] tracking-[-0.04em] text-gray-950 sm:text-[2.8rem] md:text-[3.5rem] lg:text-[4.25rem]"
            : "text-3xl md:text-4xl font-black text-gray-900 leading-tight mb-2"
        }
        style={isVitrine ? { fontFamily: "var(--ks-catalog-font-heading, var(--ks-font-editorial))" } : undefined}
      >
        {product.name}
      </h1>
      <div className={`flex items-center gap-2 text-sm text-yellow-500 ${isVitrine ? "mt-4 mb-0" : "mb-4"}`}>
        <div className="flex">
          {Array.from({ length: 5 }).map((_, index) => {
            const filled = index + 1 <= Math.round(averageRating || 0);
            return (
              <Star
                key={index}
                size={16}
                className={filled ? "fill-current" : "text-zinc-300"}
                fill={filled ? "currentColor" : "none"}
              />
            );
          })}
        </div>
        <span className="text-gray-400 font-medium flex items-center gap-1 ml-2">
          <CheckCircle2 size={14} className="text-[var(--ks-color-success)]" />
          {reviewCount > 0 ? `${reviewCount} avalia${reviewCount === 1 ? "ção" : "ções"}` : "Produto verificado"}
        </span>
      </div>
    </div>
  );

  return (
    <div className="catalog-product-showcase">
      {isVitrine && (
        <div className="mb-8 md:mb-10">
          {productHeader}
        </div>
      )}
      <div className="grid grid-cols-1 md:grid-cols-[minmax(0,1fr)_minmax(0,1fr)] gap-8 lg:gap-16 items-start">
      <div
        className="w-full relative group md:sticky md:top-[calc(var(--ks-announcement-offset,0px)+180px)] lg:top-[calc(var(--ks-announcement-offset,0px)+200px)]"
        onMouseEnter={() => setIsGalleryHovered(true)}
        onMouseLeave={() => setIsGalleryHovered(false)}
      >
        <div className="catalog-product-gallery aspect-square w-full bg-white rounded-3xl shadow-sm border border-gray-100 overflow-hidden relative z-10">
          <AnimatePresence initial={false} custom={slideDirection}>
            {activeImage ? (
              <motion.div
                key={activeImage.id}
                custom={slideDirection}
                initial={{ x: slideDirection > 0 ? "16%" : "-16%", opacity: 0 }}
                animate={{ x: "0%", opacity: 1 }}
                exit={{ x: slideDirection > 0 ? "-16%" : "16%", opacity: 0 }}
                transition={{
                  x: { duration: 0.45, ease: [0.22, 1, 0.36, 1] },
                  opacity: { duration: 0.28, ease: "easeOut" },
                }}
                className="absolute inset-0"
              >
                <Image
                  src={activeImage.image_url}
                  alt={product.name}
                  className="w-full h-full object-cover group-hover:scale-105 transition-transform duration-500"
                  fill
                  sizes="(max-width: 768px) 100vw, 50vw"
                  unoptimized
                />
              </motion.div>
            ) : (
              <div className="w-full h-full flex items-center justify-center bg-gray-50 text-gray-300">
                <span className="text-sm">Sem imagem</span>
              </div>
            )}
          </AnimatePresence>
          
          <ClientPortalFavoriteButton
            productId={product.id}
            clientId={loggedClient?.id}
            initialFavorites={loggedClient?.favorites}
            primaryColor={primaryColor}
            onRequireLogin={(productId) => {
              if (typeof window !== "undefined") {
                window.dispatchEvent(
                  new CustomEvent("ks_require_login", {
                    detail: { intent: { type: "favorite_product", productId } },
                  })
                );
              }
            }}
          />

          {product.track_inventory !== false && product.stock <= 0 && (
            <div className="absolute inset-0 bg-white/60 backdrop-blur-[2px] flex items-center justify-center z-20">
              <span className="bg-black text-white text-sm font-bold px-4 py-2 rounded-full uppercase tracking-wider">
                Esgotado
              </span>
            </div>
          )}
        </div>

        {galleryImages.length > 1 && (
          <div className="mt-3 grid grid-cols-7 gap-2 md:gap-3">
            {galleryImages.map((image, index) => {
              const isActive = image.id === activeImage?.id;
              return (
                <button
                  key={image.id}
                  type="button"
                  onClick={() => {
                    setPreferredImageId(null);
                    changeActiveImage(image.id);
                  }}
                  className={`relative aspect-square overflow-hidden rounded-lg md:rounded-xl border transition-all ${
                    isActive
                      ? "border-[var(--ks-color-primary)] ring-2 ring-[var(--ks-color-primary)]/25"
                      : "border-gray-200 hover:border-gray-300"
                  }`}
                  title={`Imagem ${index + 1}`}
                >
                  <Image
                    src={image.image_url}
                    alt={`${product.name} ${index + 1}`}
                    fill
                    sizes="100px"
                    className="object-cover"
                    unoptimized
                  />
                </button>
              );
            })}
          </div>
        )}

        <div
          className="absolute -inset-4 bg-gradient-to-tr opacity-20 blur-2xl rounded-full -z-0 pointer-events-none"
          style={{ backgroundImage: `linear-gradient(to top right, ${primaryColor}, transparent)` }}
        />
      </div>

      <div className="flex flex-col gap-6 pt-2 min-w-0">
        {!isVitrine && <div>{productHeader}</div>}

        <div className="pt-1">
          <ProductPurchaseCard
            product={product}
            primaryColor={primaryColor}
            buyBarColors={buyBarColors}
            storeSlug={storeSlug}
            stickyFooter
            whatsappNumber={whatsappNumber}
            onPreferredImageChange={handlePreferredImageChange}
            trustItems={productTrustItems}
            combosData={combosData}
          />
        </div>

        {(productionTimeLabel || productionTemplates.length > 0) && (
          <section className="border-t border-zinc-200 pt-6">
            <div className={`grid gap-y-6 ${productionTimeLabel && productionTemplates.length > 0 ? "md:grid-cols-2 md:items-stretch" : ""}`}>
              {productionTimeLabel ? (
                <div className={`relative flex flex-col py-2 ${productionTemplates.length > 0 ? "md:pr-8" : ""}`}>
                  <div className="pointer-events-none absolute inset-0 overflow-hidden">
                    <div className="absolute right-2 top-1/2 -translate-y-1/2 translate-x-[18%] opacity-[0.07]">
                      <Clock3 size={92} style={{ color: storeAccent, transform: "rotate(15deg)" }} />
                    </div>
                  </div>

                  <div className="relative z-20 flex items-start gap-3">
                    <span
                      className="inline-flex h-10 w-10 shrink-0 items-center justify-center rounded-full"
                      style={{ backgroundColor: storeAccentSoft, color: storeAccentText }}
                    >
                      <Clock3 size={18} />
                    </span>
                    <div className="min-w-0 flex items-center gap-2 mt-2">
                      <p className="text-base font-semibold tracking-[-0.02em] text-zinc-950">
                        Prazo de produção
                      </p>
                      <div
                        ref={productionInfoRef}
                        className="relative"
                        onMouseEnter={() => setIsProductionInfoOpen(true)}
                        onMouseLeave={() => setIsProductionInfoOpen(false)}
                      >
                        <button
                          type="button"
                          aria-label="Informações sobre o prazo"
                          onClick={() => setIsProductionInfoOpen((current) => !current)}
                          className="inline-flex items-center justify-center rounded-full transition-opacity hover:opacity-80"
                          style={{ color: storeAccentText }}
                        >
                          <Info size={15} />
                        </button>

                        {isProductionInfoOpen ? (
                          <div
                            className="absolute left-1/2 top-[calc(100%+10px)] z-50 w-[280px] -translate-x-1/2 rounded-2xl border bg-white p-3 text-left shadow-[0_20px_50px_-26px_rgba(15,23,42,0.42)]"
                            style={{ borderColor: withAlpha(storeAccent, 0.18) }}
                          >
                            <p className="text-xs leading-5 text-zinc-600">
                              Este prazo é estimado e pode variar conforme a complexidade do pedido, acabamentos,
                          quantidade e aprovação da arte. O prazo de entrega final depende do frete selecionado no pedido.
                            </p>
                          </div>
                        ) : null}
                      </div>
                    </div>
                  </div>

                  {/* O valor fica logo abaixo do titulo e alinhado com ele. Antes
                      ficava centralizado 28px mais abaixo, dentro de um bloco de
                      altura minima: sobrava um buraco entre o titulo e o numero, e
                      a coluna do gabarito, alinhada a esquerda, nao conversava com
                      ele. */}
                  <div className="relative z-10 mt-2 pl-[52px]">
                    <div
                      className="text-[1.3rem] font-semibold leading-tight tracking-[-0.04em]"
                      style={{ color: storeAccentText }}
                    >
                      {productionTimeLabel}
                    </div>
                    <p className="mt-1 text-xs text-zinc-500">até o pedido ficar pronto para envio</p>
                  </div>
                </div>
              ) : null}

              {productionTemplates.length > 0 ? (
                <div className={`flex flex-col py-2 ${productionTimeLabel ? "md:border-l md:border-zinc-200 md:pl-8" : ""}`}>
                  <div ref={templateMenuRef} className="relative">
                    <div>
                      <div className="flex items-center gap-2">
                        <p className="text-[1.02rem] font-semibold tracking-[-0.03em] text-zinc-950">
                          Utilize o gabarito
                        </p>
                        <div
                          ref={templateInfoRef}
                          className="relative"
                          onMouseEnter={() => setIsTemplateInfoOpen(true)}
                          onMouseLeave={() => setIsTemplateInfoOpen(false)}
                        >
                          <button
                            type="button"
                            aria-label="Informações sobre o gabarito"
                            onClick={() => setIsTemplateInfoOpen((current) => !current)}
                            className="inline-flex items-center justify-center rounded-full transition-opacity hover:opacity-80"
                            style={{ color: storeAccentText }}
                          >
                            <Info size={15} />
                          </button>

                          {isTemplateInfoOpen ? (
                            <div
                              className="absolute left-1/2 top-[calc(100%+10px)] z-50 w-[260px] -translate-x-1/2 rounded-2xl border bg-white p-3 text-left shadow-[0_20px_50px_-26px_rgba(15,23,42,0.42)]"
                              style={{ borderColor: withAlpha(storeAccent, 0.18) }}
                            >
                              <p className="text-xs leading-5 text-zinc-600">
                                Baixe o gabarito do software de sua preferência para enviar seus arquivos no nosso padrão.
                              </p>
                            </div>
                          ) : null}
                        </div>
                      </div>
                      <p className="mt-1 text-xs text-zinc-500">Escolha o formato para baixar</p>

                      <button
                        type="button"
                        onClick={() => setIsTemplateMenuOpen((current) => !current)}
                        className="group mt-4 flex w-full items-center justify-between gap-4 text-left transition-all"
                      >
                        <div className="flex shrink-0 items-center gap-2.5">
                          {productionTemplates.slice(0, 4).map((template) => (
                            <Image
                              key={template.format}
                              src={TEMPLATE_ICON_SRC[template.format]}
                              alt={getTemplateFormatLabel(template.format)}
                              width={28}
                              height={28}
                              className="h-7 w-7 object-contain"
                            />
                          ))}
                        </div>
                        <ChevronDown
                          size={18}
                          className={`shrink-0 text-zinc-500 transition-transform ${templateMenuOpen ? "rotate-180" : ""}`}
                        />
                      </button>
                    </div>

                    {templateMenuOpen ? (
                      <div
                        className="absolute left-0 top-[calc(100%+10px)] z-20 w-full overflow-hidden rounded-2xl border bg-white p-2 shadow-[0_26px_60px_-28px_rgba(15,23,42,0.4)]"
                        style={{ borderColor: storeAccentBorder }}
                      >
                        <div className="space-y-1.5">
                          {productionTemplates.map((template) => {
                            const label = getTemplateFormatLabel(template.format);
                            return (
                              <a
                                key={template.format}
                                href={template.url}
                                target="_blank"
                                rel="noreferrer"
                                download={template.format === "canva" ? undefined : true}
                                onClick={() => {
                                  setIsTemplateMenuOpen(false);
                                }}
                                className="flex w-full items-center gap-3 rounded-xl px-3 py-2.5 text-left transition-colors hover:bg-zinc-50"
                              >
                                <Image
                                  src={TEMPLATE_ICON_SRC[template.format]}
                                  alt={label}
                                  width={32}
                                  height={32}
                                  className="h-8 w-8 shrink-0 object-contain"
                                />
                                <div className="min-w-0 flex-1">
                                  <p className="text-sm font-semibold text-zinc-900">{label}</p>
                                  <p className="truncate text-xs text-zinc-500">
                                    {template.format === "canva" ? "Abre em outra aba" : "Disponível para download"}
                                  </p>
                                </div>
                                {template.format === "canva" ? (
                                  <ExternalLink size={16} style={{ color: storeAccentText }} className="shrink-0" />
                                ) : (
                                  <Download size={16} style={{ color: storeAccentText }} className="shrink-0" />
                                )}
                              </a>
                            );
                          })}
                        </div>
                      </div>
                    ) : null}
                  </div>
                </div>
              ) : null}
            </div>
          </section>
        )}

        <section className="mt-6 border-t border-zinc-200 pt-8">
          <h3 className="text-[1.15rem] font-semibold tracking-[-0.03em] text-zinc-950">
            Detalhes
          </h3>
          <div className="mt-4 max-w-none text-[15px] leading-7 text-zinc-700 [&_h1]:mt-8 [&_h1]:text-2xl [&_h1]:font-semibold [&_h1]:tracking-[-0.03em] [&_h1]:text-zinc-950 [&_h2]:mt-8 [&_h2]:text-[1.35rem] [&_h2]:font-semibold [&_h2]:tracking-[-0.03em] [&_h2]:text-zinc-950 [&_h3]:mt-6 [&_h3]:text-lg [&_h3]:font-semibold [&_h3]:text-zinc-900 [&_p]:my-0 [&_p+*]:mt-4 [&_ul]:mt-4 [&_ul]:list-disc [&_ul]:pl-5 [&_ol]:mt-4 [&_ol]:list-decimal [&_ol]:pl-5 [&_li]:mt-1.5 [&_strong]:font-semibold [&_strong]:text-zinc-950 [&_a]:text-zinc-950 [&_a]:underline [&_blockquote]:mt-4 [&_blockquote]:border-l-2 [&_blockquote]:border-zinc-200 [&_blockquote]:pl-4 [&_blockquote]:text-zinc-600">
            {productDescriptionHtml ? (
              <div dangerouslySetInnerHTML={{ __html: productDescriptionHtml }} />
            ) : (
              <p>Este produto ainda não possui descrição detalhada.</p>
            )}
          </div>
        </section>
      </div>
      </div>

    </div>
  );
}
