"use client";

import Image from "next/image";
import { useEffect, useId, useMemo, useRef, useState } from "react";
import { AnimatePresence, motion } from "framer-motion";
import { Toaster, toast } from "sonner";
import { useRouter } from "next/navigation";
import {
  BadgeCheck,
  CheckCircle2,
  Copy,
  CreditCard,
  Hand,
  HelpCircle,
  Lock,
  RefreshCcw,
  ReceiptText,
  ShieldCheck,
  UserRound,
  X,
} from "lucide-react";
import {
  normalizeGuestProfile,
  normalizeText,
  paymentLinkRecurrenceLabel,
  type PaymentLinkPublicData,
} from "@/lib/payment-links";
import { formatDocument, getDocumentLabel, validateBrazilianDocument } from "@/lib/document-utils";
import { getAccessibleAccent, getReadableTextColor } from "@/lib/color-contrast";

type StatusMessage = {
  type: "success" | "error";
  text: string;
};

type PaymentSession = {
  paymentId: string;
  environment: "sandbox" | "production";
  publicKey: string;
  amount: number;
  payer: {
    name?: string | null;
    email?: string | null;
    document?: string | null;
  };
};

type PaymentResult = {
  catalogPaymentId?: string | null;
  providerPaymentId?: string | null;
  status?: string | null;
  statusDetail?: string | null;
  paymentMethod?: string | null;
  qrCode?: string | null;
  qrCodeBase64?: string | null;
  ticketUrl?: string | null;
};

type LinkedClient = {
  id: string;
  name: string | null;
  company_name: string | null;
  email: string | null;
  document: string | null;
  phone: string | null;
};

type LinkedItem = {
  productId: string;
  name: string;
  quantity: number;
  unitPrice: number | null;
  priceOnRequest: boolean;
  imageUrl: string;
};

function formatLinkedClientName(client: LinkedClient) {
  const name = normalizeText(client.name);
  const company = normalizeText(client.company_name);
  if (name && company && normalizeText(name).toLowerCase() !== normalizeText(company).toLowerCase()) {
    return `${name} (${company})`;
  }
  return name || company || "Cliente";
}

function formatMoney(value: number) {
  return new Intl.NumberFormat("pt-BR", { style: "currency", currency: "BRL" }).format(value || 0);
}

function hexToRgba(hex: string, alpha: number) {
  const value = normalizeText(hex).replace("#", "");
  const safeAlpha = Math.min(1, Math.max(0, alpha));
  if (value.length !== 6) return `rgba(0,0,0,${safeAlpha})`;
  const r = Number.parseInt(value.slice(0, 2), 16);
  const g = Number.parseInt(value.slice(2, 4), 16);
  const b = Number.parseInt(value.slice(4, 6), 16);
  if (!Number.isFinite(r) || !Number.isFinite(g) || !Number.isFinite(b)) return `rgba(0,0,0,${safeAlpha})`;
  return `rgba(${r},${g},${b},${safeAlpha})`;
}

function formatPhone(value: string) {
  const digits = value.replace(/\D/g, "").slice(0, 11);
  if (digits.length <= 2) return digits ? `(${digits}` : "";
  if (digits.length <= 7) return `(${digits.slice(0, 2)}) ${digits.slice(2)}`;
  if (digits.length <= 10) return `(${digits.slice(0, 2)}) ${digits.slice(2, 6)}-${digits.slice(6)}`;
  return `(${digits.slice(0, 2)}) ${digits.slice(2, 7)}-${digits.slice(7)}`;
}

function buildApprovedRedirectUrl(code: string, paymentId: string) {
  return `/lp/${encodeURIComponent(code)}/sucesso?paymentId=${encodeURIComponent(paymentId)}`;
}

function getPaymentStatusMessage(status?: string | null, paymentMethod?: string | null) {
  if (status === "approved") return "Pagamento aprovado com sucesso.";
  if (status === "pending") return paymentMethod === "pix" ? "Pix gerado. Aguarde a confirmacao do pagamento." : "Pagamento em analise.";
  if (status === "rejected") return "Nao foi possivel aprovar o pagamento. Revise os dados e tente novamente.";
  if (status === "cancelled") return "Pagamento cancelado. Tente novamente.";
  return "Nao foi possivel confirmar o pagamento.";
}

function PixIcon({ className, size = 16 }: { className?: string; size?: number }) {
  return (
    <svg
      width={size}
      height={size}
      viewBox="0 0 18 18"
      fill="currentColor"
      className={className}
      xmlns="http://www.w3.org/2000/svg"
    >
      <path d="M11.917 11.71a2.046 2.046 0 0 1-1.454-.602l-2.1-2.1a.4.4 0 0 0-.551 0l-2.108 2.108a2.044 2.044 0 0 1-1.454.602h-.414l2.66 2.66c.83.83 2.177.83 3.007 0l2.667-2.668h-.253zM4.25 4.282c.55 0 1.066.214 1.454.602l2.108 2.108a.39.39 0 0 0 .552 0l2.1-2.1a2.044 2.044 0 0 1 1.453-.602h.253L9.503 1.623a2.127 2.127 0 0 0-3.007 0l-2.66 2.66h.414z" />
      <path d="m14.377 6.496-1.612-1.612a.307.307 0 0 1-.114.023h-.733c-.379 0-.75.154-1.017.422l-2.1 2.1a1.005 1.005 0 0 1-1.425 0L5.268 5.32a1.448 1.448 0 0 0-1.018-.422h-.9a.306.306 0 0 1-.109-.021L1.623 6.496c-.83.83-.83 2.177 0 3.008l1.618 1.618a.305.305 0 0 1 .108-.022h.901c.38 0 .75-.153 1.018-.421L7.375 8.57a1.034 1.034 0 0 1 1.426 0l2.1 2.1c.267.268.638.421 1.017.421h.733c.04 0 .079.01.114.024l1.612-1.612c.83-.83.83-2.178 0-3.008z" />
    </svg>
  );
}

function getPaymentMethodCards(link: PaymentLinkPublicData) {
  const cardEnabled = link.type === "subscription" ? true : link.allowCreditCard;
  const pixEnabled = link.type === "subscription" ? false : link.allowPix;
  const boletoEnabled = link.type === "subscription" ? false : link.allowBoleto;

  return [
    {
      id: "bank_transfer",
      title: "Pix",
      icon: PixIcon,
      enabled: pixEnabled,
    },
    {
      id: "credit_card",
      title: "Cartao de Credito",
      icon: CreditCard,
      enabled: cardEnabled,
    },
    {
      id: "ticket",
      title: "Boleto",
      icon: ReceiptText,
      enabled: boletoEnabled,
    },
  ] as const;
}

const inputClass =
  "h-12 w-full rounded-md border border-slate-200 bg-white px-4 text-sm text-slate-900 outline-none transition focus:border-slate-900 shadow-sm";

let mercadoPagoScriptPromise: Promise<void> | null = null;

function loadMercadoPagoScript() {
  if (typeof window === "undefined") return Promise.resolve();
  const anyWindow = window as unknown as { MercadoPago?: unknown };
  if (anyWindow.MercadoPago) return Promise.resolve();
  if (mercadoPagoScriptPromise) return mercadoPagoScriptPromise;

  mercadoPagoScriptPromise = new Promise<void>((resolve, reject) => {
    const existing = document.querySelector('script[src="https://sdk.mercadopago.com/js/v2"]');
    if (existing) {
      existing.addEventListener("load", () => resolve());
      existing.addEventListener("error", () => reject(new Error("Nao foi possivel carregar o SDK do Mercado Pago.")));
      return;
    }

    const script = document.createElement("script");
    script.src = "https://sdk.mercadopago.com/js/v2";
    script.async = true;
    script.onload = () => {
      resolve();
    };
    script.onerror = () => {
      reject(new Error("Nao foi possivel carregar o SDK do Mercado Pago."));
    };
    document.body.appendChild(script);
  });

  return mercadoPagoScriptPromise;
}

function detectDocumentType(documentDigits: string) {
  return documentDigits.replace(/\D/g, "").length === 14 ? "CNPJ" : "CPF";
}

function extractMercadoPagoErrorMessage(error: unknown) {
  if (!error) return "";
  if (typeof error === "string") return error;
  if (error instanceof Error) return error.message;

  if (typeof error === "object") {
    const record = error as Record<string, unknown>;
    const message = typeof record.message === "string" ? record.message : "";
    const statusMessage = typeof record.status_message === "string" ? record.status_message : "";
    const errorText = typeof record.error === "string" ? record.error : "";
    const cause = Array.isArray(record.cause) ? (record.cause as Array<Record<string, unknown>>) : [];
    const causeEntry = cause[0] || null;
    const causeCode = causeEntry && typeof causeEntry.code === "string" ? causeEntry.code : "";
    const causeDescription =
      causeEntry && typeof causeEntry.description === "string"
        ? causeEntry.description
        : causeEntry && typeof causeEntry.message === "string"
          ? causeEntry.message
          : "";

    const combined = [causeCode && causeDescription ? `${causeCode}: ${causeDescription}` : "", causeDescription, message, statusMessage, errorText]
      .map((value) => normalizeText(value))
      .find(Boolean);
    if (combined) return combined;

    try {
      const json = JSON.stringify(record);
      return json.length > 400 ? json.slice(0, 400) : json;
    } catch {
      return "";
    }
  }

  return "";
}

