"use client";

import type {
  TrialPaymentScreenDefinition,
  DefaultTexts,
  FunnelDefinition,
} from "@/lib/funnel/types";
import { TemplateLayout } from "../layouts/TemplateLayout";
import { createTemplateLayoutProps } from "@/lib/funnel/templateHelpers";
import { cn } from "@/lib/utils";
import { useRef, useState } from "react";
import {
  Header,
  JoinedToday,
  TrustedByOver,
  JoinedTodayWithAvatars,
} from "@/components/domains/TrialPayment";
import { UnlockYourSketch } from "@/components/domains/TrialPayment/Cards";
import {
  FindingOneGuide,
  TryForDays,
  TotalPrice,
  PaymentButtons,
  UsersPortraits,
} from "@/components/domains/TrialPayment/Cards";
import { MoneyBackGuarantee, Policy } from "@/components/domains/TrialPayment";
import {
  StepsToSeeSoulmate,
  Reviews,
  CommonQuestions,
  StillHaveQuestions,
  Footer,
} from "@/components/domains/TrialPayment/Cards";
import ProgressToSeeSoulmate from "@/components/domains/TrialPayment/ProgressToSeeSoulmate/ProgressToSeeSoulmate";
import { buildTypographyProps } from "@/lib/funnel/mappers";
import { usePaymentPlacement } from "@/hooks/payment/usePaymentPlacement";
import { Spinner } from "@/components/ui/spinner";
import { Currency } from "@/shared/types";
import { getFormattedPrice } from "@/shared/utils/price";
import { useClientToken } from "@/hooks/auth/useClientToken";

function getTrackingCookiesForRedirect() {
  const cookieObj = Object.fromEntries(
    document.cookie.split("; ").map((c) => c.split("="))
  );

  const result = Object.entries(cookieObj).filter(([key]) => {
    return (
      [
        "_fbc",
        "_fbp",
        "_ym_uid",
        "_ym_d",
        "_ym_isad",
        "_ym_visorc",
        "yandexuid",
        "ymex",
      ].includes(key) ||
      key.startsWith("_ga") ||
      key.startsWith("_gid")
    );
  });

  const queryString = result
    .map(
      ([key, value]) =>
        `${encodeURIComponent(key)}=${encodeURIComponent(String(value))}`
    )
    .join("&");

  return queryString;
}

interface TrialPaymentTemplateProps {
  funnel: FunnelDefinition;
  screen: TrialPaymentScreenDefinition;
  onContinue: () => void;
  canGoBack: boolean;
  onBack: () => void;
  screenProgress?: { current: number; total: number };
  defaultTexts?: DefaultTexts;
}

