import { __ } from "@wordpress/i18n";
import {
  BookOpen,
  Briefcase,
  Heart,
  Monitor,
  Package,
  Settings,
  Users,
} from "lucide-react";
import {
  DEFAULT_ADMIN_EMAILS,
  DEFAULT_CUSTOM_EMAILS,
  isAccessControlBusinessType,
} from "./wizardDefaults";

const YES_NO_OPTIONS = [
  {
    value: "yes",
    label: __("Yes", "arraysubs"),
  },
  {
    value: "no",
    label: __("No", "arraysubs"),
  },
];

const BUSINESS_TYPE_OPTIONS = [
  {
    value: "saas",
    label: __("SaaS / Digital Software", "arraysubs"),
    description: __(
      "Apps, software access, API plans, and feature tiers.",
      "arraysubs",
    ),
    icon: Monitor,
  },
  {
    value: "box",
    label: __("Physical Subscription Box", "arraysubs"),
    description: __(
      "Recurring shipments of physical products or refill boxes.",
      "arraysubs",
    ),
    icon: Package,
  },
  {
    value: "membership",
    label: __("Membership / Community", "arraysubs"),
    description: __(
      "Subscriber-only communities, memberships, and gated access.",
      "arraysubs",
    ),
    icon: Users,
  },
  {
    value: "content",
    label: __("Digital Content", "arraysubs"),
    description: __(
      "Courses, downloads, publications, and streaming content.",
      "arraysubs",
    ),
    icon: BookOpen,
  },
  {
    value: "services",
    label: __("Professional Services", "arraysubs"),
    description: __(
      "Coaching, retainers, recurring consulting, and services.",
      "arraysubs",
    ),
    icon: Briefcase,
  },
  {
    value: "nonprofit",
    label: __("Nonprofit / Donations", "arraysubs"),
    description: __(
      "Recurring giving, donations, and fundraising memberships.",
      "arraysubs",
    ),
    icon: Heart,
  },
  {
    value: "other",
    label: __("Other / Custom", "arraysubs"),
    description: __(
      "A custom subscription business that needs flexible defaults.",
      "arraysubs",
    ),
    icon: Settings,
  },
];

const EMAIL_OPTIONS = [
  {
    value: "new_subscription",
    label: __("New Subscription Confirmation", "arraysubs"),
  },
  {
    value: "subscription_activated",
    label: __("Subscription Activated", "arraysubs"),
  },
  {
    value: "subscription_on_hold",
    label: __("Subscription On-Hold", "arraysubs"),
  },
  {
    value: "subscription_cancelled",
    label: __("Subscription Cancelled", "arraysubs"),
  },
  {
    value: "subscription_expired",
    label: __("Subscription Expired", "arraysubs"),
  },
  { value: "renewal_upcoming", label: __("Renewal Reminder", "arraysubs") },
  { value: "renewal_invoice", label: __("Renewal Invoice", "arraysubs") },
  {
    value: "renewal_payment_received",
    label: __("Payment Successful", "arraysubs"),
  },
  { value: "payment_failed", label: __("Payment Failed", "arraysubs") },
  { value: "trial_started", label: __("Trial Started", "arraysubs") },
  { value: "trial_ending", label: __("Trial Ending Soon", "arraysubs") },
  {
    value: "trial_converted",
    label: __("Trial Converted to Paid", "arraysubs"),
  },
  {
    value: "expiring_soon",
    label: __("Subscription Expiring Soon", "arraysubs"),
  },
  { value: "auto_downgrade", label: __("Auto-Downgrade", "arraysubs") },
];

const ADMIN_EMAIL_OPTIONS = [
  {
    value: "admin_new_subscription",
    label: __("New subscription created", "arraysubs"),
  },
  {
    value: "admin_cancelled",
    label: __("Subscription cancelled", "arraysubs"),
  },
  {
    value: "admin_payment_failed",
    label: __("Payment failed", "arraysubs"),
  },
];