function normalizeClientFacingErrorMessage(message: string) {
  const normalized = String(message || "").trim();
  if (!normalized) return "";
  const lower = normalized.toLowerCase();
  if (lower.includes("failed to fetch") || lower.includes("networkerror")) {
    return "Nao foi possivel conectar ao servico de pagamento. Verifique sua internet, extensoes (adblock) e tente novamente.";
  }
  if (lower.includes("load") && lower.includes("sdk")) {
    return "Nao foi possivel carregar o pagamento. Recarregue a pagina e tente novamente.";
  }
  return normalized;
}

function MercadoPagoCardFields({
  publicKey,
  amount,
  documentDigits,
  primaryColor,
  initialCardholderName,
  requirePaymentMethodDetails = true,
  submitting,
  onPay,
}: {
  publicKey: string;
  amount: number;
  documentDigits: string;
  primaryColor: string;
  initialCardholderName: string;
  requirePaymentMethodDetails?: boolean;
  submitting: boolean;
  onPay: (payload: { token: string; paymentMethodId: string; issuerId: string; installments: number }) => Promise<void> | void;
}) {
  const uid = useId().replaceAll(":", "");
  const [ready, setReady] = useState(false);
  const [cardholderName, setCardholderName] = useState(initialCardholderName);
  const [paymentMethodId, setPaymentMethodId] = useState("");
  const [issuerOptions, setIssuerOptions] = useState<Array<{ id: string; name: string }>>([]);
  const [installmentOptions, setInstallmentOptions] = useState<Array<{ installments: number; label: string }>>([]);
  const [issuerId, setIssuerId] = useState("");
  const [installments, setInstallments] = useState<number>(1);
  const mpRef = useRef<any>(null);
  const fieldRefs = useRef<{ cardNumber?: any; expirationDate?: any; securityCode?: any } | null>(null);
  const currentBinRef = useRef<string>("");

  const cardNumberId = `${uid}-mp-cardNumber`;
  const expirationId = `${uid}-mp-expiration`;
  const securityCodeId = `${uid}-mp-securityCode`;

  useEffect(() => {
    let cancelled = false;

    async function init() {
      try {
        setReady(false);
        setPaymentMethodId("");
        setIssuerOptions([]);
        setInstallmentOptions([]);
        setIssuerId("");
        setInstallments(1);
        currentBinRef.current = "";

        await loadMercadoPagoScript();

        const anyWindow = window as unknown as { MercadoPago?: any };
        if (!anyWindow.MercadoPago) {
          throw new Error("SDK do Mercado Pago indisponivel.");
        }

        const mp = new anyWindow.MercadoPago(publicKey, { locale: "pt-BR" });
        mpRef.current = mp;

        const cardNumber = mp.fields
          .create("cardNumber", {
            placeholder: "Numero do cartao",
          })
          .mount(cardNumberId);
        const expirationDate = mp.fields
          .create("expirationDate", {
            placeholder: "MM/AA",
          })
          .mount(expirationId);
        const securityCode = mp.fields
          .create("securityCode", {
            placeholder: "CVV",
          })
          .mount(securityCodeId);

        fieldRefs.current = { cardNumber, expirationDate, securityCode };

        cardNumber.on("binChange", async (data: { bin?: string }) => {
          try {
            const bin = String(data?.bin || "").trim();
            if (!bin) {
              currentBinRef.current = "";
              setPaymentMethodId("");
              setIssuerOptions([]);
              setInstallmentOptions([]);
              setIssuerId("");
              setInstallments(1);
              return;
            }
            if (bin === currentBinRef.current) return;
            currentBinRef.current = bin;

            const paymentMethodsResponse = await mp.getPaymentMethods({ bin });
            const paymentMethods = Array.isArray(paymentMethodsResponse)
              ? paymentMethodsResponse
              : Array.isArray(paymentMethodsResponse?.results)
                ? paymentMethodsResponse.results
                : [];
            const method = paymentMethods[0];
            if (!method?.id) return;

            setPaymentMethodId(String(method.id));

            const cardNumberSettings = method?.settings?.[0]?.card_number;
            if (cardNumberSettings) {
              cardNumber.update({ settings: cardNumberSettings });
            }
            const securityCodeSettings = method?.settings?.[0]?.security_code;
            if (securityCodeSettings) {
              securityCode.update({ settings: securityCodeSettings });
            }

            const needsIssuer = Array.isArray(method?.additional_info_needed) && method.additional_info_needed.includes("issuer_id");
            const issuerResponse = needsIssuer
              ? await mp.getIssuers({ paymentMethodId: method.id, bin })
              : method?.issuer
                ? [method.issuer]
                : [];
            const issuers = Array.isArray(issuerResponse)
              ? issuerResponse
              : Array.isArray(issuerResponse?.results)
                ? issuerResponse.results
                : [];
            const nextIssuers = issuers
              .map((item: any) => ({ id: String(item?.id || ""), name: String(item?.name || "") }))
              .filter((item: { id: string; name: string }) => item.id);
            setIssuerOptions(nextIssuers);
            setIssuerId(nextIssuers[0]?.id || "");

            const installmentsAmount = Number(amount);
            const installmentsAmountValue = Number.isFinite(installmentsAmount) ? installmentsAmount.toFixed(2) : "0.00";
            const installmentsResponse = await mp.getInstallments({
              amount: installmentsAmountValue,
              bin,
              paymentTypeId: "credit_card",
            });
            const installmentsList = Array.isArray(installmentsResponse)
              ? installmentsResponse
              : Array.isArray(installmentsResponse?.results)
                ? installmentsResponse.results
                : [];
            const payerCosts =
              installmentsList?.[0]?.payer_costs ||
              (installmentsResponse && typeof installmentsResponse === "object" && "payer_costs" in installmentsResponse
                ? (installmentsResponse as any).payer_costs
                : []) ||
              [];
            const nextInstallments = Array.isArray(payerCosts)
              ? payerCosts
                  .map((cost: any) => ({
                    installments: Number(cost?.installments || 0),
                    label: String(cost?.recommended_message || ""),
                  }))
                  .filter((item) => Number.isFinite(item.installments) && item.installments > 0)
              : [];
            setInstallmentOptions(nextInstallments);
            setInstallments(nextInstallments[0]?.installments || 1);
          } catch (err) {
            const message =
              normalizeClientFacingErrorMessage(extractMercadoPagoErrorMessage(err)) || "Nao foi possivel carregar dados do cartao.";
            toast.error(message);
          }
        });

        if (!cancelled) setReady(true);
      } catch (err) {
        if (!cancelled) {
          const message =
            normalizeClientFacingErrorMessage(extractMercadoPagoErrorMessage(err)) || "Nao foi possivel iniciar o pagamento.";
          toast.error(message);
        }
      }
    }

    void init();

    return () => {
      cancelled = true;
      try {
        fieldRefs.current?.cardNumber?.unmount?.();
        fieldRefs.current?.expirationDate?.unmount?.();
        fieldRefs.current?.securityCode?.unmount?.();
      } catch {}
      fieldRefs.current = null;
      mpRef.current = null;
    };
  }, [amount, cardNumberId, expirationId, publicKey, securityCodeId]);

  async function handlePay() {
    if (submitting) return;

    const mp = mpRef.current;
    if (!mp) {
      toast.error("Pagamento indisponivel no momento.");
      return;
    }

    const cleanName = String(cardholderName || "").trim();
    if (!cleanName) {
      toast.error("Informe o nome do titular.");
      return;
    }
    if (requirePaymentMethodDetails) {
      if (!paymentMethodId) {
        toast.error("Informe os dados do cartao.");
        return;
      }
      if (!issuerId) {
        toast.error("Selecione o banco emissor.");
        return;
      }
      if (!installments || installments < 1) {
        toast.error("Selecione as parcelas.");
        return;
      }
    }

    try {
      const token = await mp.fields.createCardToken({
        cardholderName: cleanName,
        identificationType: detectDocumentType(documentDigits),
        identificationNumber: documentDigits,
      });
      const tokenId = String(token?.id || "");
      if (!tokenId) throw new Error("Nao foi possivel capturar os dados do cartao.");
      await onPay({ token: tokenId, paymentMethodId, issuerId, installments });
    } catch (err) {
      const message =
        normalizeClientFacingErrorMessage(extractMercadoPagoErrorMessage(err)) || "Nao foi possivel processar o cartao.";
      const isFailedFetch = normalizeText(extractMercadoPagoErrorMessage(err)) === "failed to fetch";
      if (isFailedFetch) {
        toast.error("Conexao com Mercado Pago bloqueada. Para testar cartao, use HTTPS (ngrok/cloudflare) ou desative bloqueadores.");
      } else {
        toast.error(message);
      }
    }
  }

  return (
    <form
      className="space-y-4 rounded-md border border-slate-200 bg-white p-5 shadow-sm"
      style={{ ["--brand-color" as string]: primaryColor } as React.CSSProperties}
      onSubmit={(event) => {
        event.preventDefault();
        void handlePay();
      }}
    >
      {!ready ? <div className="text-[13px] text-slate-500">Carregando...</div> : null}

      <div className="grid grid-cols-1 gap-3 md:grid-cols-2">
        <div className="md:col-span-2">
          <label className="block text-[13px] font-medium text-slate-700">
            Titular do cartao
            <input
              value={cardholderName}
              onChange={(e) => setCardholderName(e.target.value)}
              placeholder="Nome completo"
              className={`${inputClass} mt-2`}
              data-payment-focus="cardholder"
            />
          </label>
        </div>

        <div className="md:col-span-2">
          <label className="block text-[13px] font-medium text-slate-700">
            Numero do cartao
            <div id={cardNumberId} className={`${inputClass} mt-2 flex items-center px-4`} />
          </label>
        </div>

        <label className="block text-[13px] font-medium text-slate-700">
          Validade
          <div id={expirationId} className={`${inputClass} mt-2 flex items-center px-4`} />
        </label>

        <label className="block text-[13px] font-medium text-slate-700">
          CVV
          <div id={securityCodeId} className={`${inputClass} mt-2 flex items-center px-4`} />
        </label>

        {requirePaymentMethodDetails ? (
          <>
            <label className="block text-[13px] font-medium text-slate-700">
              Banco emissor
              <select
                value={issuerId}
                onChange={(e) => setIssuerId(e.target.value)}
                className={`${inputClass} mt-2`}
                disabled={!ready || submitting || issuerOptions.length === 0}
              >
                {issuerOptions.length === 0 ? <option value="">Preencha o cartao</option> : null}
                {issuerOptions.map((issuer) => (
                  <option key={issuer.id} value={issuer.id}>
                    {issuer.name}
                  </option>
                ))}
              </select>
            </label>

            <label className="block text-[13px] font-medium text-slate-700">
              Parcelas
              <select
                value={String(installments)}
                onChange={(e) => setInstallments(Number(e.target.value))}
                className={`${inputClass} mt-2`}
                disabled={!ready || submitting}
              >
                {installmentOptions.length === 0 ? <option value="1">1x</option> : null}
                {installmentOptions.map((item) => (
                  <option key={item.installments} value={String(item.installments)}>
                    {item.label || `${item.installments}x`}
                  </option>
                ))}
              </select>
            </label>
            {installmentOptions.length <= 1 ? (
              <div className="md:col-span-2 text-[12px] text-slate-500">Parcelamento pode variar por valor e cartao. Para este valor, pode haver apenas 1x.</div>
            ) : null}
          </>
        ) : null}
      </div>

      <button
        type="submit"
        disabled={submitting || !ready}
        className="inline-flex h-12 w-full items-center justify-center rounded-md px-6 text-[16px] font-semibold text-white shadow-sm transition disabled:opacity-60"
        style={{ backgroundColor: primaryColor, color: getReadableTextColor(primaryColor) }}
      >
        {submitting ? "Processando..." : "Pagar com cartao"}
      </button>
    </form>
  );
}

