'use strict';
'use client';
import { c } from 'react/compiler-runtime';
import { jsxs, jsx } from 'react/jsx-runtime';
import { useState, useEffect } from 'react';
import { Button } from '../../../fd-component-toolbox/button/Button.js';
import { Card, CardTitle, CardDescription, CardContent, CardFooter } from '../../../fd-component-toolbox/card/Card.js';
import { Dialog, DialogContent, DialogTitle } from '../../../fd-component-toolbox/dialog/Dialog.js';
import { CheckoutForm } from '../../payments/checkout-form/CheckoutForm.js';
import { Icon, iconNames } from '../../../fd-component-toolbox/icon/Icon.js';
import { useAsyncEffect } from '../../../../fd-toolbox/hooks/use-async-effect.js';
import { useElementId } from '../../../../fd-toolbox/hooks/use-element-id.js';
import { onRefreshPricings, getFeaturesByPlan, isActivePricing, getAdditionalInfo, getPricingText, getPricingDescripion, isBasicPlan, canUpdateSubscription, getButtonText, getPaymentPlanButtonId, updateSubscriptionHandler, handlePlanAction, getPaymentPlanId, handleCheckoutSuccess } from './SubscriptionPlan.funcs.js';
import { dateToISOString } from '../../../../fd-toolbox/dates/date-time.js';
import { Switch } from '../../../fd-component-toolbox/switch/Switch.js';
import { useSetTitle } from '../../../meta/page/use-set-title.js';
import { billingIntervals, subscriptionStatuses } from '../../../meta/core/resources/enums/payment-enums.js';
import { subscriptionMessages } from '../../../../fd-toolbox-core/constants/subscription-messages.js';
import { cn } from '../../../../fd-toolbox/lib/utils.js';
import { resourceNames } from '../../../../fd-toolbox/resources/resource-names.js';
import { YesOrNoDialog } from '../../../fd-component-toolbox/dialog/YesOrNoDialog.js';
import { goBack } from '../../../../fd-toolbox/routing/routers.js';
import { elementSuffixes } from '../../../../fd-toolbox/constants/element-suffixes.js';
import { getElementId } from '../../../../fd-toolbox/html/element-ids.js';
import { hasScheduledCancelation } from './subscriptions.js';
import { useRouter } from '../../../meta/client/framework/hooks.js';
import { capitalizeFirstLetter } from '../../../../fd-toolbox/strings/casing-converter.js';
import { setBodyCursorBusy } from '../../../../fd-toolbox/html/document-body-cursor.js';