const ADDITIONAL_FEATURE_OPTIONS = [
  {
    value: "store_credit",
    label: __("Store Credit System", "arraysubs"),
    description: __(
      "Refund to credit, credit balances, and credit purchases.",
      "arraysubs",
    ),
    proOnly: true,
    badge: __("Pro", "arraysubs"),
  },
  {
    value: "feature_manager",
    label: __("Feature Manager", "arraysubs"),
    description: __(
      "Define plan entitlements like seats, storage, or usage caps.",
      "arraysubs",
    ),
    proOnly: true,
    badge: __("Pro", "arraysubs"),
  },
  {
    value: "audit_logging",
    label: __("Activity Audit Log", "arraysubs"),
    description: __(
      "Track subscription, payment, and settings changes over time.",
      "arraysubs",
    ),
    proOnly: true,
    badge: __("Pro", "arraysubs"),
  },
  {
    value: "custom_profile_fields",
    label: __("Custom Profile Fields", "arraysubs"),
    description: __(
      "Collect extra customer details like company, phone, or ID fields.",
      "arraysubs",
    ),
  },
  {
    value: "myaccount_editor",
    label: __("My Account Page Editor", "arraysubs"),
    description: __(
      "Customize, reorder, and manage customer account menu items.",
      "arraysubs",
    ),
  },
  {
    value: "hide_admin_bar",
    label: __("Hide Admin Bar for Customers", "arraysubs"),
    description: __(
      "Keep the frontend cleaner for non-admin customer accounts.",
      "arraysubs",
    ),
  },
  {
    value: "restrict_dashboard",
    label: __("Restrict WP Dashboard Access", "arraysubs"),
    description: __(
      "Block non-admin users from reaching the WordPress dashboard.",
      "arraysubs",
    ),
  },
  {
    value: "multi_login",
    label: __("Multi-Login Prevention", "arraysubs"),
    description: __(
      "Limit concurrent sessions to reduce shared-account abuse.",
      "arraysubs",
    ),
    proOnly: true,
    badge: __("Pro", "arraysubs"),
  },
];

const isRenewalReminderEnabled = (answers) => {
  if (answers.email_level === "minimal") {
    return false;
  }

  if (answers.email_level !== "custom") {
    return true;
  }

  return (answers.custom_emails || []).includes("renewal_upcoming");
};

const parseInteger = (value) => Number.parseInt(value, 10);

const validateIntegerRange = (value, min, max, message) => {
  const parsed = parseInteger(value);

  if (Number.isNaN(parsed) || parsed < min || parsed > max) {
    return message;
  }

  return null;
};

export const MANUAL_SETUP_NOTES = [
  __("Cancellation reasons and advanced retention copy", "arraysubs"),
  __(
    "Detailed member access rules, role mappings, URLs, CPT rules, and download restrictions",
    "arraysubs",
  ),
  __(
    "Custom profile field definitions and My Account menu item structure",
    "arraysubs",
  ),
  __(
    "Checkout Builder field layouts and advanced email subject/body content",
    "arraysubs",
  ),
];