export function TrialPaymentTemplate({
  funnel,
  screen,
  canGoBack,
  onBack,
  screenProgress,
  defaultTexts,
}: TrialPaymentTemplateProps) {
  const token = useClientToken();

  // TODO: выбрать корректный paymentId для этого экрана (ключ из backend), временно "main"
  const paymentId = "main";
  const { placement, isLoading } = usePaymentPlacement({ funnel, paymentId });

  const trialInterval = placement?.trialInterval || 7;
  const trialPeriod = placement?.trialPeriod;
  const variant = placement?.variants?.[0];
  const productId = variant?.id || "";
  const placementId = placement?.placementId || "";
  const paywallId = placement?.paywallId || "";
  const trialPrice = variant?.trialPrice || 0;
  const price = variant?.price || 0;
  const oldPrice = variant?.price || 0;
  const billingPeriod = placement?.billingPeriod;
  const billingInterval = placement?.billingInterval || 1;
  const currency = placement?.currency || Currency.USD;
  const paymentUrl = placement?.paymentUrl || "";

  const [loadingButtonIndex, setLoadingButtonIndex] = useState<number>();

  const handlePayClick = (buttonIndex: number) => {
    if (!!loadingButtonIndex || loadingButtonIndex === 0) {
      return;
    }
    setLoadingButtonIndex(buttonIndex);
    const redirectUrl = `${paymentUrl}?paywallId=${paywallId}&placementId=${placementId}&productId=${productId}&jwtToken=${token}&price=${(
      (trialPrice || 100) / 100
    ).toFixed(2)}&currency=${currency}&${getTrackingCookiesForRedirect()}`;
    return window.location.replace(redirectUrl);
  };

  const paymentSectionRef = useRef<HTMLDivElement | null>(null);

  const scrollToPayment = () => {
    if (paymentSectionRef.current) {
      paymentSectionRef.current.scrollIntoView({
        behavior: "smooth",
        block: "end", // Policy text at bottom of screen
      });
    }
  };

  const formatPeriod = (
    period: "DAY" | "WEEK" | "MONTH" | "YEAR" | undefined,
    interval: number
  ) => {
    if (!period) return `${interval} days`;
    const unit =
      period === "DAY"
        ? interval === 1
          ? "day"
          : "days"
        : period === "WEEK"
        ? interval === 1
          ? "week"
          : "weeks"
        : period === "MONTH"
        ? interval === 1
          ? "month"
          : "months"
        : interval === 1
        ? "year"
        : "years";
    return `${interval} ${unit}`;
  };

  const formattedTrialPrice = getFormattedPrice(trialPrice, currency);
  const formattedBillingPrice = getFormattedPrice(price, currency);
  const trialPeriodText = formatPeriod(trialPeriod, trialInterval);
  const billingPeriodText = formatPeriod(billingPeriod, billingInterval);

  const computeDiscountPercent = () => {
    if (!oldPrice || !trialPrice || oldPrice <= 0) return undefined;
    const ratio = 1 - trialPrice / oldPrice;
    const percent = Math.max(0, Math.min(100, Math.round(ratio * 100)));
    return String(percent);
  };

  const formatPeriodHyphen = (
    period: "DAY" | "WEEK" | "MONTH" | "YEAR" | undefined,
    interval: number
  ) => {
    if (!period) return `${interval}-day`;
    const unit =
      period === "DAY"
        ? interval === 1
          ? "day"
          : "days"
        : period === "WEEK"
        ? interval === 1
          ? "week"
          : "weeks"
        : period === "MONTH"
        ? interval === 1
          ? "month"
          : "months"
        : interval === 1
        ? "year"
        : "years";
    return `${interval}-${unit}`;
  };

  const trialPeriodHyphenText = formatPeriodHyphen(trialPeriod, trialInterval);

  const replacePlaceholders = (text: string | undefined) => {
    if (!text) return "";
    const values: Record<string, string> = {
      trialPrice: formattedTrialPrice,
      billingPrice: formattedBillingPrice,
      oldPrice: getFormattedPrice(oldPrice || 0, currency),
      discountPercent: computeDiscountPercent() ?? "",
      trialPeriod: trialPeriodText,
      billingPeriod: billingPeriodText,
      trialPeriodHyphen: trialPeriodHyphenText,
    };
    let result = text;
    for (const [key, value] of Object.entries(values)) {
      result = result.replaceAll(`{{${key}}}`, value);
    }
    return result;
  };

  // Отключаем общий Header в TemplateLayout для этого экрана
  const screenWithoutHeader = {
    ...screen,
    header: {
      ...(screen.header || {}),
      show: false,
      showBackButton: false,
      showProgress: false,
    },
  } as typeof screen;

  // Убираем title/subtitle из общего Layout для этого экрана
  const screenForLayout = {
    ...screenWithoutHeader,
    title: undefined,
    subtitle: undefined,
  } as typeof screenWithoutHeader;

  const layoutProps = createTemplateLayoutProps(
    screenForLayout,
    { canGoBack, onBack },
    screenProgress,
    {
      preset: "center",
      actionButton:
        screen.bottomActionButton?.show === false
          ? undefined
          : {
              defaultText: defaultTexts?.nextButton || "Continue",
              disabled: false,
              onClick: scrollToPayment,
            },
    }
  );

  if (isLoading || !placement || !token) {
    return (
      <div className="w-full min-h-dvh max-w-[560px] mx-auto flex items-center justify-center">
        <Spinner className="size-8" />
      </div>
    );
  }

  return (
    <TemplateLayout
      {...layoutProps}
      contentProps={{ className: "p-0 pt-0" }}
      childrenWrapperProps={{ className: "mt-0" }}
    >
      <div
        className={cn(
          "w-full min-h-dvh max-w-[560px] mx-auto bg-trial-payment-secondary",
          "px-[17px] py-1.5 pb-[82px]",
          "flex flex-col items-center"
        )}
      >
        {/* Header block */}
        {screen.headerBlock && (
          <Header
            className="mt-3 sticky top-[18px] z-30"
            text={buildTypographyProps(screen.headerBlock.text, {
              as: "p",
              defaults: { font: "inter", weight: "semiBold", size: "sm" },
            })}
            timer={buildTypographyProps(screen.headerBlock.timer, {
              as: "span",
              defaults: { font: "inter", weight: "bold", size: "2xl" },
            })}
            timerHookProps={{
              initialSeconds: screen.headerBlock.timerSeconds ?? 600,
            }}
            button={{
              children: "Get Sketch",
              onClick: scrollToPayment,
            }}
          />
        )}

        {/* UnlockYourSketch section */}
        {screen.unlockYourSketch && (
          <UnlockYourSketch
            title={buildTypographyProps(screen.unlockYourSketch.title, {
              as: "h3",
              defaults: { font: "inter", weight: "bold", color: "default" },
            })}
            subtitle={buildTypographyProps(screen.unlockYourSketch.subtitle, {
              as: "p",
              defaults: {
                font: "inter",
                weight: "semiBold",
                size: "xl",
                color: "default",
                align: "center",
              },
            })}
            image={
              screen.unlockYourSketch.image
                ? { src: screen.unlockYourSketch.image.src, alt: "portrait" }
                : undefined
            }
            blur={{
              text: {
                ...(buildTypographyProps(screen.unlockYourSketch.blur?.text, {
                  as: "p",
                  defaults: {
                    font: "inter",
                    weight: "semiBold",
                    align: "center",
                  },
                }) ?? { as: "p", children: "" }),
                className: "text-[#A16207]",
              },
              icon:
                screen.unlockYourSketch.blur?.icon === "lock" ? (
                  <svg
                    width="18"
                    height="21"
                    viewBox="0 0 18 21"
                    fill="none"
                    xmlns="http://www.w3.org/2000/svg"
                  >
                    <path
                      d="M5.625 6.125V8H11.875V6.125C11.875 4.39844 10.4766 3 8.75 3C7.02344 3 5.625 4.39844 5.625 6.125ZM3.125 8V6.125C3.125 3.01953 5.64453 0.5 8.75 0.5C11.8555 0.5 14.375 3.01953 14.375 6.125V8H15C16.3789 8 17.5 9.12109 17.5 10.5V18C17.5 19.3789 16.3789 20.5 15 20.5H2.5C1.12109 20.5 0 19.3789 0 18V10.5C0 9.12109 1.12109 8 2.5 8H3.125Z"
                      fill="#A16207"
                    />
                  </svg>
                ) : undefined,
            }}
            button={
              screen.unlockYourSketch.buttonText
                ? {
                    children: screen.unlockYourSketch.buttonText,
                    onClick: scrollToPayment,
                  }
                : undefined
            }
          />
        )}

        {screen.joinedToday && (
          <JoinedToday
            className="mt-[18px]"
            count={buildTypographyProps(screen.joinedToday.count, {
              as: "span",
              defaults: {
                font: "inter",
                weight: "bold",
                size: "sm",
                align: "center",
                color: "muted",
              },
            })}
            text={buildTypographyProps(screen.joinedToday.text, {
              as: "p",
              defaults: {
                font: "inter",
                size: "sm",
                align: "center",
                color: "muted",
              },
            })}
            icon={
              <svg
                width="15"
                height="13"
                viewBox="0 0 15 13"
                fill="none"
                xmlns="http://www.w3.org/2000/svg"
              >
                <path
                  d="M2.23906 7.96384L7.18008 12.5767C7.38516 12.7681 7.65586 12.8748 7.9375 12.8748C8.21914 12.8748 8.48984 12.7681 8.69492 12.5767L13.6359 7.96384C14.4672 7.19001 14.9375 6.10447 14.9375 4.9697V4.81111C14.9375 2.89978 13.5566 1.27009 11.6727 0.95564C10.4258 0.747827 9.15703 1.15525 8.26562 2.04666L7.9375 2.37478L7.60938 2.04666C6.71797 1.15525 5.44922 0.747827 4.20234 0.95564C2.31836 1.27009 0.9375 2.89978 0.9375 4.81111V4.9697C0.9375 6.10447 1.40781 7.19001 2.23906 7.96384Z"
                  fill="#1047A2"
                />
              </svg>
            }
          />
        )}

        {screen.trustedByOver && (
          <TrustedByOver
            className="mt-[9px]"
            text={buildTypographyProps(screen.trustedByOver.text, {
              as: "p",
              defaults: {
                font: "inter",
                size: "sm",
                align: "center",
                color: "muted",
              },
            })}
            icon={
              <svg
                width="19"
                height="15"
                viewBox="0 0 19 15"
                fill="none"
                xmlns="http://www.w3.org/2000/svg"
              >
                <path
                  d="M4.6875 0.75C5.26766 0.75 5.82406 0.980468 6.2343 1.3907C6.64453 1.80094 6.875 2.35734 6.875 2.9375C6.875 3.51766 6.64453 4.07406 6.2343 4.4843C5.82406 4.89453 5.26766 5.125 4.6875 5.125C4.10734 5.125 3.55094 4.89453 3.1407 4.4843C2.73047 4.07406 2.5 3.51766 2.5 2.9375C2.5 2.35734 2.73047 1.80094 3.1407 1.3907C3.55094 0.980468 4.10734 0.75 4.6875 0.75ZM14.75 0.75C15.3302 0.75 15.8866 0.980468 16.2968 1.3907C16.707 1.80094 16.9375 2.35734 16.9375 2.9375C16.9375 3.51766 16.707 4.07406 16.2968 4.4843C15.8866 4.89453 15.3302 5.125 14.75 5.125C14.1698 5.125 13.6134 4.89453 13.2032 4.4843C12.793 4.07406 12.5625 3.51766 12.5625 2.9375C12.5625 2.35734 12.793 1.80094 13.2032 1.3907C13.6134 0.980468 14.1698 0.75 14.75 0.75ZM0.75 8.91758C0.75 7.30703 2.05703 6 3.66758 6H4.83516C5.26992 6 5.68281 6.0957 6.05469 6.26523C6.01914 6.46211 6.00273 6.66719 6.00273 6.875C6.00273 7.91953 6.46211 8.85742 7.18672 9.5C7.18125 9.5 7.17578 9.5 7.16758 9.5H1.33242C1.0125 9.5 0.75 9.2375 0.75 8.91758ZM11.8324 9.5C11.827 9.5 11.8215 9.5 11.8133 9.5C12.5406 8.85742 12.9973 7.91953 12.9973 6.875C12.9973 6.66719 12.9781 6.46484 12.9453 6.26523C13.3172 6.09297 13.7301 6 14.1648 6H15.3324C16.943 6 18.25 7.30703 18.25 8.91758C18.25 9.24023 17.9875 9.5 17.6676 9.5H11.8324ZM6.875 6.875C6.875 6.17881 7.15156 5.51113 7.64384 5.01884C8.13613 4.52656 8.80381 4.25 9.5 4.25C10.1962 4.25 10.8639 4.52656 11.3562 5.01884C11.8484 5.51113 12.125 6.17881 12.125 6.875C12.125 7.57119 11.8484 8.23887 11.3562 8.73116C10.8639 9.22344 10.1962 9.5 9.5 9.5C8.80381 9.5 8.13613 9.22344 7.64384 8.73116C7.15156 8.23887 6.875 7.57119 6.875 6.875ZM4.25 14.0199C4.25 12.0074 5.88242 10.375 7.89492 10.375H11.1051C13.1176 10.375 14.75 12.0074 14.75 14.0199C14.75 14.4219 14.4246 14.75 14.0199 14.75H4.98008C4.57812 14.75 4.25 14.4246 4.25 14.0199Z"
                  fill="#1047A2"
                />
              </svg>
            }
          />
        )}

        {screen.findingOneGuide && (
          <FindingOneGuide
            className="mt-[22px]"
            header={{
              emoji: buildTypographyProps(
                screen.findingOneGuide.header?.emoji,
                {
                  as: "span",
                  defaults: { size: "2xl" },
                }
              ),
              title: buildTypographyProps(
                screen.findingOneGuide.header?.title,
                {
                  as: "h3",
                  defaults: { font: "inter", weight: "bold" },
                }
              ),
            }}
            text={buildTypographyProps(screen.findingOneGuide.text, {
              as: "p",
              defaults: { font: "inter", size: "sm", color: "muted" },
            })}
            blur={{
              text: {
                ...(buildTypographyProps(screen.findingOneGuide.blur?.text, {
                  as: "p",
                  defaults: {
                    font: "inter",
                    weight: "medium",
                    align: "center",
                  },
                }) ?? { as: "p", children: "" }),
                className: "text-[#A16207]",
              },
              icon:
                screen.findingOneGuide.blur?.icon === "lock" ? (
                  <svg
                    width="18"
                    height="21"
                    viewBox="0 0 18 21"
                    fill="none"
                    xmlns="http://www.w3.org/2000/svg"
                  >
                    <path
                      d="M5.625 6.125V8H11.875V6.125C11.875 4.39844 10.4766 3 8.75 3C7.02344 3 5.625 4.39844 5.625 6.125ZM3.125 8V6.125C3.125 3.01953 5.64453 0.5 8.75 0.5C11.8555 0.5 14.375 3.01953 14.375 6.125V8H15C16.3789 8 17.5 9.12109 17.5 10.5V18C17.5 19.3789 16.3789 20.5 15 20.5H2.5C1.12109 20.5 0 19.3789 0 18V10.5C0 9.12109 1.12109 8 2.5 8H3.125Z"
                      fill="#A16207"
                    />
                  </svg>
                ) : undefined,
            }}
          />
        )}

        {screen.tryForDays && (
          <TryForDays
            className="mt-[46px]"
            title={buildTypographyProps(
              {
                ...screen.tryForDays.title,
                text: replacePlaceholders(screen.tryForDays.title?.text),
              },
              {
                as: "h3",
                defaults: { font: "inter", weight: "bold", size: "xl" },
              }
            )}
            textListProps={
              screen.tryForDays.textList
                ? {
                    listStyleType: "none",
                    items: screen.tryForDays.textList.items.map(
                      (it) =>
                        buildTypographyProps(
                          { ...it, text: replacePlaceholders(it.text) },
                          { as: "li", defaults: { font: "inter", size: "sm" } }
                        )!
                    ),
                  }
                : undefined
            }
          />
        )}

        {screen.totalPrice && (
          <TotalPrice
            className="mt-[46px]"
            couponContainer={{
              title: buildTypographyProps(
                screen.totalPrice.couponContainer.title,
                {
                  as: "h4",
                  defaults: { font: "inter", weight: "semiBold" },
                }
              ),
              button: screen.totalPrice.couponContainer.buttonText
                ? {
                    children: screen.totalPrice.couponContainer.buttonText,
                    onClick: scrollToPayment,
                  }
                : undefined,
            }}
            priceContainer={
              screen.totalPrice.priceContainer
                ? {
                    title: buildTypographyProps(
                      screen.totalPrice.priceContainer.title,
                      {
                        as: "h4",
                        defaults: { font: "inter", weight: "bold", size: "xl" },
                      }
                    ),
                    price: buildTypographyProps(
                      {
                        ...screen.totalPrice.priceContainer.price,
                        text: replacePlaceholders(
                          screen.totalPrice.priceContainer.price?.text
                        ),
                      },
                      {
                        as: "span",
                        defaults: { font: "inter", weight: "black" },
                      }
                    ),
                    oldPrice: buildTypographyProps(
                      {
                        ...screen.totalPrice.priceContainer.oldPrice,
                        text: replacePlaceholders(
                          screen.totalPrice.priceContainer.oldPrice?.text
                        ),
                      },
                      {
                        as: "span",
                        defaults: { font: "inter" },
                      }
                    ),
                    discount: buildTypographyProps(
                      {
                        ...screen.totalPrice.priceContainer.discount,
                        text: replacePlaceholders(
                          screen.totalPrice.priceContainer.discount?.text
                        ),
                      },
                      {
                        as: "span",
                        defaults: { font: "inter", weight: "bold", size: "sm" },
                      }
                    ),
                  }
                : undefined
            }
          />
        )}

        {screen.paymentButtons && (
          <div className="w-full">
            <PaymentButtons
              className="mt-[46px]"
              buttons={screen.paymentButtons.buttons.map((b, index) => {
                const icon =
                  b.icon === "pay" ? (
                    <svg
                      width="19"
                      height="24"
                      viewBox="0 0 19 24"
                      fill="none"
                      xmlns="http://www.w3.org/2000/svg"
                    >
                      <g clipPath="url(#clip0_49_113)">
                        <path
                          d="M15.8141 12.5953C15.8047 10.875 16.5828 9.57656 18.1578 8.62031C17.2766 7.35938 15.9453 6.66563 14.1875 6.52969C12.5234 6.39844 10.7047 7.5 10.0391 7.5C9.33594 7.5 7.72344 6.57656 6.45781 6.57656C3.84219 6.61875 1.0625 8.6625 1.0625 12.8203C1.0625 14.0484 1.2875 15.3172 1.7375 16.6266C2.3375 18.3469 4.50312 22.5656 6.7625 22.4953C7.94375 22.4672 8.77812 21.6563 10.3156 21.6563C11.8062 21.6563 12.5797 22.4953 13.8969 22.4953C16.175 22.4625 18.1344 18.6281 18.7062 16.9031C15.65 15.4641 15.8141 12.6844 15.8141 12.5953ZM13.1609 4.89844C14.4406 3.37969 14.3234 1.99688 14.2859 1.5C13.1562 1.56563 11.8484 2.26875 11.1031 3.13594C10.2828 4.06406 9.8 5.2125 9.90313 6.50625C11.1266 6.6 12.2422 5.97188 13.1609 4.89844Z"
                          fill="white"
                        />
                      </g>
                      <defs>
                        <clipPath id="clip0_49_113">
                          <path d="M0.875 0H18.875V24H0.875V0Z" fill="white" />
                        </clipPath>
                      </defs>
                    </svg>
                  ) : b.icon === "google" ? (
                    <svg
                      xmlns="http://www.w3.org/2000/svg"
                      x="0px"
                      y="0px"
                      width="24"
                      height="24"
                      viewBox="0 0 48 48"
                    >
                      <path
                        fill="#FFC107"
                        d="M43.611,20.083H42V20H24v8h11.303c-1.649,4.657-6.08,8-11.303,8c-6.627,0-12-5.373-12-12c0-6.627,5.373-12,12-12c3.059,0,5.842,1.154,7.961,3.039l5.657-5.657C34.046,6.053,29.268,4,24,4C12.955,4,4,12.955,4,24c0,11.045,8.955,20,20,20c11.045,0,20-8.955,20-20C44,22.659,43.862,21.35,43.611,20.083z"
                      ></path>
                      <path
                        fill="#FF3D00"
                        d="M6.306,14.691l6.571,4.819C14.655,15.108,18.961,12,24,12c3.059,0,5.842,1.154,7.961,3.039l5.657-5.657C34.046,6.053,29.268,4,24,4C16.318,4,9.656,8.337,6.306,14.691z"
                      ></path>
                      <path
                        fill="#4CAF50"
                        d="M24,44c5.166,0,9.86-1.977,13.409-5.192l-6.19-5.238C29.211,35.091,26.715,36,24,36c-5.202,0-9.619-3.317-11.283-7.946l-6.522,5.025C9.505,39.556,16.227,44,24,44z"
                      ></path>
                      <path
                        fill="#1976D2"
                        d="M43.611,20.083H42V20H24v8h11.303c-0.792,2.237-2.231,4.166-4.087,5.571c0.001-0.001,0.002-0.001,0.003-0.002l6.19,5.238C36.971,39.205,44,34,44,24C44,22.659,43.862,21.35,43.611,20.083z"
                      ></path>
                    </svg>
                  ) : b.icon === "card" ? (
                    <svg
                      width="19"
                      height="16"
                      viewBox="0 0 19 16"
                      fill="none"
                      xmlns="http://www.w3.org/2000/svg"
                    >
                      <g clipPath="url(#clip0_49_125)">
                        <path
                          d="M16.0312 2.5C16.3062 2.5 16.5312 2.725 16.5312 3V4H1.53125V3C1.53125 2.725 1.75625 2.5 2.03125 2.5H16.0312ZM16.5312 7V13C16.5312 13.275 16.3062 13.5 16.0312 13.5H2.03125C1.75625 13.5 1.53125 13.275 1.53125 13V7H16.5312ZM2.03125 1C0.928125 1 0.03125 1.89688 0.03125 3V13C0.03125 14.1031 0.928125 15 2.03125 15H16.0312C17.1344 15 18.0312 14.1031 18.0312 13V3C18.0312 1.89688 17.1344 1 16.0312 1H2.03125ZM3.78125 10.5C3.36562 10.5 3.03125 10.8344 3.03125 11.25C3.03125 11.6656 3.36562 12 3.78125 12H5.28125C5.69688 12 6.03125 11.6656 6.03125 11.25C6.03125 10.8344 5.69688 10.5 5.28125 10.5H3.78125ZM7.78125 10.5C7.36562 10.5 7.03125 10.8344 7.03125 11.25C7.03125 11.6656 7.36562 12 7.78125 12H11.2812C11.6969 12 12.0312 11.6656 12.0312 11.25C12.0312 10.8344 11.6969 10.5 11.2812 10.5H7.78125Z"
                          fill="white"
                        />
                      </g>
                      <defs>
                        <clipPath id="clip0_49_125">
                          <path
                            d="M0.03125 0H18.0312V16H0.03125V0Z"
                            fill="white"
                          />
                        </clipPath>
                      </defs>
                    </svg>
                  ) : undefined;

                const className = b.primary ? "bg-primary" : undefined;

                return {
                  children:
                    index === loadingButtonIndex ? (
                      <Spinner className="size-6" />
                    ) : (
                      b.text
                    ),
                  icon: loadingButtonIndex === index ? undefined : icon,
                  className,
                  onClick: () => handlePayClick(index),
                };
              })}
            />
          </div>
        )}

        {screen.moneyBackGuarantee && (
          <MoneyBackGuarantee
            className="mt-[17px]"
            title={buildTypographyProps(screen.moneyBackGuarantee.title, {
              as: "h4",
              defaults: { font: "inter", weight: "bold", size: "sm" },
            })}
            text={buildTypographyProps(screen.moneyBackGuarantee.text, {
              as: "p",
              defaults: { font: "inter", weight: "medium", size: "xs" },
            })}
          />
        )}

        {screen.policy && (
          <div ref={paymentSectionRef}>
            <Policy className="mt-4">
              By clicking Continue, you agree to our{" "}
              <a
                href="https://witlab.us/terms"
                target="_blank"
                rel="noopener noreferrer"
                className="underline hover:text-[#4B5563]"
              >
                Terms of Use & Service
              </a>{" "}
              and{" "}
              <a
                href="https://witlab.us/privacy"
                target="_blank"
                rel="noopener noreferrer"
                className="underline hover:text-[#4B5563]"
              >
                Privacy Policy
              </a>
              . You also acknowledge that your 1-week introductory plan to Wit Lab LLC, billed at $1.00, will automatically renew at $14.99 every 1 week unless canceled before the end of the trial period.
            </Policy>
          </div>
        )}

        {screen.usersPortraits && (
          <UsersPortraits
            className="mt-12"
            title={buildTypographyProps(screen.usersPortraits.title, {
              as: "h3",
              defaults: {
                font: "inter",
                weight: "bold",
                size: "2xl",
                align: "center",
              },
            })}
            imgs={screen.usersPortraits.images?.map((img) => ({
              src: img.src,
              alt: "user portrait",
            }))}
            button={
              screen.usersPortraits.buttonText
                ? {
                    children: screen.usersPortraits.buttonText,
                    onClick: scrollToPayment,
                  }
                : undefined
            }
          />
        )}

        {screen.joinedTodayWithAvatars && (
          <JoinedTodayWithAvatars
            className="mt-[22px]"
            avatars={
              screen.joinedTodayWithAvatars.avatars
                ? {
                    avatars: screen.joinedTodayWithAvatars.avatars.images.map(
                      (img) => ({
                        imageProps: { src: img.src, alt: "avatar" },
                      })
                    ),
                  }
                : undefined
            }
            count={buildTypographyProps(screen.joinedTodayWithAvatars.count, {
              as: "span",
              defaults: { font: "inter", weight: "bold", size: "sm" },
            })}
            text={buildTypographyProps(screen.joinedTodayWithAvatars.text, {
              as: "p",
              defaults: { font: "inter", weight: "semiBold", size: "sm" },
            })}
          />
        )}

        {screen.progressToSeeSoulmate && (
          <ProgressToSeeSoulmate
            className="mt-12"
            title={
              buildTypographyProps(screen.progressToSeeSoulmate.title, {
                as: "h3",
                defaults: { font: "inter", weight: "bold", align: "center" },
              }) ?? { as: "h3", children: "" }
            }
            progress={{
              value: screen.progressToSeeSoulmate.progress?.value ?? 0,
            }}
            progressText={{
              leftText: buildTypographyProps(
                screen.progressToSeeSoulmate.leftText,
                {
                  as: "span",
                  defaults: { font: "inter", size: "sm", weight: "medium" },
                }
              ),
              rightText: buildTypographyProps(
                screen.progressToSeeSoulmate.rightText,
                {
                  as: "span",
                  defaults: { font: "inter", size: "sm" },
                }
              ),
            }}
          />
        )}

        {screen.stepsToSeeSoulmate && (
          <StepsToSeeSoulmate
            className="mt-12"
            steps={screen.stepsToSeeSoulmate.steps.map((s) => ({
              title: buildTypographyProps(s.title, {
                as: "h4",
                defaults: { font: "inter", weight: "semiBold", size: "sm" },
              })!,
              description: buildTypographyProps(s.description, {
                as: "p",
                defaults: { font: "inter", size: "xs" },
              })!,
              icon:
                s.icon === "questions" ? (
                  <svg
                    width="12"
                    height="15"
                    viewBox="0 0 12 15"
                    fill="none"
                    xmlns="http://www.w3.org/2000/svg"
                  >
                    <path
                      d="M6 0.75C4.85703 0.75 3.88359 1.48008 3.52539 2.5H2.5C1.53477 2.5 0.75 3.28477 0.75 4.25V13C0.75 13.9652 1.53477 14.75 2.5 14.75H9.5C10.4652 14.75 11.25 13.9652 11.25 13V4.25C11.25 3.28477 10.4652 2.5 9.5 2.5H8.47461C8.11641 1.48008 7.14297 0.75 6 0.75ZM6 2.5C6.23206 2.5 6.45462 2.59219 6.61872 2.75628C6.78281 2.92038 6.875 3.14294 6.875 3.375C6.875 3.60706 6.78281 3.82962 6.61872 3.99372C6.45462 4.15781 6.23206 4.25 6 4.25C5.76794 4.25 5.54538 4.15781 5.38128 3.99372C5.21719 3.82962 5.125 3.60706 5.125 3.375C5.125 3.14294 5.21719 2.92038 5.38128 2.75628C5.54538 2.59219 5.76794 2.5 6 2.5ZM3.64297 7.01992C3.85898 6.41016 4.43867 6 5.08672 6H6.68086C7.63516 6 8.40625 6.77383 8.40625 7.72539C8.40625 8.34336 8.07539 8.91484 7.53945 9.22383L6.65625 9.72969C6.65078 10.0852 6.3582 10.375 6 10.375C5.63633 10.375 5.34375 10.0824 5.34375 9.71875V9.34961C5.34375 9.11445 5.46953 8.89844 5.67461 8.78086L6.88594 8.08633C7.01445 8.0125 7.09375 7.87578 7.09375 7.72813C7.09375 7.49844 6.90781 7.31523 6.68086 7.31523H5.08672C4.99375 7.31523 4.91172 7.37266 4.88164 7.46016L4.8707 7.49297C4.75039 7.83477 4.37305 8.0125 4.03398 7.89219C3.69492 7.77188 3.51445 7.39453 3.63477 7.05547L3.6457 7.02266L3.64297 7.01992ZM5.125 12.125C5.125 11.8929 5.21719 11.6704 5.38128 11.5063C5.54538 11.3422 5.76794 11.25 6 11.25C6.23206 11.25 6.45462 11.3422 6.61872 11.5063C6.78281 11.6704 6.875 11.8929 6.875 12.125C6.875 12.3571 6.78281 12.5796 6.61872 12.7437C6.45462 12.9078 6.23206 13 6 13C5.76794 13 5.54538 12.9078 5.38128 12.7437C5.21719 12.5796 5.125 12.3571 5.125 12.125Z"
                      fill="white"
                    />
                  </svg>
                ) : s.icon === "profile" ? (
                  <svg
                    width="14"
                    height="15"
                    viewBox="0 0 14 15"
                    fill="none"
                    xmlns="http://www.w3.org/2000/svg"
                  >
                    <path
                      d="M5.03125 0.75C5.87617 0.75 6.5625 1.43633 6.5625 2.28125V13.2188C6.5625 14.0637 5.87617 14.75 5.03125 14.75C4.24102 14.75 3.59023 14.1512 3.5082 13.3801C3.36602 13.4184 3.21563 13.4375 3.0625 13.4375C2.09727 13.4375 1.3125 12.6527 1.3125 11.6875C1.3125 11.4852 1.34805 11.2883 1.41094 11.1078C0.585156 10.7961 0 9.99766 0 9.0625C0 8.19023 0.511328 7.43555 1.25234 7.08555C1.01445 6.7875 0.875 6.41016 0.875 6C0.875 5.16055 1.46563 4.46055 2.25312 4.28828C2.20938 4.13789 2.1875 3.97656 2.1875 3.8125C2.1875 2.99492 2.75078 2.30586 3.5082 2.11445C3.59023 1.34883 4.24102 0.75 5.03125 0.75ZM8.96875 0.75C9.75898 0.75 10.407 1.34883 10.4918 2.11445C11.252 2.30586 11.8125 2.99219 11.8125 3.8125C11.8125 3.97656 11.7906 4.13789 11.7469 4.28828C12.5344 4.45781 13.125 5.16055 13.125 6C13.125 6.41016 12.9855 6.7875 12.7477 7.08555C13.4887 7.43555 14 8.19023 14 9.0625C14 9.99766 13.4148 10.7961 12.5891 11.1078C12.652 11.2883 12.6875 11.4852 12.6875 11.6875C12.6875 12.6527 11.9027 13.4375 10.9375 13.4375C10.7844 13.4375 10.634 13.4184 10.4918 13.3801C10.4098 14.1512 9.75898 14.75 8.96875 14.75C8.12383 14.75 7.4375 14.0637 7.4375 13.2188V2.28125C7.4375 1.43633 8.12383 0.75 8.96875 0.75Z"
                      fill="white"
                    />
                  </svg>
                ) : s.icon === "sketch" ? (
                  <svg
                    width="14"
                    height="15"
                    viewBox="0 0 14 15"
                    fill="none"
                    xmlns="http://www.w3.org/2000/svg"
                  >
                    <path
                      d="M14 7.75C14 7.77461 14 7.79922 14 7.82383C13.9891 8.82188 13.0813 9.5 12.0832 9.5H9.40625C8.68164 9.5 8.09375 10.0879 8.09375 10.8125C8.09375 10.9055 8.10469 10.9957 8.12109 11.0832C8.17852 11.3621 8.29883 11.6301 8.41641 11.9008C8.5832 12.2781 8.74727 12.6527 8.74727 13.0492C8.74727 13.9187 8.15664 14.709 7.28711 14.7445C7.19141 14.7473 7.0957 14.75 6.99727 14.75C3.13359 14.75 0 11.6164 0 7.75C0 3.88359 3.13359 0.75 7 0.75C10.8664 0.75 14 3.88359 14 7.75ZM3.5 8.625C3.5 8.39294 3.40781 8.17038 3.24372 8.00628C3.07962 7.84219 2.85706 7.75 2.625 7.75C2.39294 7.75 2.17038 7.84219 2.00628 8.00628C1.84219 8.17038 1.75 8.39294 1.75 8.625C1.75 8.85706 1.84219 9.07962 2.00628 9.24372C2.17038 9.40781 2.39294 9.5 2.625 9.5C2.85706 9.5 3.07962 9.40781 3.24372 9.24372C3.40781 9.07962 3.5 8.85706 3.5 8.625ZM3.5 6C3.73206 6 3.95462 5.90781 4.11872 5.74372C4.28281 5.57962 4.375 5.35706 4.375 5.125C4.375 4.89294 4.28281 4.67038 4.11872 4.50628C3.95462 4.34219 3.73206 4.25 3.5 4.25C3.26794 4.25 3.04538 4.34219 2.88128 4.50628C2.71719 4.67038 2.625 4.89294 2.625 5.125C2.625 5.35706 2.71719 5.57962 2.88128 5.74372C3.04538 5.90781 3.26794 6 3.5 6ZM7.875 3.375C7.875 3.14294 7.78281 2.92038 7.61872 2.75628C7.45462 2.59219 7.23206 2.5 7 2.5C6.76794 2.5 6.54538 2.59219 6.38128 2.75628C6.21719 2.92038 6.125 3.14294 6.125 3.375C6.125 3.60706 6.21719 3.82962 6.38128 3.99372C6.54538 4.15781 6.76794 4.25 7 4.25C7.23206 4.25 7.45462 4.15781 7.61872 3.99372C7.78281 3.82962 7.875 3.60706 7.875 3.375ZM10.5 6C10.7321 6 10.9546 5.90781 11.1187 5.74372C11.2828 5.57962 11.375 5.35706 11.375 5.125C11.375 4.89294 11.2828 4.67038 11.1187 4.50628C10.9546 4.34219 10.7321 6 10.5 6Z"
                      fill="#6B7280"
                    />
                  </svg>
                ) : s.icon === "astro" ? (
                  <svg
                    width="12"
                    height="13"
                    viewBox="0 0 12 13"
                    fill="none"
                    xmlns="http://www.w3.org/2000/svg"
                  >
                    <path
                      d="M6.86133 0.625C3.48438 0.625 0.75 3.36758 0.75 6.75C0.75 10.1324 3.48438 12.875 6.86133 12.875C8.51836 12.875 10.0195 12.2133 11.1215 11.1414C11.2582 11.0074 11.2937 10.7996 11.2063 10.6301C11.1187 10.4605 10.9301 10.3648 10.7414 10.3977C10.4734 10.4441 10.2 10.4688 9.91836 10.4688C7.26875 10.4688 5.11953 8.31406 5.11953 5.65625C5.11953 3.85703 6.10391 2.29023 7.56133 1.46445C7.72813 1.36875 7.81289 1.17734 7.77187 0.991406C7.73086 0.805469 7.57227 0.666016 7.38086 0.649609C7.20859 0.635938 7.03633 0.627734 6.86133 0.627734V0.625Z"
                      fill="#6B7280"
                    />
                  </svg>
                ) : s.icon === "chat" ? (
                  <svg
                    width="18"
                    height="15"
                    viewBox="0 0 18 15"
                    fill="none"
                    xmlns="http://www.w3.org/2000/svg"
                  >
                    <path
                      d="M5.93755 10.375C9.07935 10.375 11.6251 8.22031 11.6251 5.5625C11.6251 2.90469 9.07935 0.75 5.93755 0.75C2.79576 0.75 0.250055 2.90469 0.250055 5.5625C0.250055 6.61797 0.652008 7.59414 1.33287 8.38984C1.23716 8.64687 1.09498 8.87383 0.944586 9.06523C0.813336 9.23477 0.679352 9.36602 0.580914 9.45625C0.531696 9.5 0.49068 9.53555 0.463336 9.55742C0.449664 9.56836 0.438727 9.57656 0.433258 9.5793L0.427789 9.58477C0.277399 9.69688 0.211774 9.89375 0.27193 10.0715C0.332086 10.2492 0.498883 10.375 0.687555 10.375C1.28365 10.375 1.88521 10.2219 2.3856 10.0332C2.63716 9.9375 2.87232 9.83086 3.0774 9.72148C3.91685 10.1371 4.89302 10.375 5.93755 10.375ZM12.5001 5.5625C12.5001 8.6332 9.79029 10.9465 6.58013 11.2227C7.24459 13.257 9.44849 14.75 12.0626 14.75C13.1071 14.75 14.0833 14.5121 14.9254 14.0965C15.1305 14.2059 15.3629 14.3125 15.6145 14.4082C16.1149 14.5969 16.7165 14.75 17.3126 14.75C17.5012 14.75 17.6708 14.627 17.7282 14.4465C17.7856 14.266 17.7227 14.0691 17.5696 13.957L17.5641 13.9516C17.5586 13.9461 17.5477 13.9406 17.534 13.9297C17.5067 13.9078 17.4657 13.875 17.4165 13.8285C17.318 13.7383 17.184 13.607 17.0528 13.4375C16.9024 13.2461 16.7602 13.0164 16.6645 12.7621C17.3454 11.9691 17.7473 10.993 17.7473 9.93477C17.7473 7.39727 15.4258 5.31641 12.4809 5.13594C12.4919 5.27539 12.4973 5.41758 12.4973 5.55977L12.5001 5.5625Z"
                      fill="#6B7280"
                    />
                  </svg>
                ) : null,
              isActive: s.isActive ?? false,
            }))}
            button={
              screen.stepsToSeeSoulmate.buttonText
                ? {
                    children: screen.stepsToSeeSoulmate.buttonText,
                    onClick: scrollToPayment,
                  }
                : undefined
            }
          />
        )}

        {screen.reviews && (
          <Reviews
            className="mt-12"
            title={buildTypographyProps(screen.reviews.title, {
              as: "h3",
              defaults: { font: "inter", weight: "bold", align: "center" },
            })}
            reviews={screen.reviews.items.map((r) => ({
              name: buildTypographyProps(r.name, {
                as: "span",
                defaults: { font: "inter", weight: "semiBold", size: "sm" },
              }),
              text: buildTypographyProps(r.text, {
                as: "p",
                defaults: { font: "inter", size: "sm" },
              }),
              date: buildTypographyProps(r.date, {
                as: "span",
                defaults: { font: "inter", size: "xs" },
              }),
              avatar: r.avatar
                ? {
                    imageProps: { src: r.avatar.src, alt: "avatar" },
                  }
                : undefined,
              stars: r.rating ? { value: r.rating } : undefined,
              portrait: r.portrait
                ? { src: r.portrait.src, alt: "Portrait" }
                : undefined,
              photo: r.photo ? { src: r.photo.src, alt: "Photo" } : undefined,
            }))}
          />
        )}

        {screen.commonQuestions && (
          <CommonQuestions
            className="mt-[31px]"
            title={buildTypographyProps(screen.commonQuestions.title, {
              as: "h3",
              defaults: {
                font: "inter",
                weight: "bold",
                size: "2xl",
                align: "center",
              },
            })}
            questions={screen.commonQuestions.items.map((q, index) => ({
              value: `q-${index}`,
              trigger: { children: q.question },
              content: { children: q.answer },
            }))}
            accordionProps={{ defaultValue: "q-0", type: "single" }}
          />
        )}

        {screen.stillHaveQuestions && (
          <StillHaveQuestions
            className="mt-8"
            title={buildTypographyProps(screen.stillHaveQuestions.title, {
              as: "h3",
              defaults: { font: "inter", size: "sm" },
            })}
            actionButton={
              screen.stillHaveQuestions.actionButtonText
                ? {
                    children: screen.stillHaveQuestions.actionButtonText,
                    onClick: scrollToPayment,
                  }
                : undefined
            }
            contactButton={
              screen.stillHaveQuestions.contactButtonText
                ? {
                    children: screen.stillHaveQuestions.contactButtonText,
                    onClick: () => {
                      // Open contact link from footer config
                      const contactUrl = screen.footer?.contacts?.email?.href;
                      if (contactUrl) {
                        window.open(contactUrl, "_blank", "noopener,noreferrer");
                      }
                    },
                  }
                : undefined
            }
          />
        )}

        {screen.footer && (
          <Footer
            className="mt-[60px]"
            title={buildTypographyProps(screen.footer.title, {
              as: "h3",
              defaults: {
                font: "inter",
                weight: "bold",
                size: "2xl",
                align: "center",
              },
            })}
            contacts={
              screen.footer.contacts
                ? {
                    title: buildTypographyProps(screen.footer.contacts.title, {
                      as: "h3",
                      defaults: { font: "inter", weight: "bold" },
                    }),
                    email: screen.footer.contacts.email
                      ? {
                          href: screen.footer.contacts.email.href,
                          children: screen.footer.contacts.email.text,
                        }
                      : undefined,
                    address: buildTypographyProps(
                      screen.footer.contacts.address,
                      {
                        as: "address",
                        defaults: { font: "inter", size: "sm" },
                      }
                    ),
                  }
                : undefined
            }
            legal={
              screen.footer.legal
                ? {
                    title: buildTypographyProps(screen.footer.legal.title, {
                      as: "h3",
                      defaults: { font: "inter", weight: "bold" },
                    }),
                    links:
                      screen.footer.legal.links?.map((l) => ({
                        href: l.href,
                        children: l.text,
                      })) || [],
                    copyright: buildTypographyProps(
                      screen.footer.legal.copyright,
                      { as: "p", defaults: { font: "inter", size: "xs" } }
                    ),
                  }
                : undefined
            }
            paymentMethods={
              screen.footer.paymentMethods
                ? {
                    title: buildTypographyProps(
                      screen.footer.paymentMethods.title,
                      { as: "h3", defaults: { font: "inter", weight: "bold" } }
                    ),
                    methods:
                      screen.footer.paymentMethods.methods?.map((m) => ({
                        src: m.src,
                        alt: m.alt,
                      })) || [],
                  }
                : undefined
            }
          />
        )}
      </div>
    </TemplateLayout>
  );
}
