"use client";

import { useState, useEffect, useMemo, Fragment, type ReactNode } from "react";
import Link from "next/link";
import { useRouter } from "next/navigation";
import { Elements, PaymentElement, useElements, useStripe } from "@stripe/react-stripe-js";
import { loadStripe } from "@stripe/stripe-js";
import staticCopy from "@/i18n/staticCopy.json";
import {
  DEFAULT_LOCALE,
  getStoredLocale,
  getStoredLocaleRaw,
  LOCALE_CHANGE_EVENT,
  type LocaleCode,
} from "@/i18n/localeSwitcher";

export type CheckoutPageProps = {
  cartId?: string;
};

type CheckoutSidebarCms = {
  secureTitle: string;
  secureHeaderSvg: string;
  features: { text: string; logoSvg: string }[];
  helpTitle: string;
  helpDescription: string;
  contacts: { text: string; logoSvg: string; href: string }[];
  infoCardItems: { title: string; subtitle: string }[];
};

function collectPageComponents(pageJson: unknown): any[] {
  const list: any[] = [];
  for (const sec of (pageJson as { page?: { sections?: any[] } })?.page?.sections ?? []) {
    for (const comp of sec?.components ?? []) list.push(comp);
  }
  return list;
}

function contactHrefFromText(text: string): string {
  const t = text.trim();
  if (!t) return "#";
  if (/^https?:\/\//i.test(t)) return t;
  if (t.includes("@")) return `mailto:${t}`;
  const digits = t.replace(/[^\d+]/g, "");
  if (digits.replace(/\D/g, "").length >= 6) return `tel:${digits}`;
  return "#";
}

function parseCheckoutSidebar(pageJson: unknown): CheckoutSidebarCms {
  const comps = collectPageComponents(pageJson);
  const secure = comps.find((c) => c?.type?.name === "secure_transition_card");
  const support = comps.find((c) => c?.type?.name === "supporthelp_card");
  const secureData = secure?.instance?.data ?? {};
  const featuresRaw = Array.isArray(secureData?.features?.items) ? secureData.features.items : [];
  const features = featuresRaw
    .map((item: { text?: string; logo_svg?: string }) => ({
      text: String(item?.text ?? "").trim(),
      logoSvg: typeof item?.logo_svg === "string" ? item.logo_svg : "",
    }))
    .filter((f: { text: string; logoSvg: string }) => f.text || f.logoSvg);
  const secureTitle = String(secureData?.title ?? "").trim();
  const secureHeaderSvg =
    typeof secureData?.logo_svg === "string" ? secureData.logo_svg.trim() : "";

  const supportData = support?.instance?.data ?? {};
  const supportItem = Array.isArray(supportData?.items)
    ? supportData.items[0]
    : supportData;
  const helpTitle = String(supportItem?.text ?? "").trim();
  const helpDescription = String(supportItem?.description ?? "").trim();
  const contactItems = Array.isArray(supportItem?.contact_info?.items)
    ? supportItem.contact_info.items
    : Array.isArray(supportItem?.contact_information?.items)
      ? supportItem.contact_information.items
      : [];
  const contacts = contactItems
    .map((item: { text?: string; logo_svg?: string }) => {
      const text = String(item?.text ?? "").trim();
      return {
        text,
        logoSvg: typeof item?.logo_svg === "string" ? item.logo_svg : "",
        href: contactHrefFromText(text),
      };
    })
    .filter((c: { text: string; logoSvg: string; href: string }) => c.text || c.logoSvg);

  const infoCard = comps.find((c) => c?.type?.name === "information_card");
  const infoItemsRaw = Array.isArray(infoCard?.instance?.data?.info?.items)
    ? infoCard.instance.data.info.items
    : [];
  const infoCardItems = infoItemsRaw
    .map((item: { title?: string; subtitle?: string }) => ({
      title: String(item?.title ?? "").trim(),
      subtitle: String(item?.subtitle ?? "").trim(),
    }))
    .filter((item: { title: string; subtitle: string }) => item.title || item.subtitle);

  return {
    secureTitle,
    secureHeaderSvg,
    features,
    helpTitle,
    helpDescription,
    contacts,
    infoCardItems,
  };
}

const TERMS_LINK_MARKER = "Terms & Conditions";

function renderTermsLinkInText(text: string): ReactNode {
  const idx = text.indexOf(TERMS_LINK_MARKER);
  if (idx === -1) return text;
  return (
    <>
      {text.slice(0, idx)}
      <Link href="/terms-and-conditions" className="text-[#999999] hover:underline">
        {TERMS_LINK_MARKER}
      </Link>
      {text.slice(idx + TERMS_LINK_MARKER.length)}
    </>
  );
}

function renderInformationCardSubtitle(subtitle: string): ReactNode {
  if (!subtitle) return null;
  const emailRe = /\b[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,}\b/gi;
  const chunks = subtitle.split(emailRe);
  const emails = subtitle.match(emailRe) ?? [];
  const out: ReactNode[] = [];
  chunks.forEach((chunk, i) => {
    out.push(<Fragment key={`t${i}`}>{renderTermsLinkInText(chunk)}</Fragment>);
    if (i < emails.length) {
      const e = emails[i];
      out.push(
        <a key={`m${i}`} href={`mailto:${e}`} className="text-[#999999] hover:underline">
          {e}
        </a>
      );
    }
  });
  return <>{out}</>;
}

function IconChevronDown() {
  return (
    <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
      <path d="m6 9 6 6 6-6" />
    </svg>
  );
}

function IconArrowRight() {
  return (
    <svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
      <path d="M5 12h14M12 5l7 7-7 7" />
    </svg>
  );
}

function IconArrowPay() {
  return (
    <svg xmlns="http://www.w3.org/2000/svg" width="36" height="36" viewBox="0 0 36 36" fill="none">
      <path d="M0 18C0 8.05888 8.05888 0 18 0C27.9411 0 36 8.05888 36 18C36 27.9411 27.9411 36 18 36C8.05888 36 0 27.9411 0 18Z" fill="#F7FAF8" />
      <path d="M11.9391 23.2297L23.7061 12.3882M23.7061 12.3882L14.923 11.9958M23.7061 12.3882L23.7317 21.5565" stroke="#053F31" strokeWidth="2" />
    </svg>
  );
}

type B2bAddress = {
  company?: string | null;
  first_name?: string | null;
  last_name?: string | null;
  address_1?: string | null;
  address_2?: string | null;
  city?: string | null;
  country_code?: string | null;
  postal_code?: string | null;
  phone?: string | null;
  email?: string | null;
};

type CustomerDefaultAddress = {
  address_1?: string | null;
  address_2?: string | null;
  city?: string | null;
  province?: string | null;
  postal_code?: string | null;
  country_code?: string | null;
  phone?: string | null;
  company?: string | null;
  first_name?: string | null;
  last_name?: string | null;
};

type B2bCheckoutData = {
  customer_details?: {
    email?: string | null;
    company_name?: string | null;
    tax_id?: string | null;
    phone?: string | null;
    responsible_person_name?: string | null;
    responsible_person_phone?: string | null;
    default_billing_address?: CustomerDefaultAddress | null;
    default_shipping_address?: CustomerDefaultAddress | null;
  };
  cart?: {
    email?: string | null;
    currency_code?: string;
    total?: number;
    subtotal?: number;
    shipping_total?: number;
    shipping_methods?: Array<{
      id?: string;
      name?: string;
      amount?: number;
      shipping_option_id?: string;
      data?: Record<string, unknown>;
      tax_lines?: unknown[];
    }>;
    tax_total?: number;
    metadata?: Record<string, unknown> | null;
    billing_address?: B2bAddress | null;
    shipping_address?: B2bAddress | null;
    items?: Array<{
      title?: string;
      quantity?: number;
      unit_price?: number;
      metadata?: Record<string, unknown> | null;
    }>;
    customer?: { email?: string | null } | null;
  };
  payment_options?: Array<{
    code?: string;
    label?: string;
    description?: string;
    requires_additional_action?: boolean;
    client_secret?: string;
  }>;
  countries?: Array<{
    iso_2?: string;
    display_name?: string;
    tax_rate?: number | null;
    tax_label?: string;
  }>;
  data?: {
    countries?: Array<{
      iso_2?: string;
      display_name?: string;
      tax_rate?: number | null;
      tax_label?: string;
    }>;
  };
  pricing_summary?: {
    product_title?: string;
    quantity?: number;
    quantity_unit?: string;
    tax_label?: string;
    tax_rate?: number;
  };
};

function formatCheckoutMoney(amount: number | undefined, currencyCode: string | undefined): string {
  const code = (currencyCode ?? "eur").toLowerCase();
  const sym = code === "eur" ? "€" : `${code.toUpperCase()} `;
  return `${sym}${Number(amount ?? 0).toFixed(2)}`;
}

function isStripeCardPaymentOption(opt: NonNullable<B2bCheckoutData["payment_options"]>[number]): boolean {
  const pid = (opt.code ?? "").toLowerCase();
  const code = (opt.code ?? "").toLowerCase();
  const text = `${opt.label ?? ""} ${opt.description ?? ""}`.toLowerCase();
  if (text.includes("bank transfer") || text.includes("wire transfer") || pid.includes("manual")) {
    return false;
  }
  if (pid.includes("stripe") || code.includes("stripe")) return true;
  if (/\b(credit|debit)\b/.test(text) && /\bcard\b/.test(text)) return true;
  if (text.includes("credit/debit") || text.includes("debit/credit")) return true;
  return false;
}

function StripeCardPayButton({
  cartId,
  billingData,
  shippingData,
  grandTotal,
  currencyCode,
  selectedPaymentProvider,
  termsAccepted,
  payLabels,
}: {
  cartId: string;
  billingData: { company: string; vat: string; email: string; phone: string; address: string; postal: string; city: string; country: string };
  shippingData: { company?: string; email: string; phone: string; address: string; postal: string; city: string; country: string };
  grandTotal: number;
  currencyCode: string | undefined;
  selectedPaymentProvider: string;
  termsAccepted: boolean;
  payLabels: { acceptTermsMessage: string; processing: string; confirmPay: string };
}) {
  const stripe = useStripe();
  const elements = useElements();
  const [busy, setBusy] = useState(false);
  const [msg, setMsg] = useState<string | null>(null);

  const getAuthHeaders = (): Record<string, string> => {
    try {
      const raw = typeof window !== "undefined" ? localStorage.getItem("currentUser") : null;
      const user = raw ? JSON.parse(raw) : null;
      const token = String(user?.token ?? user?.access_token ?? "").trim();
      return token ? { Authorization: `Bearer ${token}` } : {};
    } catch { return {}; }
  };

  const handlePay = async () => {
    if (!stripe || !elements || !cartId) return;
    if (!termsAccepted) { setMsg(payLabels.acceptTermsMessage); return; }

    setBusy(true);
    setMsg(null);

    const base = process.env.NEXT_PUBLIC_MEDUSA_BACKEND_URL!;
    const headers: Record<string, string> = {
      "Content-Type": "application/json",
      "x-publishable-api-key": process.env.NEXT_PUBLIC_MEDUSA_PUBLISHABLE_API_KEY || "",
      ...getAuthHeaders(),
    };

    try {
      const addrRes = await fetch(`${base}/store/checkout/${cartId}/address`, {
        method: "POST",
        headers,
        body: JSON.stringify({
          use_default_address: false,
          shipping_same_as_billing: false,
          billing_email: billingData.email,
          billing_name: billingData.company,
          billing_company_name: billingData.company,
          billing_tax_id: billingData.vat,
          billing_phone: billingData.phone,
          billing_address: billingData.address,
          billing_city: billingData.city,
          billing_province: billingData.city,
          billing_postal_code: billingData.postal,
          billing_country: billingData.country,
          shipping_email: shippingData.email,
          shipping_name: shippingData.company || billingData.company,
          shipping_company_name: shippingData.company || billingData.company,
          shipping_phone: shippingData.phone,
          shipping_address: shippingData.address,
          shipping_city: shippingData.city,
          shipping_province: shippingData.city,
          shipping_postal_code: shippingData.postal,
          shipping_country: shippingData.country,
        }),
      });
      if (!addrRes.ok) {
        const e = await addrRes.json().catch(() => ({})) as { message?: string };
        setMsg(e.message ?? "Failed to save address"); setBusy(false); return;
      }
    } catch {
      setMsg("Network error saving address"); setBusy(false); return;
    }

    let clientSecret = "";
    try {
      const sessionRes = await fetch(`${base}/store/checkout/${cartId}/payment-session`, {
        method: "POST",
        headers,
        body: JSON.stringify({ provider: selectedPaymentProvider }),
      });
      if (!sessionRes.ok) {
        const e = await sessionRes.json().catch(() => ({})) as { message?: string };
        setMsg(e.message ?? "Failed to initialize payment"); setBusy(false); return;
      }

      const sessionData = await sessionRes.json() as {
        payment_session?: { data?: { client_secret?: string } };
        payment_collection?: { payment_sessions?: Array<{ data?: { client_secret?: string } }> };
      };

      clientSecret =
        sessionData.payment_session?.data?.client_secret ??
        sessionData.payment_collection?.payment_sessions?.[0]?.data?.client_secret ?? "";

      if (!clientSecret) {
        setMsg("Could not get payment session from server");
        setBusy(false); return;
      }
    } catch {
      setMsg("Network error initializing payment session"); setBusy(false); return;
    }
    const { error: submitError } = await elements.submit();
    if (submitError) {
      setMsg(submitError.message ?? "Check your card details");
      setBusy(false); return;
    }

    const returnUrl = `${window.location.origin}/stripe-return?cart_id=${encodeURIComponent(cartId)}`;
    const { error } = await stripe.confirmPayment({
      elements,
      clientSecret,
      confirmParams: { return_url: returnUrl },
    });

    if (error) {
      setMsg(error.message ?? "Payment could not be completed");
      setBusy(false);
    }
  };

  return (
    <>
      {msg ? <p className="mb-3 font-outfit text-sm text-red-600">{msg}</p> : null}
      <div className="flex justify-end">
        <button
          type="button"
          disabled={!stripe || busy}
          onClick={() => void handlePay()}
          className="flex items-center justify-center gap-5 bg-[#0F3F32] text-white p-[7px_7px_7px_15px] cursor-pointer rounded-full font-semibold hover:bg-[#082a21] transition text-lg disabled:cursor-not-allowed disabled:opacity-60"
        >
          {busy ? payLabels.processing : payLabels.confirmPay}
          <span className="flex h-9 w-9 items-center justify-center rounded-full bg-[#1E8449] text-white">
            <IconArrowPay />
          </span>
        </button>
      </div>
    </>
  );
}

export default function CheckoutPage({ cartId = "" }: CheckoutPageProps) {
  const router = useRouter();
  const [checkoutData, setCheckoutData] = useState<B2bCheckoutData | null>(null);
  const [billingCompany, setBillingCompany] = useState("");
  const [billingVat, setBillingVat] = useState("");
  const [billingEmail, setBillingEmail] = useState("");
  const [billingPhone, setBillingPhone] = useState("");
  const [billingAddress, setBillingAddress] = useState("");
  const [billingPostal, setBillingPostal] = useState("");
  const [billingCity, setBillingCity] = useState("");

  const [shippingEmail, setShippingEmail] = useState("");
  const [shippingPhone, setShippingPhone] = useState("");
  const [shippingCompany, setShippingCompany] = useState("");
  const [shippingAddress, setShippingAddress] = useState("");
  const [shippingPostal, setShippingPostal] = useState("");
  const [shippingCity, setShippingCity] = useState("");
  const [shippingCountry, setShippingCountry] = useState("");

  const [selectedPaymentProvider, setSelectedPaymentProvider] = useState("");
  const [termsAccepted, setTermsAccepted] = useState(false);
  const [country, setCountry] = useState("");
  const [stripeIntentLoading, setStripeIntentLoading] = useState(false);
  const [stripeIntentError, setStripeIntentError] = useState<string | null>(null);
  const [stripePublishableKeyFromApi, setStripePublishableKeyFromApi] = useState("");
  const [busy, setBusy] = useState(false);
  const [sidebarCms, setSidebarCms] = useState<CheckoutSidebarCms | null>(null);
  const [uiLocale, setUiLocale] = useState<LocaleCode>(DEFAULT_LOCALE);

  const envStripePublishableKey = (process.env.NEXT_PUBLIC_STRIPE_TEST_PUBLIC_KEY ?? "").trim();
  const effectiveStripePublishableKey =
    envStripePublishableKey || stripePublishableKeyFromApi.trim();
  const stripePromise = useMemo(
    () => (effectiveStripePublishableKey ? loadStripe(effectiveStripePublishableKey) : null),
    [effectiveStripePublishableKey]
  );

  useEffect(() => {
    const id = cartId?.trim();
    if (!id) {
      setCheckoutData(null);
      setBillingCompany("");
      setBillingVat("");
      setBillingEmail("");
      setBillingPhone("");
      setBillingAddress("");
      setBillingPostal("");
      setBillingCity("");
      setCountry("");
      setSelectedPaymentProvider("");
      setStripeIntentError(null);
      setStripePublishableKeyFromApi("");
      return;
    }
    const base = process.env.NEXT_PUBLIC_MEDUSA_BACKEND_URL;
    if (!base) return;
    let cancelled = false;
    const load = async () => {
      const headers: Record<string, string> = {
        "Content-Type": "application/json",
        "x-publishable-api-key": process.env.NEXT_PUBLIC_MEDUSA_PUBLISHABLE_API_KEY || "",
        "x-medusa-locale": (getStoredLocaleRaw() ?? getStoredLocale()).trim(),
      };
      try {
        const raw = typeof window !== "undefined" ? localStorage.getItem("currentUser") : null;
        const user = raw ? JSON.parse(raw) : null;
        const authTok = String(user?.token ?? user?.access_token ?? "").trim();
        if (authTok) headers.Authorization = `Bearer ${authTok}`;
      } catch {
      }
      try {
        const res = await fetch(`${base}/store/checkout/${encodeURIComponent(id)}`, {
          method: "GET",
          headers,
          credentials: "include",
          cache: "no-store",
        });
        if (!cancelled && res.ok) {
          const data = (await res.json().catch(() => null)) as B2bCheckoutData | null;
          if (data) setCheckoutData(data);
        }
      } catch {
      }
    };
    void load();

    const onLocaleChange = () => {
      void load();
    };
    if (typeof window !== "undefined") {
      window.addEventListener(LOCALE_CHANGE_EVENT, onLocaleChange);
    }
    return () => {
      cancelled = true;
      if (typeof window !== "undefined") {
        window.removeEventListener(LOCALE_CHANGE_EVENT, onLocaleChange);
      }
    };
  }, [cartId]);

  useEffect(() => {
    let cancelled = false;
    const base = process.env.NEXT_PUBLIC_MEDUSA_BACKEND_URL;
    if (!base) return;
    const loadSidebar = async () => {
      try {
        const xMedusaLocale = (getStoredLocaleRaw() ?? getStoredLocale()).trim();
        const res = await fetch(`${base}/store/pages/check-out`, {
          method: "GET",
          headers: {
            "x-publishable-api-key": process.env.NEXT_PUBLIC_MEDUSA_PUBLISHABLE_API_KEY || "",
            "x-medusa-locale": xMedusaLocale,
          },
          cache: "no-store",
        });
        if (!res.ok || cancelled) return;
        const json = await res.json().catch(() => null);
        if (!cancelled && json) setSidebarCms(parseCheckoutSidebar(json));
      } catch {
      }
    };
    void loadSidebar();

    const onLocaleChange = () => {
      void loadSidebar();
    };
    if (typeof window !== "undefined") {
      window.addEventListener(LOCALE_CHANGE_EVENT, onLocaleChange);
    }
    return () => {
      cancelled = true;
      if (typeof window !== "undefined") {
        window.removeEventListener(LOCALE_CHANGE_EVENT, onLocaleChange);
      }
    };
  }, []);

  useEffect(() => {
    if (!checkoutData?.cart) return;
    const cart = checkoutData.cart;
    const b = cart.billing_address;
    const meta = cart.metadata;
    const companyOrName =
      (b?.company && String(b.company)) ||
      [b?.first_name, b?.last_name].filter(Boolean).join(" ").trim();
    setBillingCompany(companyOrName);
    setBillingVat(meta?.buyer_vat_number != null && meta.buyer_vat_number !== "" ? String(meta.buyer_vat_number) : "");
    setBillingEmail(String(cart.email ?? cart.customer?.email ?? ""));
    setBillingPhone(b?.phone != null ? String(b.phone) : "");
    setBillingAddress(b?.address_1 != null ? String(b.address_1) : "");
    setBillingPostal(b?.postal_code != null ? String(b.postal_code) : "");
    setBillingCity(b?.city != null ? String(b.city) : "");
    setCountry((b?.country_code ?? "").toLowerCase());

    const s = cart.shipping_address;
    setShippingEmail(s?.email ?? cart.email ?? cart.customer?.email ?? "");
    setShippingPhone(s?.phone != null ? String(s.phone) : "");
    setShippingAddress(s?.address_1 != null ? String(s.address_1) : "");
    setShippingPostal(s?.postal_code != null ? String(s.postal_code) : "");
    setShippingCity(s?.city != null ? String(s.city) : "");
    setShippingCountry((s?.country_code ?? "").toLowerCase());
    setShippingCompany(s?.company != null ? String(s.company) : "");

    const opts = checkoutData.payment_options;
    if (opts?.length) {
      setSelectedPaymentProvider((prev) =>
        prev && opts.some((o) => o.code === prev) ? prev : (opts[0]?.code ?? "")
      );
    }
  }, [checkoutData]);

  const handleNonStripeConfirm = async () => {
    if (!termsAccepted) { alert("Please accept the Terms & Conditions"); return; }
    if (!cartId) return;

    setBusy(true);
    const base = process.env.NEXT_PUBLIC_MEDUSA_BACKEND_URL!;
    const headers: Record<string, string> = {
      "Content-Type": "application/json",
      "x-publishable-api-key": process.env.NEXT_PUBLIC_MEDUSA_PUBLISHABLE_API_KEY || "",
    };
    try {
      const raw = typeof window !== "undefined" ? localStorage.getItem("currentUser") : null;
      const user = raw ? JSON.parse(raw) : null;
      const token = String(user?.token ?? user?.access_token ?? "").trim();
      if (token) headers.Authorization = `Bearer ${token}`;
    } catch { }

    try {
      const addressRes = await fetch(`${base}/store/checkout/${cartId}/address`, {
        method: "POST", headers,
        body: JSON.stringify({
          use_default_address: false,
          shipping_same_as_billing: false,
          billing_email: billingEmail,
          billing_name: billingCompany,
          billing_company_name: billingCompany,
          billing_tax_id: billingVat,
          billing_phone: billingPhone,
          billing_address: billingAddress,
          billing_city: billingCity,
          billing_province: billingCity,
          billing_postal_code: billingPostal,
          billing_country: country,
          shipping_email: shippingEmail,
          shipping_name: shippingCompany || billingCompany,
          shipping_company_name: shippingCompany || billingCompany,
          shipping_phone: shippingPhone,
          shipping_address: shippingAddress,
          shipping_city: shippingCity,
          shipping_province: shippingCity,
          shipping_postal_code: shippingPostal,
          shipping_country: shippingCountry,
        }),
      });

      if (!addressRes.ok) {
        alert("Failed to save addresses");
        setBusy(false);
        return;
      }

      const sessionRes = await fetch(`${base}/store/checkout/${cartId}/payment-session`, {
        method: "POST",
        headers,
        body: JSON.stringify({ provider: selectedPaymentProvider }),
      });
      if (!sessionRes.ok) {
        alert("Failed to initialize payment session");
        setBusy(false);
        return;
      }

      const completeRes = await fetch(`${base}/store/checkout/${cartId}/complete`, {
        method: "POST",
        headers,
        body: JSON.stringify({ provider: selectedPaymentProvider }),
      });
      const data = await completeRes.json() as { order?: { id: string } };
      if (data.order?.id) {
        localStorage.removeItem("biomket_cart_id");
        router.push(`/payment?orderId=${data.order.id}`);
      } else {
        setBusy(false);
      }
    } catch (err) {
      alert("An error occurred during checkout. Please try again.");
      setBusy(false);
    }
  };

  const fillBillingFromCustomerDetails = () => {
    const d = checkoutData?.customer_details;
    if (!d) return;

    const b = d.default_billing_address;
    if (b) {
      const addr1 = b.address_1 != null ? String(b.address_1) : "";
      const addr2Raw = b.address_2 != null ? String(b.address_2).trim() : "";
      const addressLine = addr2Raw ? `${addr1}, ${addr2Raw}` : addr1;
      setBillingAddress(addressLine);
      setBillingPostal(b.postal_code != null ? String(b.postal_code) : "");
      setBillingCity(b.city != null ? String(b.city) : "");
      setCountry(String(b.country_code ?? "").toLowerCase());

      const companyFromDetails = String(d.company_name ?? "").trim();
      const companyFromAddr = b?.company != null && String(b.company).trim() !== "" ? String(b.company) : "";
      const nameFromAddr = [b?.first_name, b?.last_name].filter(Boolean).join(" ").trim();
      setBillingCompany(companyFromDetails || companyFromAddr || nameFromAddr);
      setBillingVat(d.tax_id != null ? String(d.tax_id) : "");
      setBillingEmail(d.email != null ? String(d.email) : "");
      setBillingPhone(String(d.phone ?? b?.phone ?? "").trim());
    }

  };

  const fillShippingFromBilling = () => {
    setShippingEmail(billingEmail);
    setShippingPhone(billingPhone);
    setShippingAddress(billingAddress);
    setShippingCompany(billingCompany);
    setShippingPostal(billingPostal);
    setShippingCity(billingCity);
    setShippingCountry(country);
  };

  const cart = checkoutData?.cart;
  const pricing = checkoutData?.pricing_summary;
  const items = cart?.items ?? [];
  const titlesFromItems = items.map((i) => i.title).filter(Boolean).join(", ");
  const displayTitle = (pricing?.product_title ?? titlesFromItems) || "";
  const quantityUnitLabel =
    pricing?.quantity != null
      ? `${pricing.quantity}${pricing.quantity_unit ? ` ${pricing.quantity_unit}` : ""}`
      : items[0]?.quantity != null
        ? `${items[0].quantity}${items[0].metadata?.quantity_unit ? ` ${String(items[0].metadata.quantity_unit)}` : ""
        }`
        : "";

  const subtotal = cart?.subtotal ?? 0;
  const shippingMethods = cart?.shipping_methods ?? [];
  const shippingTotal =
    shippingMethods.length > 0
      ? Math.round(
        shippingMethods.reduce((sum, m) => sum + (Number(m.amount) || 0), 0) * 100
      ) / 100
      : (cart?.shipping_total ?? 0);
  const lineSubtotal =
    items.length > 0
      ? Math.round(
        items.reduce((sum, i) => {
          const q = Number(i.quantity) || 0;
          const meta = i.metadata;
          const base =
            meta != null &&
              meta.base_price != null &&
              String(meta.base_price).trim() !== "" &&
              !Number.isNaN(Number(meta.base_price))
              ? Number(meta.base_price)
              : Number(i.unit_price) || 0;
          return sum + q * base;
        }, 0) * 100
      ) / 100
      : subtotal;
  const currencyCode = cart?.currency_code;
  const paymentOptions = checkoutData?.payment_options ?? [];
  const rootCountries = checkoutData?.countries;
  const nestedCountries = checkoutData?.data?.countries;
  const apiCountries = ((rootCountries?.length ? rootCountries : nestedCountries) ?? []).filter((c) =>
    String(c.iso_2 ?? "").trim()
  );

  const selectedCountryMeta =
    country.trim() && apiCountries.length > 0
      ? apiCountries.find((c) => (c.iso_2 ?? "").toLowerCase() === country.toLowerCase())
      : undefined;

  let taxLabel: string;
  let vat: number;
  let total: number;
  if (selectedCountryMeta) {
    const rate = selectedCountryMeta.tax_rate;
    taxLabel =
      rate != null
        ? `VAT (${rate}%)`
        : (selectedCountryMeta.tax_label ?? "VAT");
    if (typeof rate === "number") {
      const taxableAmount = lineSubtotal + shippingTotal;
      vat = Math.round(taxableAmount * (rate / 100) * 100) / 100;
      total = Math.round((taxableAmount + vat) * 100) / 100;
    } else {
      vat = cart?.tax_total ?? 0;
      total = cart?.total ?? 0;
    }
  } else {
    taxLabel =
      pricing?.tax_rate != null
        ? `VAT (${pricing.tax_rate}%)`
        : (pricing?.tax_label ?? "VAT");
    vat = cart?.tax_total ?? 0;
    total = cart?.total ?? 0;
  }

  const grandTotal = total;
  const totalExclVatAmount = Math.round((lineSubtotal + shippingTotal) * 100) / 100;
  const grandTotalDisplay = total > 0 ? total : totalExclVatAmount;

  const selectedPaymentOption = paymentOptions.find((o) => o.code === selectedPaymentProvider);
  const stripeCardSelected = Boolean(
    selectedPaymentOption && isStripeCardPaymentOption(selectedPaymentOption)
  );

  useEffect(() => {
    if (!stripeCardSelected) {
      setStripeIntentError(null);
      setStripeIntentLoading(false);
    }
  }, [stripeCardSelected]);

  useEffect(() => {
    const syncLocale = () => setUiLocale(getStoredLocale());
    syncLocale();
    window.addEventListener("storage", syncLocale);
    window.addEventListener(LOCALE_CHANGE_EVENT, syncLocale);
    return () => {
      window.removeEventListener("storage", syncLocale);
      window.removeEventListener(LOCALE_CHANGE_EVENT, syncLocale);
    };
  }, []);

  const co = staticCopy.checkout[uiLocale];

  return (
    <div className="min-h-screen px-4 pt-8 md:px-8 lg:px-10 mb-[50px] sm:mb-12 md:mb-14 lg:mb-16 xl:mb-[70px]">
      <div className="mx-auto max-w-[1360px] 2xl:max-w-[1840px]">
        <div className="flex flex-col gap-[20px] lg:flex-row xl:max-w-[1240px] 2xl:max-w-[1440px] sm:mx-auto">
          <div className="flex-1 max-w-[925px] 2xl:max-w-[1220px]">
            <section className="mb-3 rounded-[20px] border border-[#053F31]/20 bg-[#F7FAF8] p-[30px]">
              <p className="font-outfit mb-[5px] font-normal text-[#000000]">
                {co.yourOrder}
              </p>
              <span className="font-outfit text-[22px] leading-[150%] font-semibold text-[#053F31]">
                {displayTitle}
              </span>
              <div className="border-t border-[#000000]/10 mt-5">
                <div className="flex justify-between mt-5 text-[20px] leading-[30px] font-outfit font-regular text-[#000000]">
                  <span>{co.subtotal}</span>
                  <span>{formatCheckoutMoney(lineSubtotal, currencyCode)}</span>
                </div>
                <div className="flex justify-between pt-[12px] text-[20px] leading-[30px] font-outfit font-regular text-[#000000]">
                  <span>{co.transportCost}</span>
                  <span>{formatCheckoutMoney(shippingTotal, currencyCode)}</span>
                </div>
                <div className="border-b border-[#E5E7EB] my-3" />
                <div className="flex justify-between pt-[12px] text-[20px] leading-[30px] font-outfit font-regular text-[#000000]">
                  <span>{co.totalExclVat}</span>
                  <span>{formatCheckoutMoney(lineSubtotal + shippingTotal, currencyCode)}</span>
                </div>
                <div className="flex justify-between pt-[12px] text-[20px] leading-[30px] font-outfit font-regular text-[#000000]">
                  <span>+ {taxLabel}</span>
                  <span>{formatCheckoutMoney(vat, currencyCode)}</span>
                </div>
                <div className="border-b border-[#E5E7EB] my-3" />
                <div className="flex justify-between pt-5 text-[20px] font-outfit leading-[30px] font-semibold text-[#333333]">
                  <span>{co.grandTotal}</span>
                  <span>{formatCheckoutMoney(grandTotalDisplay, currencyCode)}</span>
                </div>
              </div>
            </section>

            <section className="mb-3">
              <div className="rounded-[20px] border border-[#053F31]/20 bg-[#F7FAF8] p-[30px]">
                <div className="flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between">
                  <p className="font-outfit font-semibold text-[#053F31]">
                    {co.billingInfoTitle}
                  </p>
                  {checkoutData?.customer_details ? (
                    <button
                      type="button"
                      onClick={fillBillingFromCustomerDetails}
                      className="inline-flex items-center justify-center gap-[10px] w-full max-w-[400px] sm:w-auto shrink-0 bg-[#053F31] font-outfit text-[18px] leading-[150%] text-white font-semibold p-[7px_7px_7px_15px] cursor-pointer rounded-full border-2 hover:border-[#0F3F32] hover:bg-[#ffffff] hover:text-[#0F3F32] transition"
                    >
                      {co.sameAsRegisterDetails}
                      <IconArrowRight />
                    </button>
                  ) : null}
                </div>
                <div className="grid gap-4 sm:grid-cols-2 border-t border-[#000000]/10 mt-[15px] pt-5">
                  <div>
                    <label htmlFor="name" className="block text-[16px] font-medium text-[#000000] mb-[9px]">
                      {co.labelNameCompany} <span className="text-[#FF0000]">*</span>
                    </label>
                    <div className="relative">
                      <input
                        id="name"
                        type="text"
                        placeholder={co.placeholderCompany}
                        value={billingCompany}
                        onChange={(e) => setBillingCompany(e.target.value)}
                        className="w-full border border-[#053F31]/20 rounded-[5px] px-[30px] py-1.5 focus:outline-none focus:border-gray-300 text-[18px] leading-[150%] font-outfit font-light text-[18px] text-[#000000] placeholder:text-[#999999]"
                      />
                      <div className="absolute bottom-0 left-[30px] h-[3px] w-[60px] bg-[#053F31] z-10"></div>
                    </div>
                  </div>
                  <div>
                    <label htmlFor="vat_number" className="block text-[16px] font-medium text-[#000000] mb-[9px]">
                      {co.labelTaxId} <span className="text-[#FF0000]">*</span>
                    </label>
                    <div className="relative">
                      <input
                        id="vat_number"
                        type="text"
                        placeholder={co.placeholderTaxId}
                        value={billingVat}
                        onChange={(e) => setBillingVat(e.target.value)}
                        className="w-full border border-[#053F31]/20 rounded-[5px] px-[30px] py-1.5 focus:outline-none focus:border-gray-300 text-[18px] leading-[150%] font-outfit font-light text-[18px] text-[#000000] placeholder:text-[#999999]"
                      />
                      <div className="absolute bottom-0 left-[30px] h-[3px] w-[60px] bg-[#053F31] z-10"></div>
                    </div>
                  </div>
                  <div>
                    <label htmlFor="mail" className="block text-[16px] font-medium text-[#000000] mb-[9px]">
                      {co.labelEmail} <span className="text-[#FF0000]">*</span>
                    </label>
                    <div className="relative">
                      <input
                        id="mail"
                        type="text"
                        placeholder={co.placeholderEmail}
                        value={billingEmail}
                        onChange={(e) => setBillingEmail(e.target.value)}
                        className="w-full border border-[#053F31]/20 rounded-[5px] px-[30px] py-1.5 focus:outline-none focus:border-gray-300 text-[18px] leading-[150%] font-outfit font-light text-[18px] text-[#000000] placeholder:text-[#999999]"
                      />
                      <div className="absolute bottom-0 left-[30px] h-[3px] w-[60px] bg-[#053F31] z-10"></div>
                    </div>
                  </div>
                  <div>
                    <label htmlFor="phone" className="block text-[16px] font-medium text-[#000000] mb-[9px]">
                      {co.labelPhone} <span className="text-[#FF0000]">*</span>
                    </label>
                    <div className="relative">
                      <input
                        id="phone"
                        type="text"
                        placeholder={co.placeholderPhone}
                        value={billingPhone}
                        onChange={(e) => setBillingPhone(e.target.value)}
                        className="w-full border border-[#053F31]/20 rounded-[5px] px-[30px] py-1.5 focus:outline-none focus:border-gray-300 text-[18px] leading-[150%] font-outfit font-light text-[18px] text-[#000000] placeholder:text-[#999999]"
                      />
                      <div className="absolute bottom-0 left-[30px] h-[3px] w-[60px] bg-[#053F31] z-10"></div>
                    </div>
                  </div>
                  <div className="w-full sm:col-span-2">
                    <label htmlFor="address" className="block text-[16px] font-medium text-[#000000] mb-[9px]">
                      {co.labelBillingAddress} <span className="text-[#FF0000]">*</span>
                    </label>
                    <div className="relative w-full">
                      <input
                        id="address"
                        type="text"
                        placeholder={co.placeholderStreetAddress}
                        value={billingAddress}
                        onChange={(e) => setBillingAddress(e.target.value)}
                        className="w-full border border-[#053F31]/20 rounded-[5px] px-[30px] py-1.5 focus:outline-none focus:border-gray-300 text-[18px] leading-[150%] font-outfit font-light text-[18px] text-[#000000] placeholder:text-[#999999]"
                      />
                      <div className="absolute bottom-0 left-[30px] h-[3px] w-[60px] bg-[#053F31] z-10"></div>
                    </div>
                  </div>
                  <div>
                    <label htmlFor="code" className="block text-[16px] font-medium text-[#000000] mb-[9px]">
                      {co.labelPostalCode} <span className="text-[#FF0000]">*</span>
                    </label>
                    <div className="relative">
                      <input
                        id="code"
                        type="text"
                        placeholder={co.placeholderPostalCode}
                        value={billingPostal}
                        onChange={(e) => setBillingPostal(e.target.value)}
                        className="w-full border border-[#053F31]/20 rounded-[5px] px-[30px] py-1.5 focus:outline-none focus:border-gray-300 text-[18px] leading-[150%] font-outfit font-light text-[18px] text-[#000000] placeholder:text-[#999999]"
                      />
                      <div className="absolute bottom-0 left-[30px] h-[3px] w-[60px] bg-[#053F31] z-10"></div>
                    </div>
                  </div>
                  <div>
                    <label htmlFor="city" className="block text-[16px] font-medium text-[#000000] mb-[9px]">
                      {co.labelCity} <span className="text-[#FF0000]">*</span>
                    </label>
                    <div className="relative">
                      <input
                        id="city"
                        type="text"
                        placeholder={co.placeholderCity}
                        value={billingCity}
                        onChange={(e) => setBillingCity(e.target.value)}
                        className="w-full border border-[#053F31]/20 rounded-[5px] px-[30px] py-1.5 focus:outline-none focus:border-gray-300 text-[18px] leading-[150%] font-outfit font-light text-[18px] text-[#000000] placeholder:text-[#999999]"
                      />
                      <div className="absolute bottom-0 left-[30px] h-[3px] w-[60px] bg-[#053F31] z-10"></div>
                    </div>
                  </div>
                  <div className="w-full sm:col-span-2">
                    <label htmlFor="country" className="block text-[16px] font-medium text-[#000000] mb-[9px]">
                      {co.labelCountry} <span className="text-[#FF0000]">*</span>
                    </label>
                    <div className="relative w-full">
                      <select
                        id="country"
                        value={country}
                        onChange={(e) => setCountry(e.target.value)}
                        className="w-full appearance-none bg-[#F7FAF8] border border-[#E0E0E0] rounded-[5px] pl-4 pr-10 py-3 focus:outline-none focus:border-[#053F31]/20 font-outfit font-light text-[18px] text-[#333333]"
                      >
                        {apiCountries.length > 0 ? (
                          [
                            <option key="country-placeholder" value="">
                              {co.selectCountry}
                            </option>,
                            ...apiCountries.map((c, idx) => {
                              const code = String(c.iso_2 ?? "").toLowerCase();
                              return (
                                <option
                                  key={code ? `${code}-${idx}` : `country-${idx}`}
                                  value={code}
                                >
                                  {c.display_name ?? c.iso_2 ?? ""}
                                </option>
                              );
                            }),
                          ]
                        ) : (
                          <></>
                        )}
                      </select>
                      <span className="pointer-events-none absolute right-3 top-1/2 -translate-y-1/2 text-[#053F31]">
                        <IconChevronDown />
                      </span>
                      <div className="absolute bottom-0 left-[60px] h-[3px] w-[60px] -translate-x-1/2 bg-[#053F31] z-10"></div>
                    </div>
                  </div>
                </div>
              </div>
            </section>

            <section className="mb-3">
              <div className="rounded-[20px] border border-[#053F31]/20 bg-[#F7FAF8] p-[30px]">
                <div className="flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between">
                  <p className="font-outfit font-semibold text-[#053F31]">
                    {co.shippingInfoTitle}
                  </p>
                  <button
                    type="button"
                    onClick={fillShippingFromBilling}
                    className="inline-flex items-center justify-center gap-[10px] w-full max-w-[400px] sm:w-auto shrink-0 bg-[#053F31] font-outfit text-[18px] leading-[150%] text-white font-semibold p-[7px_7px_7px_15px] cursor-pointer rounded-full border-2 hover:border-[#0F3F32] hover:bg-[#ffffff] hover:text-[#0F3F32] transition"
                  >
                    {co.sameAsBillingDetails}
                    <IconArrowRight />
                  </button>
                </div>
                <div className="grid gap-4 sm:grid-cols-2 border-t border-[#000000]/10 mt-[15px] pt-5">
                  <div>
                    <label htmlFor="shipping_mail" className="block text-[16px] font-medium text-[#000000] mb-[9px]">
                      {co.labelEmail} <span className="text-[#FF0000]">*</span>
                    </label>
                    <div className="relative">
                      <input
                        id="shipping_mail"
                        type="text"
                        placeholder={co.placeholderEmail}
                        value={shippingEmail}
                        onChange={(e) => setShippingEmail(e.target.value)}
                        className="w-full border border-[#053F31]/20 rounded-[5px] px-[30px] py-1.5 focus:outline-none focus:border-gray-300 text-[18px] leading-[150%] font-outfit font-light text-[18px] text-[#000000] placeholder:text-[#999999]"
                      />
                      <div className="absolute bottom-0 left-[30px] h-[3px] w-[60px] bg-[#053F31] z-10"></div>
                    </div>
                  </div>
                  <div>
                    <label htmlFor="shipping_phone" className="block text-[16px] font-medium text-[#000000] mb-[9px]">
                      {co.labelPhone} <span className="text-[#FF0000]">*</span>
                    </label>
                    <div className="relative">
                      <input
                        id="shipping_phone"
                        type="text"
                        placeholder={co.placeholderPhone}
                        value={shippingPhone}
                        onChange={(e) => setShippingPhone(e.target.value)}
                        className="w-full border border-[#053F31]/20 rounded-[5px] px-[30px] py-1.5 focus:outline-none focus:border-gray-300 text-[18px] leading-[150%] font-outfit font-light text-[18px] text-[#000000] placeholder:text-[#999999]"
                      />
                      <div className="absolute bottom-0 left-[30px] h-[3px] w-[60px] bg-[#053F31] z-10"></div>
                    </div>
                  </div>
                  <div className="w-full sm:col-span-2">
                    <label htmlFor="shipping_address" className="block text-[16px] font-medium text-[#000000] mb-[9px]">
                      {co.labelShippingAddress} <span className="text-[#FF0000]">*</span>
                    </label>
                    <div className="relative w-full">
                      <input
                        id="shipping_address"
                        type="text"
                        placeholder={co.placeholderStreetAddress}
                        value={shippingAddress}
                        onChange={(e) => setShippingAddress(e.target.value)}
                        className="w-full border border-[#053F31]/20 rounded-[5px] px-[30px] py-1.5 focus:outline-none focus:border-gray-300 text-[18px] leading-[150%] font-outfit font-light text-[18px] text-[#000000] placeholder:text-[#999999]"
                      />
                      <div className="absolute bottom-0 left-[30px] h-[3px] w-[60px] bg-[#053F31] z-10"></div>
                    </div>
                  </div>
                  <div>
                    <label htmlFor="shipping_code" className="block text-[16px] font-medium text-[#000000] mb-[9px]">
                      {co.labelPostalCode} <span className="text-[#FF0000]">*</span>
                    </label>
                    <div className="relative">
                      <input
                        id="shipping_code"
                        type="text"
                        placeholder={co.placeholderPostalCode}
                        value={shippingPostal}
                        onChange={(e) => setShippingPostal(e.target.value)}
                        className="w-full border border-[#053F31]/20 rounded-[5px] px-[30px] py-1.5 focus:outline-none focus:border-gray-300 text-[18px] leading-[150%] font-outfit font-light text-[18px] text-[#000000] placeholder:text-[#999999]"
                      />
                      <div className="absolute bottom-0 left-[30px] h-[3px] w-[60px] bg-[#053F31] z-10"></div>
                    </div>
                  </div>
                  <div>
                    <label htmlFor="shipping_city" className="block text-[16px] font-medium text-[#000000] mb-[9px]">
                      {co.labelCity} <span className="text-[#FF0000]">*</span>
                    </label>
                    <div className="relative">
                      <input
                        id="shipping_city"
                        type="text"
                        placeholder={co.placeholderCity}
                        value={shippingCity}
                        onChange={(e) => setShippingCity(e.target.value)}
                        className="w-full border border-[#053F31]/20 rounded-[5px] px-[30px] py-1.5 focus:outline-none focus:border-gray-300 text-[18px] leading-[150%] font-outfit font-light text-[18px] text-[#000000] placeholder:text-[#999999]"
                      />
                      <div className="absolute bottom-0 left-[30px] h-[3px] w-[60px] bg-[#053F31] z-10"></div>
                    </div>
                  </div>
                  <div className="w-full sm:col-span-2">
                    <label htmlFor="shipping_country" className="block text-[16px] font-medium text-[#000000] mb-[9px]">
                      {co.labelCountry} <span className="text-[#FF0000]">*</span>
                    </label>
                    <div className="relative w-full">
                      <select
                        id="shipping_country"
                        value={shippingCountry}
                        onChange={(e) => setShippingCountry(e.target.value)}
                        className="w-full appearance-none bg-[#F7FAF8] border border-[#E0E0E0] rounded-[5px] pl-4 pr-10 py-3 focus:outline-none focus:border-[#053F31]/20 font-outfit font-light text-[18px] text-[#333333]"
                      >
                        {apiCountries.length > 0 ? (
                          [
                            <option key="country-placeholder-shipping" value="">
                              {co.selectCountry}
                            </option>,
                            ...apiCountries.map((c, idx) => {
                              const code = String(c.iso_2 ?? "").toLowerCase();
                              return (
                                <option
                                  key={code ? `${code}-${idx}` : `country-${idx}`}
                                  value={code}
                                >
                                  {c.display_name ?? c.iso_2 ?? ""}
                                </option>
                              );
                            }),
                          ]
                        ) : (
                          <></>
                        )}
                      </select>
                      <span className="pointer-events-none absolute right-3 top-1/2 -translate-y-1/2 text-[#053F31]">
                        <IconChevronDown />
                      </span>
                      <div className="absolute bottom-0 left-[60px] h-[3px] w-[60px] -translate-x-1/2 bg-[#053F31] z-10"></div>
                    </div>
                  </div>
                </div>
              </div>
            </section>

            <section className="mb-3">
              <div className="rounded-[20px] border border-[#053F31]/20 bg-[#F7FAF8] p-[30px]">
                <p className="font-outfit font-semibold text-[#053F31]">
                  {co.paymentMethodTitle}
                </p>
                <div className="space-y-5 border-t border-[#000000]/10 mt-[15px] pt-5">
                  {paymentOptions.length > 0 ? (
                    paymentOptions.map((opt) => {
                      const pid = opt.code ?? "";
                      const selected = selectedPaymentProvider === pid;
                      return (
                        <button
                          key={pid || `${opt.code}-${opt.label}`}
                          type="button"
                          onClick={() => pid && setSelectedPaymentProvider(pid)}
                          className={`flex w-full items-start gap-5 rounded-[16px] border-2 p-5 text-left transition-colors ${selected
                            ? "border-[#053F31]/10 bg-[#E8F5E9]"
                            : "border-[#053F31]/10 hover:border-[#cccccc]"
                            }`}
                        >
                          <span
                            className={`mt-1.5 flex h-5 w-5 shrink-0 items-center justify-center rounded-full border-1 ${selected ? "border-[#053F31] bg-[#ffffff]" : "border-[#053F31]"
                              }`}
                          >
                            {selected && <span className="h-3.5 w-3.5 rounded-full bg-[#053F31]" />}
                          </span>
                          <div className="flex flex-col">
                            <span className="font-outfit text-[16px] font-medium text-[#000000]">
                              {opt.label ?? opt.code ?? co.paymentOptionFallback}
                            </span>
                            {opt.description ? (
                              <span className="mt-1 font-outfit font-light text-[#999999]">{opt.description}</span>
                            ) : null}
                          </div>
                        </button>
                      );
                    })
                  ) : (
                    <p className="font-outfit font-light text-[#999999] text-[16px]">
                      {co.paymentOptionsEmpty}
                    </p>
                  )}
                  {stripeCardSelected &&
                    (stripeIntentLoading ||
                      stripePromise ||
                      Boolean(stripeIntentError)) ? (
                    <div className="space-y-3 border-t border-[#000000]/10 pt-5">
                      {stripeIntentLoading ? (
                        <p className="font-outfit text-[16px] font-light text-[#757575]">
                          {co.preparingCardPayment}
                        </p>
                      ) : null}
                      {stripeIntentError ? (
                        <p className="font-outfit text-[14px] text-red-600">{stripeIntentError}</p>
                      ) : null}
                      {stripePromise && stripeCardSelected ? (
                        <Elements
                          stripe={stripePromise}
                          options={{
                            mode: "payment",
                            amount: Math.round(grandTotal * 100) || 100,
                            currency: (currencyCode ?? "eur").toLowerCase(),
                          }}
                        >
                          <div className="rounded-[16px] border border-[#E0E0E0] bg-white p-4">
                            <PaymentElement />
                          </div>
                          <div className="mt-5 rounded-[16px] border border-[#E0E0E0] bg-[#F7FAF8] p-5">
                            <label className="flex w-full cursor-pointer items-start gap-5 border-b border-[#000000]/10 pb-[15px]">
                              <input
                                type="checkbox"
                                checked={termsAccepted}
                                onChange={(e) => setTermsAccepted(e.target.checked)}
                                className="mt-1.5 h-5 w-5 shrink-0 rounded border-1 border-[#053F31] bg-[#F7FAF8]"
                              />
                              <p className="font-outfit font-medium text-[#000000]">
                                {co.termsAcceptPrefix}{" "}
                                <Link href="/terms" className="underline hover:opacity-90">
                                  {co.termsLinkLabel}
                                </Link>{" "}
                                {co.termsBetweenLinks}{" "}
                                <Link href="/privacy" className="underline hover:opacity-90">
                                  {co.privacyLinkLabel}
                                </Link>{" "}
                                <span>*</span>
                              </p>
                            </label>
                            <div className="mt-5 rounded-[16px] border border-[#E0E0E0] bg-[#E6EEE7] p-5">
                              <p
                                className="font-outfit font-light text-[#999999] leading-[150%]"
                                style={{ fontSize: "18px" }}
                              >
                                {co.postPaymentNote}
                              </p>
                            </div>
                          </div>
                          <div className="mt-5">
                            <StripeCardPayButton
                              cartId={cartId}
                              billingData={{ company: billingCompany, vat: billingVat, email: billingEmail, phone: billingPhone, address: billingAddress, postal: billingPostal, city: billingCity, country }}
                              shippingData={{ company: billingCompany, email: shippingEmail, phone: shippingPhone, address: shippingAddress, postal: shippingPostal, city: shippingCity, country: shippingCountry }}
                              grandTotal={grandTotal}
                              currencyCode={currencyCode}
                              selectedPaymentProvider={selectedPaymentProvider}
                              termsAccepted={termsAccepted}
                              payLabels={{
                                acceptTermsMessage: co.stripeAcceptTerms,
                                processing: co.processing,
                                confirmPay: co.confirmAndPay,
                              }}
                            />
                          </div>
                        </Elements>
                      ) : null}
                    </div>
                  ) : null}
                </div>
              </div>
            </section>

            {!(stripeCardSelected && stripePromise) ? (
              <section className="mb-3">
                <div className="rounded-[20px] border border-[#053F31]/20 bg-[#F7FAF8] p-[30px]">
                  <label className="flex w-full cursor-pointer items-start gap-5 border-b border-[#000000]/10 pb-[15px]">
                    <input
                      type="checkbox"
                      checked={termsAccepted}
                      onChange={(e) => setTermsAccepted(e.target.checked)}
                      className="mt-1.5 h-5 w-5 shrink-0 rounded border-1 border-[#053F31] bg-[#F7FAF8]"
                    />
                    <p className="font-outfit font-medium text-[#000000]">
                      {co.termsAcceptPrefix}{" "}
                      <Link href="/terms" className="underline hover:opacity-90">
                        {co.termsLinkLabel}
                      </Link>{" "}
                      {co.termsBetweenLinks}{" "}
                      <Link href="/privacy" className="underline hover:opacity-90">
                        {co.privacyLinkLabel}
                      </Link>{" "}
                      <span>*</span>
                    </p>
                  </label>
                  <div className="mt-5 rounded-[16px] border border-[#E0E0E0] bg-[#E6EEE7] p-5">
                    <p className="font-outfit font-light text-[#999999] leading-[150%]" style={{ fontSize: "18px" }}>
                      {co.postPaymentNote}
                    </p>
                  </div>
                </div>
              </section>
            ) : null}

            {!stripeCardSelected ? (
              <div className="flex justify-end">
                <button
                  type="button"
                  onClick={handleNonStripeConfirm}
                  disabled={busy}
                  className="flex items-center justify-center gap-5 bg-[#0F3F32] text-white p-[7px_7px_7px_15px] cursor-pointer rounded-full font-semibold hover:bg-[#082a21] transition text-lg disabled:cursor-not-allowed disabled:opacity-50"
                >
                  {busy ? co.processing : co.confirmAndPay}
                  <span className="flex h-9 w-9 items-center justify-center rounded-full bg-[#1E8449] text-white">
                    <IconArrowPay />
                  </span>
                </button>
              </div>
            ) : null}

          </div>

          <aside className="flex shrink-0 flex-col gap-[22px] w-full lg:w-[415px] 2xl:w-[600px]">
            {sidebarCms &&
            (sidebarCms.secureTitle ||
              sidebarCms.secureHeaderSvg ||
              sidebarCms.features.length > 0) ? (
              <div className="rounded-[20px] border border-[#053F31]/20 bg-[#F7FAF8] p-[32px] mt-[28px] md:mt-0">
                {sidebarCms.secureTitle || sidebarCms.secureHeaderSvg ? (
                  <div className="flex items-center gap-[10px] border-b border-[#000000]/10 pb-[15px]">
                    {sidebarCms.secureHeaderSvg ? (
                      <span
                        className="inline-flex shrink-0 [&_svg]:block"
                        dangerouslySetInnerHTML={{ __html: sidebarCms.secureHeaderSvg }}
                        aria-hidden
                      />
                    ) : null}
                    {sidebarCms.secureTitle ? (
                      <div className="font-outfit block text-[18px] leading-[150%] font-semibold text-[#053F31]">
                        {sidebarCms.secureTitle}
                      </div>
                    ) : null}
                  </div>
                ) : null}
                <ul className="flex flex-col gap-5 pt-5">
                  {sidebarCms.features.map((f, idx) => (
                    <li key={`${f.text}-${idx}`} className="flex items-center gap-[10px]">
                      {f.logoSvg ? (
                        <span
                          className="inline-flex shrink-0 [&_svg]:block"
                          dangerouslySetInnerHTML={{ __html: f.logoSvg }}
                          aria-hidden
                        />
                      ) : null}
                      {f.text ? (
                        <span className="font-outfit font-light text-[16px] text-[#000000] leading-7">
                          {f.text}
                        </span>
                      ) : null}
                    </li>
                  ))}
                </ul>
              </div>
            ) : null}

            {sidebarCms &&
            (sidebarCms.helpTitle || sidebarCms.helpDescription || sidebarCms.contacts.length > 0) ? (
              <div className="rounded-[20px] border border-[#053F31]/10 bg-[#DAE6DC]/70 p-[30px]">
                {sidebarCms.helpTitle ? (
                  <div className="border-b border-[#000000]/10 pb-[15px]">
                    <span className="font-outfit text-[18px] leading-[150%] font-semibold text-[#053F31]">
                      {sidebarCms.helpTitle}
                    </span>
                  </div>
                ) : null}
                {sidebarCms.helpDescription ? (
                  <p className="mb-5 pt-5 font-outfit text-[#424242] font-light">{sidebarCms.helpDescription}</p>
                ) : null}
                {sidebarCms.contacts.map((c, idx) => (
                  <a
                    key={`${c.text}-${idx}`}
                    href={c.href}
                    className={
                      idx > 0
                        ? "mt-[10px] flex items-center gap-3 font-outfit leading-[150%] text-[20px] font-medium text-[#053F31]"
                        : "flex items-center gap-3 font-outfit leading-[150%] text-[20px] font-medium text-[#053F31]"
                    }
                  >
                    {c.logoSvg ? (
                      <span
                        className="inline-flex shrink-0 [&_svg]:block"
                        dangerouslySetInnerHTML={{ __html: c.logoSvg }}
                        aria-hidden
                      />
                    ) : null}
                    {c.text}
                  </a>
                ))}
              </div>
            ) : null}
          </aside>
        </div>

        {sidebarCms?.infoCardItems?.length ? (
          <div className="xl:max-w-[1240px] 2xl:max-w-[1440px] sm:mx-auto">
            <div className="w-full md:max-w-[533px] 2xl:max-w-[820px] p-[30px] md:mt-[30px] mt-[10px] flex flex-col overflow-hidden rounded-xl border border-[#053F31]/20 bg-[#F7FAF8] sm:flex-row">
              {sidebarCms.infoCardItems.map((row, idx) => (
                <div
                  key={`${row.title}-${idx}`}
                  className={
                    idx === 0
                      ? "flex-1 pr-0 md:pr-[18px] sm:border-r sm:border-[#E0E0E0]"
                      : "flex-1 pl-0 pt-6 md:pl-[18px] sm:pt-0"
                  }
                >
                  {row.title ? (
                    <p className="font-outfit mb-[5px] font-medium text-[#000000]">{row.title}</p>
                  ) : null}
                  {row.subtitle ? (
                    <span className="font-outfit font-light text-[#999999]">
                      {renderInformationCardSubtitle(row.subtitle)}
                    </span>
                  ) : null}
                </div>
              ))}
            </div>
          </div>
        ) : null}
      </div>
    </div>
  );
}