export const WIZARD_STEPS = [
  {
    id: "business",
    title: __("Your Business", "arraysubs"),
    description: __(
      "Start with the shape of your subscription business so the wizard can preload smart defaults.",
      "arraysubs",
    ),
    questions: [
      {
        key: "business_type",
        field: "radio-card",
        label: __(
          "What type of subscription business are you running?",
          "arraysubs",
        ),
        helpText: __(
          "This sets the default recommendations for billing, retention, access control, and optional tools.",
          "arraysubs",
        ),
        required: true,
        options: BUSINESS_TYPE_OPTIONS,
      },
      {
        key: "billing_cycle",
        field: "radio",
        label: __("What is your primary billing cycle?", "arraysubs"),
        required: true,
        options: [
          { value: "weekly", label: __("Weekly", "arraysubs") },
          { value: "monthly", label: __("Monthly", "arraysubs") },
          { value: "yearly", label: __("Yearly", "arraysubs") },
          { value: "custom", label: __("Custom", "arraysubs") },
        ],
      },
      {
        key: "billing_interval",
        field: "number",
        label: __("Every how many billing periods?", "arraysubs"),
        helpText: __("Only shown for a custom billing cycle.", "arraysubs"),
        min: 1,
        max: 365,
        suffix: __("interval", "arraysubs"),
        showWhen: (answers) => answers.billing_cycle === "custom",
        validate: (value, answers) => {
          if (answers.billing_cycle !== "custom") {
            return null;
          }

          return validateIntegerRange(
            value,
            1,
            365,
            __("Enter a billing interval between 1 and 365.", "arraysubs"),
          );
        },
      },
      {
        key: "billing_period",
        field: "select",
        label: __("Which period should that custom interval use?", "arraysubs"),
        showWhen: (answers) => answers.billing_cycle === "custom",
        options: [
          { value: "day", label: __("Day", "arraysubs") },
          { value: "week", label: __("Week", "arraysubs") },
          { value: "month", label: __("Month", "arraysubs") },
          { value: "year", label: __("Year", "arraysubs") },
        ],
      },
      {
        key: "plan_structure",
        field: "radio",
        label: __("How many subscription plans do you offer?", "arraysubs"),
        options: [
          {
            value: "single",
            label: __("One plan", "arraysubs"),
            description: __(
              "A single subscription product or offer.",
              "arraysubs",
            ),
          },
          {
            value: "multiple",
            label: __("Multiple plans / tiers", "arraysubs"),
            description: __(
              "Different plans at different price points, like Basic and Pro.",
              "arraysubs",
            ),
          },
        ],
      },
      {
        key: "offer_trials",
        field: "radio",
        label: __("Do you offer free trials?", "arraysubs"),
        options: YES_NO_OPTIONS,
      },
      {
        key: "trial_require_payment",
        field: "radio",
        label: __(
          "Should a payment method be required for a free trial?",
          "arraysubs",
        ),
        showWhen: (answers) => answers.offer_trials === "yes",
        options: YES_NO_OPTIONS,
      },
      {
        key: "one_trial_per_customer",
        field: "radio",
        label: __("Limit free trials to one per customer?", "arraysubs"),
        showWhen: (answers) => answers.offer_trials === "yes",
        options: YES_NO_OPTIONS,
      },
    ],
  },
  {
    id: "renewals",
    title: __("Billing & Renewal Rules", "arraysubs"),
    description: __(
      "Control grace periods, invoice timing, and skip/pause flexibility.",
      "arraysubs",
    ),
    questions: [
      {
        key: "grace_period",
        field: "radio",
        label: __("How strict should unpaid renewals be handled?", "arraysubs"),
        options: [
          {
            value: "strict",
            label: __("Strict", "arraysubs"),
            description: __(
              "Active for 1 day, then on-hold for 3 days.",
              "arraysubs",
            ),
          },
          {
            value: "standard",
            label: __("Standard", "arraysubs"),
            description: __(
              "Active for 3 days, then on-hold for 7 days.",
              "arraysubs",
            ),
          },
          {
            value: "lenient",
            label: __("Lenient", "arraysubs"),
            description: __(
              "Active for 5 days, then on-hold for 14 days.",
              "arraysubs",
            ),
          },
          { value: "custom", label: __("Custom", "arraysubs") },
        ],
      },
      {
        key: "custom_grace_active_days",
        field: "number",
        label: __(
          "How many days should the subscription stay active after a failed payment?",
          "arraysubs",
        ),
        min: 0,
        max: 30,
        suffix: __("days", "arraysubs"),
        showWhen: (answers) => answers.grace_period === "custom",
        validate: (value, answers) => {
          if (answers.grace_period !== "custom") {
            return null;
          }

          return validateIntegerRange(
            value,
            0,
            30,
            __("Enter a number from 0 to 30 days.", "arraysubs"),
          );
        },
      },
      {
        key: "custom_grace_hold_days",
        field: "number",
        label: __(
          "How many days should it remain on-hold before cancellation?",
          "arraysubs",
        ),
        min: 1,
        max: 60,
        suffix: __("days", "arraysubs"),
        showWhen: (answers) => answers.grace_period === "custom",
        validate: (value, answers) => {
          if (answers.grace_period !== "custom") {
            return null;
          }

          return validateIntegerRange(
            value,
            1,
            60,
            __("Enter a number from 1 to 60 days.", "arraysubs"),
          );
        },
      },
      {
        key: "invoice_timing",
        field: "radio",
        label: __("When should renewal invoices be generated?", "arraysubs"),
        options: [
          {
            value: "6_hours",
            label: __("6 hours before due date", "arraysubs"),
          },
          { value: "1_day", label: __("1 day before due date", "arraysubs") },
          { value: "3_days", label: __("3 days before due date", "arraysubs") },
        ],
      },
      {
        key: "billing_flexibility",
        field: "checkbox-group",
        label: __(
          "What billing flexibility should customers have?",
          "arraysubs",
        ),
        helpText: __(
          "Skip helps customers avoid a renewal, and pause gives them a temporary break without cancelling.",
          "arraysubs",
        ),
        options: [
          {
            value: "skip",
            label: __("Allow skipping the next renewal", "arraysubs"),
            description: __(
              "Best for physical boxes or fulfillment-driven plans.",
              "arraysubs",
            ),
          },
          {
            value: "pause",
            label: __("Allow pausing the subscription", "arraysubs"),
            description: __(
              "Useful for memberships, coaching, or seasonal usage.",
              "arraysubs",
            ),
          },
        ],
      },
      {
        key: "max_skips",
        field: "select",
        label: __("Maximum consecutive skips allowed", "arraysubs"),
        showWhen: (answers) =>
          (answers.billing_flexibility || []).includes("skip"),
        options: [
          { value: "1", label: __("1 skip", "arraysubs") },
          { value: "2", label: __("2 skips", "arraysubs") },
          { value: "3", label: __("3 skips", "arraysubs") },
          { value: "5", label: __("5 skips", "arraysubs") },
        ],
      },
      {
        key: "skip_cutoff_days",
        field: "select",
        label: __(
          "How many days before renewal can a skip still be requested?",
          "arraysubs",
        ),
        showWhen: (answers) =>
          (answers.billing_flexibility || []).includes("skip"),
        options: [
          { value: "0", label: __("Any time", "arraysubs") },
          { value: "2", label: __("2 days before", "arraysubs") },
          { value: "5", label: __("5 days before", "arraysubs") },
          { value: "7", label: __("7 days before", "arraysubs") },
        ],
      },
      {
        key: "max_pause_days",
        field: "select",
        label: __("Maximum pause duration", "arraysubs"),
        showWhen: (answers) =>
          (answers.billing_flexibility || []).includes("pause"),
        options: [
          { value: "14", label: __("14 days", "arraysubs") },
          { value: "30", label: __("30 days", "arraysubs") },
          { value: "60", label: __("60 days", "arraysubs") },
          { value: "90", label: __("90 days", "arraysubs") },
        ],
      },
      {
        key: "max_pauses",
        field: "select",
        label: __("Maximum pauses per subscription", "arraysubs"),
        showWhen: (answers) =>
          (answers.billing_flexibility || []).includes("pause"),
        options: [
          { value: "1", label: __("1 pause", "arraysubs") },
          { value: "2", label: __("2 pauses", "arraysubs") },
          { value: "3", label: __("3 pauses", "arraysubs") },
          { value: "5", label: __("5 pauses", "arraysubs") },
        ],
      },
    ],
  },
  {
    id: "checkout",
    title: __("Checkout & Cart Rules", "arraysubs"),
    description: __(
      "Shape how subscriptions behave in the cart, checkout, and account creation flow.",
      "arraysubs",
    ),
    questions: [
      {
        key: "multiple_subscriptions",
        field: "radio",
        label: __(
          "Can customers have multiple active subscriptions?",
          "arraysubs",
        ),
        options: [
          {
            value: "allow",
            label: __("Allow multiple subscriptions", "arraysubs"),
          },
          {
            value: "one_per_customer",
            label: __("Only one subscription per customer", "arraysubs"),
          },
          {
            value: "one_per_product",
            label: __("One subscription per product", "arraysubs"),
          },
        ],
      },
      {
        key: "auto_migrate",
        field: "radio",
        label: __(
          "Should checkout auto-migrate an existing subscription?",
          "arraysubs",
        ),
        showWhen: (answers) =>
          answers.multiple_subscriptions === "one_per_customer",
        options: [
          {
            value: "yes",
            label: __(
              "Yes — automatically replace the old subscription",
              "arraysubs",
            ),
          },
          {
            value: "no",
            label: __(
              "No — block checkout until they cancel first",
              "arraysubs",
            ),
          },
        ],
      },
      {
        key: "mixed_cart",
        field: "radio",
        label: __(
          "Allow subscription and non-subscription products in the same cart?",
          "arraysubs",
        ),
        showWhen: (answers) =>
          answers.multiple_subscriptions !== "one_per_customer",
        options: YES_NO_OPTIONS,
      },
      {
        key: "one_click_checkout",
        field: "radio",
        label: __("How should one-click checkout behave?", "arraysubs"),
        options: [
          {
            value: "default",
            label: __("Standard cart and checkout flow", "arraysubs"),
          },
          {
            value: "subscription_items",
            label: __("One-click checkout for subscription items", "arraysubs"),
          },
          {
            value: "all_items",
            label: __("One-click checkout for all products", "arraysubs"),
          },
        ],
      },
      {
        key: "disable_cart_page",
        field: "radio",
        label: __(
          "Should one-click items skip the cart page entirely?",
          "arraysubs",
        ),
        showWhen: (answers) => answers.one_click_checkout !== "default",
        options: YES_NO_OPTIONS,
      },
      {
        key: "auto_create_account",
        field: "radio",
        label: __(
          "Automatically create customer accounts at checkout?",
          "arraysubs",
        ),
        options: YES_NO_OPTIONS,
      },
    ],
  },
  {
    id: "portal",
    title: __("Plan Switching", "arraysubs"),
    description: __(
      "Decide whether customers can switch between plans from My Account → Subscriptions.",
      "arraysubs",
    ),
    questions: [
      {
        key: "plan_switching",
        field: "radio",
        label: __(
          "Should customers be able to switch plans from the portal?",
          "arraysubs",
        ),
        showWhen: (answers) => answers.plan_structure === "multiple",
        options: [
          {
            value: "all",
            label: __("Allow all switching directions", "arraysubs"),
          },
          {
            value: "upgrades_downgrades",
            label: __("Only upgrades and downgrades", "arraysubs"),
          },
          { value: "upgrades_only", label: __("Only upgrades", "arraysubs") },
          {
            value: "disabled",
            label: __("Disable plan switching", "arraysubs"),
          },
        ],
      },
      {
        key: "proration_type",
        field: "radio",
        label: __(
          "How should price differences be handled during plan switching?",
          "arraysubs",
        ),
        showWhen: (answers) =>
          answers.plan_structure === "multiple" &&
          answers.plan_switching !== "disabled",
        options: [
          {
            value: "prorate_immediately",
            label: __("Prorate immediately", "arraysubs"),
          },
          {
            value: "apply_at_renewal",
            label: __("Apply the change at renewal", "arraysubs"),
          },
          { value: "no_proration", label: __("No proration", "arraysubs") },
        ],
      },
    ],
  },
  {
    id: "cancellation",
    title: __("Cancellation & Retention", "arraysubs"),
    description: __(
      "Decide what happens when a customer tries to leave and how hard the wizard should work to save the subscription.",
      "arraysubs",
    ),
    questions: [
      {
        key: "cancel_timing",
        field: "radio",
        label: __("When should a cancellation take effect?", "arraysubs"),
        options: [
          { value: "immediately", label: __("Immediately", "arraysubs") },
          {
            value: "end_of_period",
            label: __("At the end of the billing period", "arraysubs"),
          },
        ],
      },
      {
        key: "require_cancel_reason",
        field: "radio",
        label: __(
          "Should customers be required to provide a cancellation reason?",
          "arraysubs",
        ),
        options: YES_NO_OPTIONS,
      },
      {
        key: "retention_offers",
        field: "radio",
        label: __(
          "Show retention offers during the cancellation flow?",
          "arraysubs",
        ),
        options: YES_NO_OPTIONS,
      },
      {
        key: "retention_offer_types",
        field: "checkbox-group",
        label: __("Which retention offers should be enabled?", "arraysubs"),
        showWhen: (answers) => answers.retention_offers === "yes",
        options: [
          { value: "discount", label: __("Discount offer", "arraysubs") },
          { value: "pause", label: __("Pause offer", "arraysubs") },
          { value: "downgrade", label: __("Downgrade offer", "arraysubs") },
          {
            value: "contact_support",
            label: __("Contact support", "arraysubs"),
          },
        ],
      },
      {
        key: "retention_discount_percent",
        field: "select",
        label: __("Retention discount percentage", "arraysubs"),
        showWhen: (answers) =>
          answers.retention_offers === "yes" &&
          (answers.retention_offer_types || []).includes("discount"),
        options: [
          { value: "10", label: __("10% off", "arraysubs") },
          { value: "20", label: __("20% off", "arraysubs") },
          { value: "30", label: __("30% off", "arraysubs") },
          { value: "50", label: __("50% off", "arraysubs") },
        ],
      },
      {
        key: "retention_discount_cycles",
        field: "select",
        label: __(
          "How many billing cycles should that discount last?",
          "arraysubs",
        ),
        showWhen: (answers) =>
          answers.retention_offers === "yes" &&
          (answers.retention_offer_types || []).includes("discount"),
        options: [
          { value: "1", label: __("1 cycle", "arraysubs") },
          { value: "2", label: __("2 cycles", "arraysubs") },
          { value: "3", label: __("3 cycles", "arraysubs") },
          { value: "6", label: __("6 cycles", "arraysubs") },
        ],
      },
      {
        key: "refund_policy",
        field: "radio",
        label: __(
          "What should the default refund behavior be on cancellation?",
          "arraysubs",
        ),
        options: [
          {
            value: "immediate",
            label: __("Immediate prorated refund", "arraysubs"),
          },
          {
            value: "end_of_period",
            label: __("Refund at end of period", "arraysubs"),
          },
          { value: "none", label: __("No automatic refund", "arraysubs") },
        ],
      },
    ],
  },
  {
    id: "access",
    title: __("Access Control & Content Gating", "arraysubs"),
    description: __(
      "Configure how non-subscribers and expired members should be handled when content is restricted.",
      "arraysubs",
    ),
    questions: [
      {
        key: "enable_access_control",
        field: "radio",
        label: __(
          "Do you need subscription-based content restriction?",
          "arraysubs",
        ),
        showWhen: (answers) =>
          !isAccessControlBusinessType(answers.business_type),
        options: YES_NO_OPTIONS,
      },
      {
        key: "restricted_redirect",
        field: "radio",
        label: __(
          "What should non-subscribers see when they hit restricted content?",
          "arraysubs",
        ),
        showWhen: (answers) =>
          isAccessControlBusinessType(answers.business_type) ||
          answers.enable_access_control === "yes",
        options: [
          {
            value: "redirect",
            label: __("Redirect to a pricing or signup page", "arraysubs"),
          },
          {
            value: "message",
            label: __("Show a restricted content message", "arraysubs"),
          },
          {
            value: "login",
            label: __("Ask the visitor to log in first", "arraysubs"),
          },
        ],
      },
      {
        key: "restricted_redirect_url",
        field: "text",
        label: __(
          "Where should restricted visitors be redirected?",
          "arraysubs",
        ),
        helpText: __(
          "Use a relative path such as /pricing or /subscribe.",
          "arraysubs",
        ),
        placeholder: "/pricing",
        showWhen: (answers) =>
          (isAccessControlBusinessType(answers.business_type) ||
            answers.enable_access_control === "yes") &&
          answers.restricted_redirect === "redirect",
        validate: (value, answers) => {
          if (
            !(
              (isAccessControlBusinessType(answers.business_type) ||
                answers.enable_access_control === "yes") &&
              answers.restricted_redirect === "redirect"
            )
          ) {
            return null;
          }

          if (!value || !String(value).trim()) {
            return __("Enter a redirect path such as /pricing.", "arraysubs");
          }

          return null;
        },
      },
      {
        key: "require_login",
        field: "radio",
        label: __(
          "Require login before checking subscription access rules?",
          "arraysubs",
        ),
        showWhen: (answers) =>
          isAccessControlBusinessType(answers.business_type) ||
          answers.enable_access_control === "yes",
        options: YES_NO_OPTIONS,
      },
    ],
  },
  {
    id: "emails",
    title: __("Emails & Notifications", "arraysubs"),
    description: __(
      "Pick how chatty the subscription system should be with customers and admins.",
      "arraysubs",
    ),
    questions: [
      {
        key: "email_level",
        field: "radio",
        label: __(
          "How many customer email notifications should be sent?",
          "arraysubs",
        ),
        options: [
          { value: "all", label: __("All notifications", "arraysubs") },
          { value: "essential", label: __("Essential only", "arraysubs") },
          { value: "minimal", label: __("Minimal", "arraysubs") },
          { value: "custom", label: __("Let me choose", "arraysubs") },
        ],
      },
      {
        key: "custom_emails",
        field: "checkbox-group",
        label: __("Choose the customer emails to enable", "arraysubs"),
        showWhen: (answers) => answers.email_level === "custom",
        options: EMAIL_OPTIONS,
        helpText: __(
          "The wizard will only toggle the enabled state — you can still edit subjects and body text later.",
          "arraysubs",
        ),
      },
      {
        key: "renewal_reminder_days",
        field: "select",
        label: __(
          "How many days before renewal should customers get a reminder?",
          "arraysubs",
        ),
        showWhen: isRenewalReminderEnabled,
        options: [
          { value: "1", label: __("1 day before", "arraysubs") },
          { value: "3", label: __("3 days before", "arraysubs") },
          { value: "5", label: __("5 days before", "arraysubs") },
          { value: "7", label: __("7 days before", "arraysubs") },
        ],
      },
      {
        key: "admin_emails",
        field: "checkbox-group",
        label: __(
          "Which admin notifications should stay enabled?",
          "arraysubs",
        ),
        options: ADMIN_EMAIL_OPTIONS,
      },
    ],
  },
  {
    id: "features",
    title: __("Additional Features & Tools", "arraysubs"),
    description: __(
      "Enable optional modules and tighten a few final operational preferences.",
      "arraysubs",
    ),
    questions: [
      {
        key: "additional_features",
        field: "checkbox-group",
        label: __(
          "Which optional features should be enabled now?",
          "arraysubs",
        ),
        options: ADDITIONAL_FEATURE_OPTIONS,
      },
      {
        key: "store_credit_auto_apply",
        field: "radio",
        label: __(
          "Should store credit automatically apply to renewal payments?",
          "arraysubs",
        ),
        showWhen: (answers) =>
          (answers.additional_features || []).includes("store_credit"),
        options: YES_NO_OPTIONS,
      },
      {
        key: "store_credit_expiration",
        field: "select",
        label: __("When should store credits expire?", "arraysubs"),
        showWhen: (answers) =>
          (answers.additional_features || []).includes("store_credit"),
        options: [
          { value: "0", label: __("Never expire", "arraysubs") },
          { value: "90", label: __("After 90 days", "arraysubs") },
          { value: "180", label: __("After 180 days", "arraysubs") },
          { value: "365", label: __("After 365 days", "arraysubs") },
        ],
      },
      {
        key: "feature_manager_product_page",
        field: "radio",
        label: __(
          "Show Feature Manager highlights on product pages?",
          "arraysubs",
        ),
        showWhen: (answers) =>
          (answers.additional_features || []).includes("feature_manager"),
        options: YES_NO_OPTIONS,
      },
      {
        key: "multi_login_max_sessions",
        field: "select",
        label: __(
          "Maximum concurrent login sessions per customer",
          "arraysubs",
        ),
        showWhen: (answers) =>
          (answers.additional_features || []).includes("multi_login"),
        options: [
          { value: "1", label: __("1 session", "arraysubs") },
          { value: "2", label: __("2 sessions", "arraysubs") },
          { value: "3", label: __("3 sessions", "arraysubs") },
          { value: "5", label: __("5 sessions", "arraysubs") },
        ],
      },
      {
        key: "dashboard_redirect",
        field: "radio",
        label: __("Where should blocked dashboard users be sent?", "arraysubs"),
        showWhen: (answers) =>
          (answers.additional_features || []).includes("restrict_dashboard"),
        options: [
          { value: "my_account", label: __("My Account page", "arraysubs") },
          { value: "not_found", label: __("Show a 404 page", "arraysubs") },
        ],
      },
    ],
  },
  {
    id: "review",
    title: __("Review & Apply", "arraysubs"),
    description: __(
      "Review the answers below before the wizard applies your configuration.",
      "arraysubs",
    ),
    questions: [],
  },
];

const QUESTION_LOOKUP = new Map();
WIZARD_STEPS.forEach((step, stepIndex) => {
  step.questions.forEach((question) => {
    QUESTION_LOOKUP.set(question.key, { question, stepIndex });
  });
});

export const getVisibleQuestions = (step, answers, isProActive) => {
  return (step?.questions || []).filter((question) => {
    if (question.proOnly && !isProActive) {
      return false;
    }

    if (typeof question.showWhen === "function") {
      return question.showWhen(answers);
    }

    return true;
  });
};

export const findQuestionByKey = (key) =>
  QUESTION_LOOKUP.get(key)?.question || null;

export const findStepIndexByQuestionKey = (key) => {
  return QUESTION_LOOKUP.get(key)?.stepIndex ?? -1;
};

export const getQuestionOptionLabel = (question, value, isProActive) => {
  if (!question?.options) {
    return value;
  }

  const options = question.options.filter(
    (option) => isProActive || !option.proOnly,
  );
  const match = options.find((option) => option.value === value);

  return match?.label || value;
};

export const getDefaultCustomEmails = () => [...DEFAULT_CUSTOM_EMAILS];

export const getDefaultAdminEmails = () => [...DEFAULT_ADMIN_EMAILS];