var __defProp = Object.defineProperty;
var __name = (target, value) => __defProp(target, "name", {
  value,
  configurable: true
});
function SubscriptionPlan(t0) {
  const $ = c(15);
  const {
    config
  } = t0;
  const [isDialogOpen, setIsDialogOpen] = useState(false);
  const [selectedPlanPrice, setSelectedPlanPrice] = useState(0);
  const [selectedPricingId, setSelectedPricingId] = useState("");
  const [isSubmittingForm, setIsSubmittingForm] = useState(false);
  let t1;
  if ($[0] === Symbol.for("react.memo_cache_sentinel")) {
    t1 = [];
    $[0] = t1;
  } else {
    t1 = $[0];
  }
  const [pricings, setPricings] = useState(t1);
  const [refreshPricingsTrigger, setRefreshPricingsTrigger] = useState(0);
  const [isCanceling, setIsCanceling] = useState(false);
  const [activeSubscription, setActiveSubscription] = useState();
  const [selectedBillingInterval, setSelectedBillingInterval] = useState(billingIntervals.month);
  let t2;
  if ($[1] === Symbol.for("react.memo_cache_sentinel")) {
    t2 = [];
    $[1] = t2;
  } else {
    t2 = $[1];
  }
  const [paymentPlanFeature, setPaymentPlanFeature] = useState(t2);
  const router = useRouter();
  const containerId = useElementId(SubscriptionPlan.displayName);
  let t3;
  if ($[2] !== selectedBillingInterval) {
    t3 = pricing => pricing.billingInterval === selectedBillingInterval;
    $[2] = selectedBillingInterval;
    $[3] = t3;
  } else {
    t3 = $[3];
  }
  const filteredPricings = pricings.filter(t3);
  useSetTitle(resourceNames.paymentPlan);
  let t4;
  if ($[4] !== config?.excludePricingIds || $[5] !== isCanceling) {
    t4 = async () => {
      await onRefreshPricings(isCanceling, setIsCanceling, setActiveSubscription, setPricings, setPaymentPlanFeature, config?.excludePricingIds);
    };
    $[4] = config?.excludePricingIds;
    $[5] = isCanceling;
    $[6] = t4;
  } else {
    t4 = $[6];
  }
  let t5;
  if ($[7] !== refreshPricingsTrigger) {
    t5 = [refreshPricingsTrigger];
    $[7] = refreshPricingsTrigger;
    $[8] = t5;
  } else {
    t5 = $[8];
  }
  useAsyncEffect(t4, t5);
  let t6;
  let t7;
  if ($[9] !== isCanceling) {
    t6 = () => {
      setBodyCursorBusy(isCanceling);
    };
    t7 = [isCanceling];
    $[9] = isCanceling;
    $[10] = t6;
    $[11] = t7;
  } else {
    t6 = $[10];
    t7 = $[11];
  }
  useEffect(t6, t7);
  let t8;
  if ($[12] === Symbol.for("react.memo_cache_sentinel")) {
    t8 = () => setRefreshPricingsTrigger(_temp);
    $[12] = t8;
  } else {
    t8 = $[12];
  }
  const refreshPricingsData = __name(t8, "refreshPricingsData");
  const featuresByPlan = getFeaturesByPlan(paymentPlanFeature.map(_temp2));
  let t9;
  if ($[13] !== selectedBillingInterval) {
    t9 = () => setSelectedBillingInterval(selectedBillingInterval === billingIntervals.year ? billingIntervals.month : billingIntervals.year);
    $[13] = selectedBillingInterval;
    $[14] = t9;
  } else {
    t9 = $[14];
  }
  return jsxs("div", {
    id: containerId,
    className: "flex flex-col justify-center py-6 xl:px-4",
    children: [jsx("p", {
      className: "text-muted-foreground mt-2 mb-4 text-center",
      children: subscriptionMessages.pricingIntro
    }), jsxs("div", {
      className: "flex items-center justify-center",
      children: [jsx("div", {
        className: "absolute top-0 left-0 items-start justify-start gap-2",
        children: jsxs(Button, {
          id: getElementId(elementSuffixes.back, SubscriptionPlan.displayName),
          variant: "ghost",
          size: "default",
          onClick: goBack,
          tooltipText: "Go back",
          tooltipClassName: "mt-2",
          children: [jsx(Icon, {
            name: iconNames.arrowLeft,
            className: "mr-2"
          }), "Back"]
        })
      }), jsx("p", {
        className: "pointer-events-none pr-3 text-sm leading-none font-medium peer-disabled:cursor-not-allowed",
        children: subscriptionMessages.pricePerMonth
      }), jsx(Switch, {
        label: subscriptionMessages.pricePerYear,
        checked: selectedBillingInterval === billingIntervals.year,
        onCheckedChange: t9,
        name: "subscriptionTypeSwitcher"
      })]
    }), !!filteredPricings.length && jsxs("div", {
      className: "mx-auto flex flex-col items-center justify-center gap-4 sm:mx-0 lg:flex-row lg:items-stretch",
      children: [filteredPricings.map(pricing_0 => {
        const isActive = isActivePricing(pricing_0, activeSubscription?.pricing, activeSubscription?.pendingPricingId);
        const plan = pricing_0.paymentPlan;
        const additionalInfo = getAdditionalInfo(pricing_0, activeSubscription);
        return plan && jsxs(Card, {
          className: cn("relative mt-4 flex w-full flex-col items-center gap-2 rounded-3xl p-4 sm:max-w-2xl lg:max-w-md", isActive && "border-primary border-4"),
          id: getPaymentPlanId(plan.name, pricing_0.billingInterval),
          children: [additionalInfo && additionalInfo.shouldShowAdditionalInfo && jsxs("div", {
            className: "bg-primary text-primary-foreground absolute top-6 right-4 flex size-28 flex-col items-center justify-center rounded-full p-2 text-sm",
            children: [jsx("p", {
              children: additionalInfo.infoText
            }), jsx("time", {
              className: "text-xs",
              children: additionalInfo.infoDate && dateToISOString(additionalInfo.infoDate.toString())
            })]
          }), jsx(CardTitle, {
            className: "w-full text-left font-semibold",
            children: capitalizeFirstLetter(plan.name)
          }), jsx(CardDescription, {
            className: cn("text-primary mt-8 w-full text-left text-3xl font-semibold", plan.isContactUs && "text-center text-base xl:text-xl"),
            children: getPricingText(pricing_0, plan.pricingDescription)
          }), jsx("p", {
            className: "w-full text-left text-sm",
            children: getPricingDescripion(pricing_0)
          }), jsxs(CardContent, {
            className: "mt-2 w-full grow pl-0",
            children: [jsx("span", {
              className: "text-sm font-semibold",
              children: plan.description
            }), jsx("ul", {
              className: "mt-2 space-y-2",
              children: (featuresByPlan[pricing_0.paymentPlanId] || []).map(_temp3)
            })]
          }), jsx(CardFooter, {
            className: "flex w-full flex-col pb-0",
            children: !isBasicPlan(plan.name) && (canUpdateSubscription(pricing_0.id, activeSubscription) && !plan.isContactUs ? jsx(YesOrNoDialog, {
              triggerClassName: "w-full",
              title: activeSubscription?.status === subscriptionStatuses.trialing ? subscriptionMessages.trialDIalogTitle : subscriptionMessages.dialogTitle,
              onResponse: dialogResult => updateSubscriptionHandler(dialogResult, pricing_0, refreshPricingsData, activeSubscription),
              trigger: jsx(Button, {
                size: "default",
                className: "w-full",
                id: getPaymentPlanButtonId(SubscriptionPlan.displayName, plan.name),
                disabled: hasScheduledCancelation(activeSubscription, pricing_0.id),
                children: getButtonText(pricing_0, activeSubscription)
              }),
              disabled: hasScheduledCancelation(activeSubscription, pricing_0.id)
            }) : jsx(Button, {
              onClick: () => handlePlanAction(pricing_0, isDialogOpen, refreshPricingsTrigger, setIsDialogOpen, setIsCanceling, setRefreshPricingsTrigger, setSelectedPlanPrice, setSelectedPricingId, activeSubscription, config, router),
              size: "default",
              className: "w-full",
              id: getPaymentPlanButtonId(SubscriptionPlan.displayName, plan.name),
              disabled: hasScheduledCancelation(activeSubscription, pricing_0.id),
              children: getButtonText(pricing_0, activeSubscription)
            }))
          })]
        }, pricing_0.id);
      }), jsx(Dialog, {
        open: isDialogOpen,
        onOpenChange: setIsDialogOpen,
        children: jsxs(DialogContent, {
          closeButtonShown: !isSubmittingForm,
          className: "flex w-full min-w-96 flex-col justify-center gap-0",
          children: [jsx(DialogTitle, {
            className: "mt-8 text-center leading-none font-semibold",
            children: subscriptionMessages.enterPaymentDetails
          }), jsx("div", {
            children: jsx(CheckoutForm, {
              price: selectedPlanPrice,
              pricingId: selectedPricingId,
              onSubmitting: setIsSubmittingForm,
              onSubmitSuccess: () => handleCheckoutSuccess(!!activeSubscription, setIsDialogOpen, refreshPricingsData, config)
            })
          })]
        })
      })]
    })]
  });
}
function _temp3(featureName) {
  return jsxs("li", {
    className: "flex items-start",
    children: [jsx(Icon, {
      name: iconNames.check,
      className: "mt-1 mr-2 shrink-0 self-start"
    }), jsx("span", {
      className: "text-sm",
      children: featureName
    })]
  }, featureName);
}
function _temp2(f) {
  return {
    ...f,
    featureName: f.featureName ?? f.feature?.name ?? ""
  };
}
function _temp(prev) {
  return prev + 1;
}
__name(SubscriptionPlan, "SubscriptionPlan");
SubscriptionPlan.displayName = "SubscriptionPlan";

export { SubscriptionPlan };