export default function PaymentLinkCheckoutClient({
  storeName,
  logoUrl,
  primaryColor,
  headerColor,
  headerTextColor,
  link,
  linkedClient,
  linkedItems,
  showCookieBanner,
  gatewayName,
  mercadoPagoConfig,
}: {
  storeName: string;
  logoUrl: string;
  primaryColor: string;
  headerColor: string;
  headerTextColor: string;
  link: PaymentLinkPublicData;
  linkedClient: LinkedClient | null;
  linkedItems: LinkedItem[];
  showCookieBanner: boolean;
  gatewayName: string;
  mercadoPagoConfig: {
    environment: "sandbox" | "production";
    publicKey: string;
  } | null;
}) {
  const router = useRouter();
  const [submitting, setSubmitting] = useState(false);
  const [copyingPix, setCopyingPix] = useState(false);
  const [status, setStatus] = useState<StatusMessage | null>(null);
  const [paymentSession, setPaymentSession] = useState<PaymentSession | null>(null);
  const [paymentResult, setPaymentResult] = useState<PaymentResult | null>(null);
  const [selectedPaymentMethodId, setSelectedPaymentMethodId] = useState<string>("");
  const [autoSubmitMethodId, setAutoSubmitMethodId] = useState<string | null>(null);
  const [fieldErrors, setFieldErrors] = useState<Partial<Record<"name" | "email" | "document" | "phone", string>>>({});
  const [subscriptionState, setSubscriptionState] = useState<{
    status: string | null;
    subscriptionId: string | null;
  }>({ status: null, subscriptionId: null });
  const [documentInfoOpen, setDocumentInfoOpen] = useState(false);
  const [termsOpen, setTermsOpen] = useState(false);
  const nameInputRef = useRef<HTMLInputElement | null>(null);
  const emailInputRef = useRef<HTMLInputElement | null>(null);
  const documentInputRef = useRef<HTMLInputElement | null>(null);
  const phoneInputRef = useRef<HTMLInputElement | null>(null);
  const paymentCardRef = useRef<HTMLDivElement | null>(null);
  const paymentDetailsRef = useRef<HTMLDivElement | null>(null);
  const didPrefillFromClientRef = useRef(false);
  const redirectedToSuccessRef = useRef(false);
  const [form, setForm] = useState({
    name: "",
    email: "",
    document: "",
    phone: "",
  });

  useEffect(() => {
    if (!linkedClient || didPrefillFromClientRef.current) return;

    const nextName = normalizeText(linkedClient.name) || normalizeText(linkedClient.company_name);
    const nextEmail = normalizeText(linkedClient.email);
    const nextDocument = normalizeText(linkedClient.document);
    const nextPhone = normalizeText(linkedClient.phone);

    setForm((current) => ({
      name: normalizeText(current.name) ? current.name : nextName,
      email: normalizeText(current.email) ? current.email : nextEmail,
      document: normalizeText(current.document) ? current.document : (nextDocument ? formatDocument(nextDocument) : ""),
      phone: normalizeText(current.phone) ? current.phone : (nextPhone ? formatPhone(nextPhone) : ""),
    }));

    didPrefillFromClientRef.current = true;
  }, [linkedClient]);

  const profile = useMemo(() => normalizeGuestProfile(form), [form]);
  const documentIsValid = profile.document.length > 0 ? validateBrazilianDocument(profile.document) : false;
  const documentLabel = getDocumentLabel(profile.document);
  const hasPendingPix =
    paymentResult?.status === "pending" && paymentResult.paymentMethod === "pix" && Boolean(paymentResult.qrCode);
  const hasPendingTicket =
    paymentResult?.status === "pending" && paymentResult.paymentMethod === "ticket" && Boolean(paymentResult.ticketUrl);
  const paymentMethodCards = useMemo(() => getPaymentMethodCards(link), [link]);
  const selectedMethod =
    (selectedPaymentMethodId
      ? paymentMethodCards.find((method) => method.id === selectedPaymentMethodId && method.enabled)
      : null) || null;
  const hasSelectedMethod = Boolean(selectedMethod);

  function validateGuestFieldsAndScroll() {
    const nextErrors: Partial<Record<"name" | "email" | "document" | "phone", string>> = {};

    if (!normalizeText(form.name)) nextErrors.name = "Informe seu nome completo.";
    if (!normalizeText(form.email)) nextErrors.email = "Informe um email valido.";
    if (!normalizeText(form.document)) nextErrors.document = "Informe seu CPF/CNPJ.";
    if (!normalizeText(form.phone)) nextErrors.phone = "Informe seu celular.";
    if (normalizeText(form.document) && !documentIsValid) nextErrors.document = `Informe um ${documentLabel} valido.`;

    setFieldErrors(nextErrors);
    if (Object.keys(nextErrors).length > 0) {
      setStatus(null);
      window.requestAnimationFrame(() => {
        const firstKey = (["name", "email", "document", "phone"] as const).find((key) => Boolean(nextErrors[key]));
        const firstRef =
          firstKey === "name"
            ? nameInputRef
            : firstKey === "email"
              ? emailInputRef
              : firstKey === "document"
                ? documentInputRef
                : phoneInputRef;
        const element = firstRef.current;
        if (element) {
          element.scrollIntoView({ behavior: "smooth", block: "center" });
          element.focus();
        }
      });
      return false;
    }

    return true;
  }

  useEffect(() => {
    if (!paymentSession || paymentResult?.status !== "pending") return;

    const timer = window.setInterval(() => {
      void refreshPaymentStatus();
    }, 5000);

    return () => window.clearInterval(timer);
  }, [paymentResult?.status, paymentSession]);

  useEffect(() => {
    if (link.type !== "one_time") return;
    if (paymentResult?.status !== "approved") return;
    if (!paymentSession?.paymentId) return;
    if (redirectedToSuccessRef.current) return;

    redirectedToSuccessRef.current = true;
    router.replace(buildApprovedRedirectUrl(link.code, paymentSession.paymentId));
  }, [link.code, link.type, paymentResult?.status, paymentSession?.paymentId, router]);

  async function refreshPaymentStatus() {
    if (!paymentSession) return;

    try {
      const response = await fetch(
        `/api/payment-links/payment/status?code=${encodeURIComponent(link.code)}&paymentId=${encodeURIComponent(paymentSession.paymentId)}`,
        { cache: "no-store" }
      );
      const payload = (await response.json().catch(() => null)) as
        | {
            error?: string;
            payment?: {
              id?: string | null;
              provider_payment_id?: string | null;
              status?: string | null;
              provider_status_detail?: string | null;
              payment_method?: string | null;
              qr_code?: string | null;
              qr_code_base64?: string | null;
              ticket_url?: string | null;
            } | null;
          }
        | null;

      if (!response.ok || payload?.error) {
        throw new Error(payload?.error || "Nao foi possivel consultar o pagamento.");
      }

      if (payload?.payment) {
        setPaymentResult({
          catalogPaymentId: payload.payment.id || null,
          providerPaymentId: payload.payment.provider_payment_id || null,
          status: payload.payment.status || null,
          statusDetail: payload.payment.provider_status_detail || null,
          paymentMethod: payload.payment.payment_method || null,
          qrCode: payload.payment.qr_code || null,
          qrCodeBase64: payload.payment.qr_code_base64 || null,
          ticketUrl: payload.payment.ticket_url || null,
        });
      }
    } catch (error) {
      setStatus({
        type: "error",
        text: error instanceof Error ? error.message : "Nao foi possivel consultar o pagamento.",
      });
    }
  }

  async function startOneTimeCheckout() {
    if (submitting) return;
    if (!validateGuestFieldsAndScroll()) return;

    try {
      if (selectedPaymentMethodId === "bank_transfer" || selectedPaymentMethodId === "ticket") {
        setAutoSubmitMethodId(selectedPaymentMethodId);
      } else {
        setAutoSubmitMethodId(null);
      }

      setSubmitting(true);
      setStatus(null);

      const response = await fetch("/api/payment-links/checkout", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({
          code: link.code,
          profile,
          additionalData: buildConsentAdditionalData(null),
        }),
      });
      const payload = (await response.json().catch(() => null)) as
        | {
            error?: string;
            payment_id?: string;
            payment?: {
              environment?: "sandbox" | "production";
              public_key?: string;
              amount?: number;
              payer?: { name?: string | null; email?: string | null; document?: string | null };
            };
          }
        | null;

      if (!response.ok || payload?.error || !payload?.payment_id || !payload.payment?.public_key || !payload.payment.environment) {
        throw new Error(payload?.error || "Nao foi possivel iniciar o pagamento.");
      }

      setPaymentSession({
        paymentId: payload.payment_id,
        environment: payload.payment.environment,
        publicKey: payload.payment.public_key,
        amount: Number(payload.payment.amount || link.amount),
        payer: payload.payment.payer || {
          name: profile.name,
          email: profile.email,
          document: profile.document,
        },
      });
      setPaymentResult(null);
      setFieldErrors({});
      setStatus({ type: "success", text: "As formas de pagamento foram carregadas. Conclua abaixo." });
    } catch (error) {
      setStatus({
        type: "error",
        text: error instanceof Error ? error.message : "Nao foi possivel iniciar o pagamento.",
      });
    } finally {
      setSubmitting(false);
    }
  }

  function selectPaymentMethod(nextId: string) {
    if (nextId === selectedPaymentMethodId) {
      setSelectedPaymentMethodId("");
      setAutoSubmitMethodId(null);
      setPaymentResult(null);
      setPaymentSession(null);
      setStatus(null);
      return;
    }

    const method = paymentMethodCards.find((item) => item.id === nextId);
    if (!method?.enabled) return;
    if (paymentResult?.status === "approved") return;

    if (!validateGuestFieldsAndScroll()) {
      setSelectedPaymentMethodId("");
      setAutoSubmitMethodId(null);
      setPaymentResult(null);
      setPaymentSession(null);
      setStatus(null);
      return;
    }

    if (paymentResult?.status === "pending") {
      setPaymentResult(null);
    }

    setSelectedPaymentMethodId(nextId);

    window.requestAnimationFrame(() => {
      paymentCardRef.current?.scrollIntoView({ behavior: "smooth", block: "start" });
    });

    if (link.type !== "one_time") {
      setAutoSubmitMethodId(null);
      return;
    }

    if (!paymentSession) {
      void startOneTimeCheckout();
    }

    if (nextId === "bank_transfer" || nextId === "ticket") {
      setAutoSubmitMethodId(nextId);
    }
  }

  useEffect(() => {
    if (!hasSelectedMethod) return;
    const timer = window.setTimeout(() => {
      paymentDetailsRef.current?.scrollIntoView({ behavior: "smooth", block: "start" });
      const focusTarget = paymentDetailsRef.current?.querySelector(
        '[data-payment-focus="cardholder"]'
      ) as HTMLElement | null;
      focusTarget?.focus?.();
    }, 120);

    return () => window.clearTimeout(timer);
  }, [hasSelectedMethod, selectedPaymentMethodId]);

  useEffect(() => {
    if (link.type !== "one_time") return;
    if (!autoSubmitMethodId) return;
    if (!paymentSession) return;
    if (submitting) return;
    if (paymentResult?.status === "approved") return;
    if (autoSubmitMethodId === "bank_transfer" && hasPendingPix) return;
    if (autoSubmitMethodId === "ticket" && hasPendingTicket) return;

    setAutoSubmitMethodId(null);

    if (autoSubmitMethodId === "bank_transfer") {
      void handleSubmitPayment({
        paymentType: "bank_transfer",
        selectedPaymentMethod: "pix",
        formData: { payment_method_id: "pix" },
      });
      return;
    }

    if (autoSubmitMethodId === "ticket") {
      void handleSubmitPayment({
        paymentType: "ticket",
        selectedPaymentMethod: "ticket",
        formData: { payment_method_id: "bolbradesco" },
      });
    }
  }, [autoSubmitMethodId, hasPendingPix, hasPendingTicket, link.type, paymentResult?.status, paymentSession, submitting]);

  async function handleSubmitPayment(
    paymentPayload: Record<string, unknown>,
    additionalData?: Record<string, unknown> | null
  ) {
    if (!paymentSession || submitting) return;

    try {
      setSubmitting(true);
      setStatus(null);

      const response = await fetch("/api/payment-links/payment/submit", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({
          code: link.code,
          paymentId: paymentSession.paymentId,
          paymentType: String(paymentPayload.paymentType || ""),
          selectedPaymentMethod: String(paymentPayload.selectedPaymentMethod || ""),
          formData: paymentPayload.formData || {},
          additionalData: buildConsentAdditionalData(additionalData || null),
        }),
      });
      const payload = (await response.json().catch(() => null)) as
        | {
            error?: string;
            catalog_payment_id?: string | null;
            provider_payment_id?: string | null;
            status?: string | null;
            status_detail?: string | null;
            payment_method?: string | null;
            qr_code?: string | null;
            qr_code_base64?: string | null;
            ticket_url?: string | null;
          }
        | null;

      if (!response.ok || payload?.error) {
        throw new Error(payload?.error || "Nao foi possivel processar o pagamento.");
      }

      const nextResult: PaymentResult = {
        catalogPaymentId: payload?.catalog_payment_id || null,
        providerPaymentId: payload?.provider_payment_id || null,
        status: payload?.status || null,
        statusDetail: payload?.status_detail || null,
        paymentMethod: payload?.payment_method || null,
        qrCode: payload?.qr_code || null,
        qrCodeBase64: payload?.qr_code_base64 || null,
        ticketUrl: payload?.ticket_url || null,
      };
      setPaymentResult(nextResult);
      setStatus({
        type: nextResult.status === "approved" || nextResult.status === "pending" ? "success" : "error",
        text: getPaymentStatusMessage(nextResult.status, nextResult.paymentMethod),
      });
    } catch (error) {
      setStatus({
        type: "error",
        text: error instanceof Error ? error.message : "Nao foi possivel processar o pagamento.",
      });
    } finally {
      setSubmitting(false);
    }
  }

  async function handleSubmitSubscription(
    paymentPayload: Record<string, unknown>,
    additionalData?: Record<string, unknown> | null
  ) {
    if (submitting) return;
    if (!validateGuestFieldsAndScroll()) return;

    try {
      setSubmitting(true);
      setStatus(null);
      const response = await fetch("/api/payment-links/subscription", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({
          code: link.code,
          profile,
          formData: paymentPayload.formData || {},
          additionalData: buildConsentAdditionalData(additionalData || null),
        }),
      });
      const payload = (await response.json().catch(() => null)) as
        | {
            error?: string;
            subscription_id?: string | null;
            status?: string | null;
          }
        | null;

      if (!response.ok || payload?.error) {
        throw new Error(payload?.error || "Nao foi possivel criar a assinatura.");
      }

      setSubscriptionState({
        status: payload?.status || null,
        subscriptionId: payload?.subscription_id || null,
      });
      setStatus({ type: "success", text: "Assinatura criada com sucesso." });
    } catch (error) {
      setStatus({
        type: "error",
        text: error instanceof Error ? error.message : "Nao foi possivel criar a assinatura.",
      });
    } finally {
      setSubmitting(false);
    }
  }

  async function copyPixCode() {
    if (!paymentResult?.qrCode || copyingPix) return;
    try {
      setCopyingPix(true);
      await navigator.clipboard.writeText(paymentResult.qrCode);
      setStatus({ type: "success", text: "Codigo Pix copiado." });
    } catch {
      setStatus({ type: "error", text: "Nao foi possivel copiar o codigo Pix." });
    } finally {
      setCopyingPix(false);
    }
  }

  const canRenderOneTimePanel = Boolean(paymentSession) && !hasPendingPix && !hasPendingTicket && paymentResult?.status !== "approved";
  const activeMethod = selectedMethod;
  const activeMethodTheme = primaryColor || headerColor || "#13795b";
  const paymentButtonLabel =
    link.type === "subscription"
      ? "Pagar com Cartao"
      : activeMethod?.id === "bank_transfer"
        ? "Pagar com PIX"
        : activeMethod?.id === "ticket"
          ? "Gerar boleto"
          : activeMethod?.id === "credit_card"
            ? "Pagar com Cartao"
            : "Selecione";
  const activeBenefits =
    activeMethod?.id === "bank_transfer"
      ? [
          "Liberacao imediata",
          "E simples, basta usar o aplicativo do seu banco para pagar com Pix",
        ]
      : activeMethod?.id === "ticket"
        ? [
            "Emissao imediata do boleto",
            "Pagamento por codigo de barras ou internet banking ate o vencimento",
          ]
        : link.type === "subscription"
          ? [
              "Pagamento recorrente autorizado com seguranca",
              `As proximas cobrancas serao processadas automaticamente por ${storeName}`,
            ]
          : activeMethod?.id === "credit_card"
            ? [
                "Pagamento seguro com cartao de credito",
                "Parcelamento disponivel conforme as condicoes oferecidas no checkout",
              ]
            : [];
  const summaryTitle = storeName;
  const summaryRecurrence = paymentLinkRecurrenceLabel(link);
  const linkedClientName = linkedClient ? formatLinkedClientName(linkedClient) : "";
  const documentHasValue = profile.document.length > 0;
  const showDocumentValid = documentHasValue && documentIsValid;
  const showDocumentInvalid = documentHasValue && !documentIsValid;

  function readCookie(name: string) {
    if (typeof document === "undefined") return "";
    const prefix = `${name}=`;
    const parts = document.cookie.split(";").map((part) => part.trim());
    const entry = parts.find((part) => part.startsWith(prefix));
    if (!entry) return "";
    return decodeURIComponent(entry.slice(prefix.length));
  }

  function writeCookie(name: string, value: string, maxAgeSeconds: number) {
    if (typeof document === "undefined") return;
    const secure = window.location.protocol === "https:" ? "; Secure" : "";
    document.cookie = `${name}=${encodeURIComponent(value)}; Path=/; Max-Age=${Math.max(0, Math.floor(maxAgeSeconds))}; SameSite=Lax${secure}`;
  }

  type CookieConsent = {
    necessary: true;
    analytics: boolean;
    marketing: boolean;
    updatedAt: string;
  };

  const [cookieConsent, setCookieConsent] = useState<CookieConsent | null>(null);
  const [cookieBannerOpen, setCookieBannerOpen] = useState(false);
  const [cookiePrefsOpen, setCookiePrefsOpen] = useState(false);
  const [cookiePrefs, setCookiePrefs] = useState<{ analytics: boolean; marketing: boolean }>({
    analytics: false,
    marketing: false,
  });

  useEffect(() => {
    if (!showCookieBanner) {
      setCookieBannerOpen(false);
      return;
    }
    const dismissed = readCookie("ktl_cookie_banner_dismissed_v1");
    if (dismissed === "1") {
      setCookieBannerOpen(false);
      return;
    }
    const raw = readCookie("ktl_cookie_consent_v1");
    if (!raw) {
      setCookieBannerOpen(true);
      return;
    }
    try {
      const parsed = JSON.parse(raw) as CookieConsent;
      if (!parsed || typeof parsed !== "object" || parsed.necessary !== true) {
        setCookieBannerOpen(true);
        return;
      }
      setCookieConsent(parsed);
      setCookiePrefs({ analytics: Boolean(parsed.analytics), marketing: Boolean(parsed.marketing) });
      setCookieBannerOpen(false);
    } catch {
      setCookieBannerOpen(true);
    }
  }, []);

  function persistCookieConsent(next: { analytics: boolean; marketing: boolean }) {
    const record: CookieConsent = {
      necessary: true,
      analytics: Boolean(next.analytics),
      marketing: Boolean(next.marketing),
      updatedAt: new Date().toISOString(),
    };
    writeCookie("ktl_cookie_consent_v1", JSON.stringify(record), 60 * 60 * 24 * 180);
    setCookieConsent(record);
    setCookiePrefs({ analytics: record.analytics, marketing: record.marketing });
    setCookieBannerOpen(false);
    setCookiePrefsOpen(false);
  }

  function dismissCookieBanner() {
    writeCookie("ktl_cookie_banner_dismissed_v1", "1", 60 * 60 * 24 * 7);
    setCookieBannerOpen(false);
  }

  function buildConsentAdditionalData(input?: Record<string, unknown> | null) {
    const merged = (input && typeof input === "object" && !Array.isArray(input) ? input : {}) as Record<string, unknown>;
    const termsVersion = "v1";
    return {
      ...merged,
      terms: {
        accepted: true,
        version: termsVersion,
        mode: "notice",
      },
      cookies: cookieConsent
        ? {
            necessary: true,
            analytics: Boolean(cookieConsent.analytics),
            marketing: Boolean(cookieConsent.marketing),
            updatedAt: cookieConsent.updatedAt,
          }
        : null,
    };
  }

  useEffect(() => {
    if (!status) return;
    const text = normalizeClientFacingErrorMessage(status.text) || status.text;
    if (status.type === "success") toast.success(text);
    else toast.error(text);
    setStatus(null);
  }, [status]);

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

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

  return (
    <div className="min-h-screen bg-[#f2f2f2]">
      <Toaster richColors position="bottom-right" />
      {documentInfoOpen ? (
        <div
          className="fixed inset-0 z-50 flex items-center justify-center bg-black/40 px-4"
          role="dialog"
          aria-modal="true"
          onMouseDown={(event) => {
            if (event.target === event.currentTarget) setDocumentInfoOpen(false);
          }}
        >
          <div className="w-full max-w-md rounded-xl bg-white p-6 shadow-xl">
            <div className="text-[18px] font-semibold text-slate-950">Sobre CPF/CNPJ</div>
            <div className="mt-3 text-[13px] leading-6 text-slate-600">
              Esse dado é necessário para garantir a segurança da sua compra e cadastro em nossa plataforma, essa informação também pode ser usada para emissão
              de Nota Fiscal.
            </div>
            <button
              type="button"
              onClick={() => setDocumentInfoOpen(false)}
              className="mt-5 inline-flex h-11 w-full items-center justify-center rounded-md text-[15px] font-semibold text-white"
              style={{ backgroundColor: activeMethodTheme }}
            >
              OK
            </button>
          </div>
        </div>
      ) : null}
      {termsOpen ? (
        <div
          className="fixed inset-0 z-50 flex items-center justify-center bg-black/40 px-4"
          role="dialog"
          aria-modal="true"
          onMouseDown={(event) => {
            if (event.target === event.currentTarget) setTermsOpen(false);
          }}
        >
          <div className="w-full max-w-lg rounded-xl bg-white p-6 shadow-xl">
            <div className="text-[18px] font-semibold text-slate-950">Termos e Privacidade (LGPD)</div>
            <div className="mt-3 space-y-3 text-[13px] leading-6 text-slate-600">
              <div>
                Ao continuar, você concorda que seus dados (nome, e-mail, CPF/CNPJ e telefone) serão utilizados para processar este pagamento, prevenir
                fraudes, cumprir obrigações legais e, quando aplicável, emitir nota fiscal.
              </div>
              <div>
                Também poderemos compartilhar esses dados com provedores de pagamento e serviços essenciais à conclusão da compra (por exemplo, Mercado Pago),
                sempre com a finalidade de viabilizar a transação.
              </div>
            </div>
            <button
              type="button"
              onClick={() => setTermsOpen(false)}
              className="mt-5 inline-flex h-11 w-full items-center justify-center rounded-md text-[15px] font-semibold text-white"
              style={{ backgroundColor: activeMethodTheme }}
            >
              OK
            </button>
          </div>
        </div>
      ) : null}
      {showCookieBanner && cookiePrefsOpen ? (
        <div
          className="fixed inset-0 z-50 flex items-center justify-center bg-black/40 px-4"
          role="dialog"
          aria-modal="true"
          onMouseDown={(event) => {
            if (event.target === event.currentTarget) setCookiePrefsOpen(false);
          }}
        >
          <div className="w-full max-w-lg rounded-xl bg-white p-6 shadow-xl">
            <div className="flex items-start justify-between gap-4">
              <div className="text-[18px] font-semibold text-slate-950">Preferências de cookies</div>
              <button
                type="button"
                onClick={() => setCookiePrefsOpen(false)}
                className="inline-flex h-9 w-9 items-center justify-center rounded-md border border-slate-200 bg-white text-slate-700"
                aria-label="Fechar"
              >
                <X className="h-4 w-4" />
              </button>
            </div>
            <div className="mt-2 text-[13px] leading-6 text-slate-600">
              Usamos cookies necessários para o funcionamento do checkout. Você pode escolher permitir cookies opcionais.
            </div>

            <div className="mt-5 space-y-3">
              <label className="flex items-start gap-3 rounded-lg border border-slate-200 bg-slate-50 px-4 py-3 text-sm text-slate-700">
                <input type="checkbox" checked disabled className="mt-0.5 h-4 w-4" />
                <div className="min-w-0">
                  <div className="font-semibold text-slate-900">Necessários</div>
                  <div className="mt-0.5 text-xs text-slate-600">Obrigatórios para o funcionamento, segurança e pagamento.</div>
                </div>
              </label>
              <label className="flex items-start gap-3 rounded-lg border border-slate-200 bg-white px-4 py-3 text-sm text-slate-700">
                <input
                  type="checkbox"
                  checked={cookiePrefs.analytics}
                  onChange={(event) => setCookiePrefs((current) => ({ ...current, analytics: event.target.checked }))}
                  className="mt-0.5 h-4 w-4"
                />
                <div className="min-w-0">
                  <div className="font-semibold text-slate-900">Analytics</div>
                  <div className="mt-0.5 text-xs text-slate-600">Ajuda a entender uso e melhorar a experiência.</div>
                </div>
              </label>
              <label className="flex items-start gap-3 rounded-lg border border-slate-200 bg-white px-4 py-3 text-sm text-slate-700">
                <input
                  type="checkbox"
                  checked={cookiePrefs.marketing}
                  onChange={(event) => setCookiePrefs((current) => ({ ...current, marketing: event.target.checked }))}
                  className="mt-0.5 h-4 w-4"
                />
                <div className="min-w-0">
                  <div className="font-semibold text-slate-900">Marketing</div>
                  <div className="mt-0.5 text-xs text-slate-600">Permite personalização e comunicações, quando aplicável.</div>
                </div>
              </label>
            </div>

            <div className="mt-5 flex items-center gap-3">
              <button
                type="button"
                onClick={() => setCookiePrefsOpen(false)}
                className="inline-flex h-11 flex-1 items-center justify-center rounded-md border border-slate-200 bg-white text-[15px] font-semibold text-slate-700"
              >
                Cancelar
              </button>
              <button
                type="button"
                onClick={() => persistCookieConsent(cookiePrefs)}
                className="inline-flex h-11 flex-1 items-center justify-center rounded-md text-[15px] font-semibold text-white"
                style={{ backgroundColor: activeMethodTheme }}
              >
                Salvar
              </button>
            </div>
          </div>
        </div>
      ) : null}
      {showCookieBanner && cookieBannerOpen ? (
        <div
          className="fixed inset-x-0 bottom-0 z-40 border-t backdrop-blur-md"
          style={{ backgroundColor: hexToRgba(activeMethodTheme, 0.14), borderColor: hexToRgba(activeMethodTheme, 0.22) }}
        >
          <div className="mx-auto relative max-w-[1056px] px-3 py-2 md:px-4">
            <button
              type="button"
              onClick={dismissCookieBanner}
              className="absolute right-3 top-1/2 inline-flex h-7 w-7 -translate-y-1/2 items-center justify-center text-slate-900 transition hover:cursor-pointer hover:opacity-80 md:right-4"
              aria-label="Fechar"
            >
              <X className="h-3.5 w-3.5" />
            </button>

            <div className="pr-10 md:pr-12">
              <div className="text-[11px] leading-4 text-slate-900 md:text-[12px]">
                Usamos cookies necessários para manter o checkout seguro e funcionando. Você pode aceitar cookies opcionais para melhorar a experiência.
              </div>
              <div className="mt-2 flex flex-wrap items-center gap-1.5">
              <button
                type="button"
                onClick={() => persistCookieConsent({ analytics: true, marketing: true })}
                className="inline-flex h-7 items-center justify-center rounded-md px-2.5 text-[11px] font-semibold text-white shadow-sm transition hover:cursor-pointer hover:opacity-95"
                style={{ backgroundColor: activeMethodTheme }}
              >
                Aceitar
              </button>
              <button
                type="button"
                onClick={() => persistCookieConsent({ analytics: false, marketing: false })}
                className="inline-flex h-7 items-center justify-center rounded-md border border-slate-900/10 bg-white/70 px-2.5 text-[11px] font-semibold text-slate-900 transition hover:cursor-pointer hover:bg-white/90"
              >
                Somente necessários
              </button>
              <button
                type="button"
                onClick={() => setCookiePrefsOpen(true)}
                className="inline-flex h-7 items-center justify-center rounded-md border border-slate-900/10 bg-white/70 px-2.5 text-[11px] font-semibold text-slate-900 transition hover:cursor-pointer hover:bg-white/90"
              >
                Preferências
              </button>
              </div>
            </div>
          </div>
        </div>
      ) : null}
      <section style={{ backgroundColor: headerColor, color: headerTextColor }}>
        <div className="mx-auto flex max-w-[1056px] items-center justify-center gap-4 px-4 py-3 md:justify-between">
          <div className="flex w-full min-w-0 items-center justify-center md:w-auto md:justify-start">
            {logoUrl ? (
              <Image src={logoUrl} alt={storeName} width={140} height={40} className="h-7 w-auto object-contain" unoptimized />
            ) : (
              <div className="text-xs font-semibold uppercase tracking-[0.12em]">{storeName}</div>
            )}
          </div>
          <div className="hidden items-center gap-1.5 text-[10px] font-semibold uppercase tracking-[0.16em] md:flex">
            <Lock className="h-3.5 w-3.5" />
            Ambiente seguro
          </div>
        </div>
      </section>

      <div className="mx-auto max-w-[1056px] px-4 py-5 md:py-8">
        {linkedClientName ? (
          <div className="mb-5 md:mb-7">
            <div className="flex items-center gap-2">
              <Hand className="h-5 w-5" style={{ color: getAccessibleAccent(primaryColor) }} />
              <div className="text-[18px] font-semibold leading-tight text-slate-950">Olá, {linkedClientName}</div>
            </div>
            <div className="mt-1 text-[12px] text-slate-600">Este link de pagamento foi gerado para você.</div>
          </div>
        ) : null}
        <div className="grid items-start gap-7 xl:grid-cols-[1fr_306px]">
          <section className="space-y-4 md:space-y-6">
            <div className="rounded-lg border border-slate-200 bg-white px-4 py-5 shadow-sm md:px-7 md:py-6">
              <div className="text-[15px] font-semibold leading-6 text-[#111827] md:text-[17px]">{summaryTitle}</div>
              <div className="mt-1 text-[13px] text-slate-500">{link.title}</div>
              {linkedClientName ? <div className="mt-1 text-[13px] font-semibold text-slate-900">{linkedClientName}</div> : null}
              <div className="mt-1 text-[17px] font-semibold leading-none text-[#13795b] md:text-[18px]">
                <span style={{ color: activeMethodTheme }}>{formatMoney(link.amount)}</span>
                {link.type === "subscription" ? " / mês" : ""}
              </div>
              {linkedItems.length ? (
                <div className="mt-4 space-y-1 text-[13px] text-slate-600">
                  {linkedItems.slice(0, 3).map((item) => (
                    <div key={`${item.productId}-${item.name}`} className="flex items-start justify-between gap-4">
                      <div className="min-w-0">
                        <div className="truncate">{item.name}</div>
                        <div className="text-[12px] text-slate-500">Qtd: {item.quantity}</div>
                      </div>
                      <div className="shrink-0 text-right text-[12px] font-medium text-slate-700">
                        {item.unitPrice != null ? formatMoney(item.unitPrice * item.quantity) : "Sob consulta"}
                      </div>
                    </div>
                  ))}
                  {linkedItems.length > 3 ? (
                    <div className="text-[12px] text-slate-500">e mais {linkedItems.length - 3} item(ns)</div>
                  ) : null}
                </div>
              ) : null}
            </div>

            <div className="rounded-lg border border-slate-200 bg-white px-4 py-5 shadow-sm md:px-7 md:py-6">
              <div className="mb-6 flex items-center gap-2.5">
                <UserRound className="h-[18px] w-[18px] text-black" strokeWidth={1.9} />
                <div className="text-[17px] font-semibold text-black">Seus dados</div>
              </div>

              <div className="grid gap-4 md:grid-cols-2">
                <label className="space-y-2 md:col-span-2">
                  <span className="text-[13px] text-[#525252]">Nome completo</span>
                  <input
                    value={form.name}
                    onChange={(event) => {
                      setForm((current) => ({ ...current, name: event.target.value }));
                      setFieldErrors((current) => ({ ...current, name: undefined }));
                    }}
                    placeholder="Preencha seu nome"
                    className={`${inputClass} ${fieldErrors.name ? "border-rose-300 focus:border-rose-500" : ""}`}
                    ref={nameInputRef}
                  />
                  {fieldErrors.name ? <div className="text-[12px] text-rose-600">{fieldErrors.name}</div> : null}
                </label>
                <label className="space-y-2 md:col-span-2">
                  <span className="text-[13px] text-[#525252]">Email</span>
                  <input
                    value={form.email}
                    onChange={(event) => {
                      setForm((current) => ({ ...current, email: event.target.value }));
                      setFieldErrors((current) => ({ ...current, email: undefined }));
                    }}
                    placeholder="Preencha seu email"
                    className={`${inputClass} ${fieldErrors.email ? "border-rose-300 focus:border-rose-500" : ""}`}
                    type="email"
                    ref={emailInputRef}
                  />
                  {fieldErrors.email ? <div className="text-[12px] text-rose-600">{fieldErrors.email}</div> : null}
                </label>
                <label className="space-y-2">
                  <span className="text-[13px] text-[#525252]">CPF/CNPJ</span>
                  <div className="relative">
                    <input
                      value={form.document}
                      onChange={(event) => {
                        setForm((current) => ({ ...current, document: formatDocument(event.target.value) }));
                        setFieldErrors((current) => ({ ...current, document: undefined }));
                      }}
                      placeholder="Preencha seu CPF/CNPJ"
                      className={`${inputClass} pr-11 ${
                        showDocumentInvalid || (fieldErrors.document && !documentHasValue) ? "border-rose-300 focus:border-rose-500" : ""
                      }`}
                      ref={documentInputRef}
                    />
                    <div className="pointer-events-none absolute right-3 top-1/2 -translate-y-1/2">
                      <AnimatePresence initial={false} mode="wait">
                        {showDocumentValid ? (
                          <motion.div
                            key="document-valid"
                            initial={{ opacity: 0, scale: 0.85 }}
                            animate={{ opacity: 1, scale: 1 }}
                            exit={{ opacity: 0, scale: 0.9 }}
                            transition={{ duration: 0.18 }}
                          >
                            <CheckCircle2 className="h-5 w-5 text-emerald-600" />
                          </motion.div>
                        ) : showDocumentInvalid ? (
                          <motion.div
                            key="document-invalid"
                            initial={{ opacity: 0, scale: 0.85 }}
                            animate={{ opacity: 1, scale: 1 }}
                            exit={{ opacity: 0, scale: 0.9 }}
                            transition={{ duration: 0.18 }}
                          >
                            <X className="h-5 w-5 text-rose-600" />
                          </motion.div>
                        ) : null}
                      </AnimatePresence>
                    </div>

                    <AnimatePresence initial={false}>
                      {showDocumentInvalid ? (
                        <motion.div
                          key="document-tooltip"
                          initial={{ opacity: 0, y: -4 }}
                          animate={{ opacity: 1, y: 0 }}
                          exit={{ opacity: 0, y: -4 }}
                          transition={{ duration: 0.16 }}
                          className="absolute right-0 top-[calc(100%+8px)] z-10 w-[260px] rounded-md border border-rose-200 bg-white px-3 py-2 text-[12px] text-rose-700 shadow-lg"
                        >
                          {fieldErrors.document || `Informe um ${documentLabel} valido.`}
                        </motion.div>
                      ) : null}
                    </AnimatePresence>
                  </div>
                  {fieldErrors.document && !documentHasValue ? (
                    <div className="text-[12px] text-rose-600">{fieldErrors.document}</div>
                  ) : null}
                  <button
                    type="button"
                    onClick={() => setDocumentInfoOpen(true)}
                    className="text-left text-[12px] font-medium underline underline-offset-2"
                    style={{ color: activeMethodTheme }}
                  >
                    Porque pedimos esse dado?
                  </button>
                </label>
                <label className="space-y-2">
                  <span className="text-[13px] text-[#525252]">Celular</span>
                  <input
                    value={form.phone}
                    onChange={(event) => {
                      setForm((current) => ({ ...current, phone: formatPhone(event.target.value) }));
                      setFieldErrors((current) => ({ ...current, phone: undefined }));
                    }}
                    placeholder="+55"
                    className={`${inputClass} ${fieldErrors.phone ? "border-rose-300 focus:border-rose-500" : ""}`}
                    ref={phoneInputRef}
                  />
                  {fieldErrors.phone ? <div className="text-[12px] text-rose-600">{fieldErrors.phone}</div> : null}
                </label>
              </div>
            </div>

            <div ref={paymentCardRef} className="scroll-mt-6 rounded-lg border border-slate-200 bg-white px-4 py-5 shadow-sm md:px-7 md:py-6">
              <div className="mb-6 flex items-center gap-2.5">
                <CreditCard className="h-[18px] w-[18px] text-black" strokeWidth={1.9} />
                <div className="text-[17px] font-semibold text-black">Pagamento</div>
              </div>
              {!hasSelectedMethod ? <div className="mb-4 text-[13px] text-slate-500">Selecione uma forma de pagamento</div> : null}

              <div className="grid grid-cols-3 gap-2.5">
                {paymentMethodCards.map((method) => {
                  const Icon = method.icon;
                  const isEnabled = method.enabled;
                  const isSelected = isEnabled && method.id === selectedPaymentMethodId;
                  return (
                    <button
                      key={method.id}
                      type="button"
                      onClick={() => selectPaymentMethod(method.id)}
                      disabled={!isEnabled}
                      className={`rounded-md border shadow-sm transition ${
                        isEnabled ? "cursor-pointer" : "cursor-not-allowed opacity-60"
                      } ${isSelected ? "border-transparent text-white" : "border-slate-200 bg-white text-slate-700"}`}
                      style={isSelected ? { backgroundColor: activeMethodTheme } : undefined}
                      aria-pressed={isSelected}
                    >
                      <div className="flex h-[82px] flex-col items-center justify-center px-2 text-center md:h-[98px] md:px-3">
                        <Icon className={`h-7 w-7 ${isSelected ? "text-white" : "text-slate-900"} md:h-8 md:w-8`} />
                        <div className={`mt-2 text-[12px] font-medium leading-tight ${isSelected ? "text-white" : "text-slate-700"} md:mt-3 md:text-[13px]`}>
                          {method.title}
                        </div>
                      </div>
                    </button>
                  );
                })}
              </div>

              <AnimatePresence initial={false}>
                {hasSelectedMethod ? (
                  <motion.div
                    key="payment-details"
                    initial={{ opacity: 0, height: 0 }}
                    animate={{ opacity: 1, height: "auto" }}
                    exit={{ opacity: 0, height: 0 }}
                    transition={{ duration: 0.25 }}
                    className="overflow-hidden"
                    ref={paymentDetailsRef}
                  >
                    <div
                      className="mt-4 rounded-md border border-dashed px-5 py-4 shadow-[0_1px_2px_rgba(15,23,42,0.03)]"
                      style={{ borderColor: activeMethodTheme }}
                    >
                      <div className="space-y-3 text-[13px] leading-5 text-black">
                        {activeBenefits.map((benefit) => (
                          <div key={benefit} className="flex items-start gap-2">
                            <BadgeCheck className="mt-0.5 h-4 w-4 shrink-0" style={{ color: activeMethodTheme }} />
                            <span>{benefit}</span>
                          </div>
                        ))}
                      </div>
                    </div>

                    <div className="mt-16">
                      <div className="mb-4 text-[17px] font-semibold text-black">Resumo do pedido</div>
                      <div className="relative overflow-hidden rounded-lg bg-slate-50 px-5 pt-5 pb-8">
                        <div className="rounded-md border border-[#e0e0e0] bg-white px-5 py-4 shadow-[0_2px_8px_rgba(0,0,0,0.08)]">
                          <div className="flex items-start justify-between gap-4 text-[14px] font-semibold text-[#334155]">
                            <div>{link.title}</div>
                            <div className="text-right">
                              {formatMoney(link.amount)}
                              {link.type === "subscription" ? " / mês" : ""}
                            </div>
                          </div>
                        </div>
                        {linkedItems.length ? (
                          <div className="mt-4 rounded-md border border-[#e0e0e0] bg-white px-5 py-4">
                            <div className="text-[12px] font-semibold uppercase tracking-[0.12em] text-slate-500">
                              Itens
                            </div>
                            <div className="mt-3 space-y-2">
                              {linkedItems.map((item) => (
                                <div key={`${item.productId}-${item.quantity}`} className="flex items-start justify-between gap-4 text-[14px] text-[#334155]">
                                  <div className="min-w-0">
                                    <div className="truncate font-medium">{item.name}</div>
                                    <div className="text-[12px] text-slate-500">
                                      Qtd: {item.quantity}
                                      {item.unitPrice != null ? ` • ${formatMoney(item.unitPrice)} cada` : ""}
                                    </div>
                                  </div>
                                  <div className="shrink-0 text-right font-semibold text-[#334155]">
                                    {item.unitPrice != null ? formatMoney(item.unitPrice * item.quantity) : "Sob consulta"}
                                  </div>
                                </div>
                              ))}
                            </div>
                          </div>
                        ) : null}
                        <div className="mt-4 border-b border-[#d8d8d8] pb-4 text-[14px] text-black">
                          <div className="flex items-center justify-between">
                            <div className="inline-flex items-center gap-1.5 text-[#404040]">
                              Taxa de servico
                              <HelpCircle className="h-3.5 w-3.5 text-slate-400" />
                            </div>
                            <div>R$ 0,00</div>
                          </div>
                        </div>
                        <div className="flex items-center justify-between pt-5 text-black">
                          <div className="text-[18px]">Total</div>
                          <div className="text-[19px] font-medium">
                            {formatMoney(link.amount)}
                            {link.type === "subscription" ? " / mês" : ""}
                          </div>
                        </div>
                        <div className="pointer-events-none absolute bottom-0 left-0 right-0 h-5">
                          <svg viewBox="0 0 100 10" preserveAspectRatio="none" className="h-full w-full">
                            <path
                              d="M0 0 L2 10 L4 0 L6 10 L8 0 L10 10 L12 0 L14 10 L16 0 L18 10 L20 0 L22 10 L24 0 L26 10 L28 0 L30 10 L32 0 L34 10 L36 0 L38 10 L40 0 L42 10 L44 0 L46 10 L48 0 L50 10 L52 0 L54 10 L56 0 L58 10 L60 0 L62 10 L64 0 L66 10 L68 0 L70 10 L72 0 L74 10 L76 0 L78 10 L80 0 L82 10 L84 0 L86 10 L88 0 L90 10 L92 0 L94 10 L96 0 L98 10 L100 0 V10 H0 Z"
                              fill="#ffffff"
                            />
                          </svg>
                        </div>
                      </div>
                    </div>

                    {link.type === "one_time" ? (
                      <div className="mt-6 space-y-5">
                        {activeMethod?.id === "credit_card" && !paymentSession ? (
                          <button
                            type="button"
                            onClick={() => void startOneTimeCheckout()}
                            disabled={submitting}
                            className="inline-flex h-12 w-full items-center justify-center rounded-md px-6 text-[17px] font-semibold text-white shadow-sm transition disabled:opacity-60"
                            style={{ backgroundColor: activeMethodTheme }}
                          >
                            {submitting ? "Carregando..." : "Continuar"}
                          </button>
                        ) : null}

                        {canRenderOneTimePanel && paymentSession && activeMethod?.id === "credit_card" ? (
                          <MercadoPagoCardFields
                            publicKey={paymentSession.publicKey}
                            amount={paymentSession.amount}
                            documentDigits={profile.document.replace(/\D/g, "")}
                            primaryColor={activeMethodTheme}
                            initialCardholderName={profile.name}
                            submitting={submitting}
                            onPay={async (payload) => {
                              await handleSubmitPayment({
                                paymentType: "credit_card",
                                selectedPaymentMethod: "credit_card",
                                formData: {
                                  token: payload.token,
                                  payment_method_id: payload.paymentMethodId,
                                  issuer_id: payload.issuerId,
                                  installments: payload.installments,
                                  transaction_amount: link.amount,
                                  payer: {
                                    email: profile.email,
                                    identification: { number: profile.document.replace(/\D/g, "") },
                                  },
                                },
                              });
                            }}
                          />
                        ) : null}

                        {hasPendingPix ? (
                          <div className="space-y-4 rounded-md border border-slate-200 bg-slate-50 p-5 shadow-[0_1px_3px_rgba(15,23,42,0.04)]">
                            <div className="text-sm font-semibold text-slate-900">Pix gerado para pagamento</div>
                            {paymentResult?.qrCodeBase64 ? (
                              <div className="flex justify-center">
                                <Image
                                  src={
                                    paymentResult.qrCodeBase64.startsWith("data:")
                                      ? paymentResult.qrCodeBase64
                                      : `data:image/png;base64,${paymentResult.qrCodeBase64}`
                                  }
                                  alt="QR Code Pix"
                                  width={224}
                                  height={224}
                                  className="h-56 w-56 border border-slate-200 bg-white p-3"
                                  unoptimized
                                />
                              </div>
                            ) : null}
                            {paymentResult?.qrCode ? (
                              <>
                                <textarea readOnly value={paymentResult.qrCode} className="min-h-[110px] w-full border border-slate-200 bg-white p-3 text-xs text-slate-700 outline-none" />
                                <div className="flex flex-wrap gap-3">
                                  <button
                                    type="button"
                                    onClick={() => void copyPixCode()}
                                    disabled={copyingPix}
                                    className="inline-flex h-11 items-center justify-center gap-2 border border-slate-200 bg-white px-4 text-sm font-medium text-slate-700 transition hover:bg-slate-50 disabled:opacity-60"
                                  >
                                    <Copy className="h-4 w-4" />
                                    {copyingPix ? "Copiando..." : "Copiar codigo Pix"}
                                  </button>
                                  <button
                                    type="button"
                                    onClick={() => void refreshPaymentStatus()}
                                    className="inline-flex h-11 items-center justify-center gap-2 px-4 text-sm font-semibold text-white transition hover:opacity-95"
                                    style={{ backgroundColor: activeMethodTheme }}
                                  >
                                    <RefreshCcw className="h-4 w-4" />
                                    Atualizar status
                                  </button>
                                </div>
                              </>
                            ) : null}
                          </div>
                        ) : null}

                  {hasPendingTicket ? (
                    <div className="space-y-4 rounded-md border border-slate-200 bg-slate-50 p-5 shadow-[0_1px_3px_rgba(15,23,42,0.04)]">
                      <div className="text-sm font-semibold text-slate-900">Boleto gerado para pagamento</div>
                      {paymentResult?.ticketUrl ? (
                        <div className="flex flex-wrap gap-3">
                          <a
                            href={paymentResult.ticketUrl}
                            target="_blank"
                            rel="noreferrer"
                            className="inline-flex h-11 items-center justify-center rounded-md px-4 text-sm font-semibold text-white shadow-sm transition hover:opacity-95"
                            style={{ backgroundColor: activeMethodTheme }}
                          >
                            Abrir boleto
                          </a>
                          <button
                            type="button"
                            onClick={() => void refreshPaymentStatus()}
                            className="inline-flex h-11 items-center justify-center gap-2 rounded-md border border-slate-200 bg-white px-4 text-sm font-medium text-slate-700 shadow-sm transition hover:bg-slate-50"
                          >
                            <RefreshCcw className="h-4 w-4" />
                            Atualizar status
                          </button>
                        </div>
                      ) : null}
                    </div>
                  ) : null}

                  {paymentResult?.status === "approved" ? (
                    <div className="text-sm font-medium text-slate-700">Pagamento aprovado.</div>
                  ) : null}
                </div>
              ) : (
                <div className="mt-6">
                  {!mercadoPagoConfig?.publicKey ? (
                    <div className="rounded-md border border-rose-200 bg-rose-50 px-4 py-4 text-sm text-rose-700">
                      Este pagamento nao esta disponivel no momento.
                    </div>
                  ) : (
                    <>
                      {subscriptionState.status === "authorized" ? (
                        <div className="text-sm font-medium text-slate-700">
                          Assinatura autorizada.
                          {subscriptionState.subscriptionId ? ` ID: ${subscriptionState.subscriptionId}` : ""}
                        </div>
                      ) : (
                        <MercadoPagoCardFields
                          publicKey={mercadoPagoConfig.publicKey}
                          amount={link.amount}
                          documentDigits={profile.document.replace(/\D/g, "")}
                          primaryColor={activeMethodTheme}
                          initialCardholderName={profile.name}
                          requirePaymentMethodDetails={false}
                          submitting={submitting}
                          onPay={async (payload) => {
                            await handleSubmitSubscription({ formData: { token: payload.token } });
                          }}
                        />
                      )}
                    </>
                  )}
                </div>
              )}

              <div className="mt-10 flex flex-col items-center justify-center text-center">
                {logoUrl ? (
                  <Image src={logoUrl} alt={storeName} width={120} height={36} className="h-7 w-auto object-contain" unoptimized />
                ) : (
                  <div className="text-[18px] font-semibold" style={{ color: activeMethodTheme }}>
                    {storeName}
                  </div>
                )}
                <div className="mt-5 inline-flex items-center gap-2 text-[14px] text-[#22a65a]">
                  <ShieldCheck className="h-4 w-4" />
                  Compra 100% segura
                </div>
                <div className="mt-5 max-w-[520px] text-[13px] leading-6 text-[#4b5563]">
                  {storeName} esta processando este pagamento em ambiente protegido.
                  {normalizeText(gatewayName) ? ` Processado por ${gatewayName}.` : ""}
                </div>
              </div>
                  </motion.div>
                ) : (
                  <motion.div
                    key="payment-select-hint"
                    initial={{ opacity: 0, height: 0 }}
                    animate={{ opacity: 1, height: "auto" }}
                    exit={{ opacity: 0, height: 0 }}
                    transition={{ duration: 0.2 }}
                    className="overflow-hidden"
                  >
                    <div className="mt-4 rounded-md border border-dashed border-slate-200 bg-slate-50 px-5 py-4 text-[13px] text-slate-600">
                      Selecione uma forma de pagamento para continuar.
                    </div>
                  </motion.div>
                )}
              </AnimatePresence>
            </div>

            {normalizeText(gatewayName) ? (
              <div className="mt-6 text-center text-[11px] leading-5 text-slate-500">
                O pagamento de {storeName} é processado pelo {gatewayName}.
              </div>
            ) : null}
            <div
              className={`${normalizeText(gatewayName) ? "mt-0.5" : "mt-6"} text-center text-[11px] leading-5 text-slate-500`}
            >
              Ao continuar, voce concorda com os{" "}
              <button
                type="button"
                onClick={() => setTermsOpen(true)}
                className="font-semibold underline underline-offset-2"
                style={{ color: activeMethodTheme }}
              >
                termos de compra e com a politica de privacidade
              </button>{" "}
              de {storeName}.
            </div>
          </section>

          <aside className="hidden self-start xl:sticky xl:top-5 xl:block">
            <div className="rounded-lg border border-slate-200 bg-white shadow-sm">
              <div className="rounded-t-lg px-6 py-4 text-center text-[15px] font-semibold text-white" style={{ backgroundColor: activeMethodTheme }}>
                Compra segura
              </div>
              <div className="space-y-6 px-5 py-5">
                <div>
                  <div className="text-[14px] font-semibold text-slate-900">{summaryTitle}</div>
                  <div className="mt-2 text-[13px] text-slate-500">Pagamento para {storeName}</div>
                  <div className="mt-1 text-[13px] font-medium" style={{ color: activeMethodTheme }}>Link protegido e validado</div>
                </div>

                <div className="border-t border-slate-200 pt-6">
                  <div className="text-[15px] font-semibold text-slate-900">Total</div>
                  <div className="mt-2 text-[18px] font-semibold leading-none" style={{ color: activeMethodTheme }}>
                    {formatMoney(link.amount)}
                    {link.type === "subscription" ? " / mês" : ""}
                  </div>
                  <div className="mt-2 text-[13px] text-slate-500">{summaryRecurrence}</div>
                </div>

                <div className="border-t border-slate-200 pt-6 text-center">
                  <div className="inline-flex items-center gap-1.5 text-[14px] font-semibold" style={{ color: activeMethodTheme }}>
                    <ShieldCheck className="h-4 w-4" />
                    Compra segura
                  </div>
                  <div className="mt-4 text-[13px] leading-6 text-slate-600">
                    Seus dados trafegam em ambiente seguro para concluir este pagamento para {storeName}.
                  </div>
                </div>

                <div className="border-t border-slate-200 pt-6 text-[13px] text-slate-600">
                  <div className="flex items-center justify-between">
                    <span>Tipo</span>
                    <span className="font-medium text-slate-900">{link.type === "subscription" ? "Assinatura" : "Produto único"}</span>
                  </div>
                  <div className="mt-3 flex items-center justify-between">
                    <span>Cobranca</span>
                    <span className="font-medium text-right text-slate-900">{summaryRecurrence}</span>
                  </div>
                  <div className="mt-3 flex items-center justify-between">
                    <span>Codigo</span>
                    <span className="font-medium text-slate-900">{link.code}</span>
                  </div>
                </div>
              </div>
            </div>
          </aside>
        </div>
      </div>
    </div>
  );
}
