<script lang="ts" setup>
import { Head, usePage } from '@inertiajs/vue3'
import { computed, ref, watch } from 'vue'
import MarketingLayout from '@/Layouts/MarketingLayout.vue'
import BuildYourOwn from '@/Components/Marketing/BuildYourOwn.vue'
import ScrollReveal from '@/Components/Marketing/ScrollReveal.vue'
import { crossDomainUrl } from '@/utils/resolvers'
import type { PlanConfigGroup } from '@/types'

defineOptions({ layout: MarketingLayout })

interface PlanPrice {
  id: number
  plan_id: number
  billing_cycle: 'monthly' | 'quarterly' | 'semi_annual' | 'annual'
  price: string
}

interface Plan {
  id: number
  name: string
  slug: string
  description: string | null
  service_type: string
  price: string
  currency: string
  billing_cycle: string
  features: Record<string, string> | null
  stock_quantity: number | null
  status: string
  sort_order: number
  prices?: PlanPrice[]
  config_groups_count?: number
}

interface ServiceTypeConfig {
  value: string
  label: string
  icon: string
}

interface PageProps {
  plans: Plan[]
  groupedPlans: Record<string, Plan[]>
  byoConfigGroups?: Record<string, PlanConfigGroup>
  domains: { marketing: string; account: string; admin: string }
}

const page = usePage()
const props = computed(() => page.props as unknown as PageProps)
const accountUrl = computed(() => crossDomainUrl(props.value.domains?.account))

// BYO mode toggle
const pricingMode = ref<'preset' | 'byo'>('preset')

const byoConfigGroups = computed<Record<string, PlanConfigGroup>>(() => {
  return (props.value.byoConfigGroups ?? {}) as Record<string, PlanConfigGroup>
})

const hasByoGroups = computed<boolean>(() => {
  return Object.keys(byoConfigGroups.value).length > 0
})

// Service types that have BYO config groups
const byoServiceTypes = computed<ServiceTypeConfig[]>(() => {
  return allServiceTypes.filter(st => byoConfigGroups.value[st.value])
})

// When switching to BYO mode, ensure the active tab is a BYO-supported type
watch(pricingMode, (mode) => {
  if (mode === 'byo') {
    const hasByoTab = byoServiceTypes.value.some(st => st.value === activeTab.value)
    if (!hasByoTab && byoServiceTypes.value.length > 0) {
      activeTab.value = byoServiceTypes.value[0].value
    }
  }
})

// Active BYO config group for current tab
const activeByoGroup = computed<PlanConfigGroup | null>(() => {
  if (pricingMode.value !== 'byo') return null
  return byoConfigGroups.value[effectiveTab.value] ?? null
})

const allServiceTypes: ServiceTypeConfig[] = [
  { value: 'vps', label: 'VPS', icon: 'tabler-cloud' },
  { value: 'dedicated', label: 'Dedicated Servers', icon: 'tabler-server' },
  { value: 'hosting', label: 'Web Hosting', icon: 'tabler-world' },
  { value: 'mysql', label: 'MySQL', icon: 'tabler-database' },
  { value: 'game', label: 'Game Servers', icon: 'tabler-device-gamepad-2' },
  { value: 'backups', label: 'Backups', icon: 'tabler-cloud-upload' },
]

// Filter out plans with hidden/internal status (client-side safety)
const publicPlans = computed<Plan[]>(() => {
  return (props.value.plans || []).filter(
    (p: Plan) => !['hidden', 'internal'].includes(p.status),
  )
})

// Group plans by service type
const groupedPlans = computed<Record<string, Plan[]>>(() => {
  const groups: Record<string, Plan[]> = {}
  publicPlans.value.forEach((plan: Plan) => {
    if (!groups[plan.service_type]) {
      groups[plan.service_type] = []
    }
    groups[plan.service_type].push(plan)
  })
  return groups
})

// Only show tabs that have plans
const availableServiceTypes = computed<ServiceTypeConfig[]>(() => {
  return allServiceTypes.filter((st: ServiceTypeConfig) => {
    const plans = groupedPlans.value[st.value]
    return plans && plans.length > 0
  })
})

// Default to VPS if available, otherwise first available type
const activeTab = ref<string>('vps')

// If VPS has no plans, pick the first available
const effectiveTab = computed<string>(() => {
  if (availableServiceTypes.value.length === 0) return ''
  const hasActive = availableServiceTypes.value.some(
    (st: ServiceTypeConfig) => st.value === activeTab.value,
  )
  if (hasActive) return activeTab.value
  return availableServiceTypes.value[0].value
})

// Plans for the currently active tab
const filteredPlans = computed<Plan[]>(() => {
  return groupedPlans.value[effectiveTab.value] || []
})

const billingCycles = [
  { value: 'monthly', label: 'Monthly', months: 1, discount: 0 },
  { value: 'quarterly', label: 'Quarterly', months: 3, discount: 5 },
  { value: 'semi_annual', label: 'Semi-Annual', months: 6, discount: 10 },
  { value: 'annual', label: 'Annual', months: 12, discount: 15 },
] as const

const selectedCycle = ref<string>('monthly')

// Animate savings badge
const savingsAnimating = ref<boolean>(false)
watch(selectedCycle, (newVal) => {
  if (newVal !== 'monthly') {
    savingsAnimating.value = true
    setTimeout(() => {
      savingsAnimating.value = false
    }, 600)
  }
})

const currentDiscount = computed<number>(() => {
  return billingCycles.find(c => c.value === selectedCycle.value)?.discount ?? 0
})

function hasPrices(plan: Plan): boolean {
  if (!plan.prices || plan.prices.length === 0) return false
  return plan.prices.some((p: PlanPrice) => parseFloat(p.price) > 0)
}

function hasConfigGroupsOnly(plan: Plan): boolean {
  return !hasPrices(plan) && (plan.config_groups_count ?? 0) > 0
}

function isOrderable(plan: Plan): boolean {
  return hasPrices(plan) || hasConfigGroupsOnly(plan)
}

function getCyclePrice(plan: Plan): string {
  const planPrice = plan.prices?.find((p: PlanPrice) => p.billing_cycle === selectedCycle.value)
  if (planPrice) {
    const price = parseFloat(planPrice.price) || 0
    return price % 1 === 0 ? price.toString() : price.toFixed(2)
  }
  return getMonthlyPrice(plan)
}

function getMonthlyEquivalent(plan: Plan): string {
  const planPrice = plan.prices?.find((p: PlanPrice) => p.billing_cycle === selectedCycle.value)
  const cycle = billingCycles.find(c => c.value === selectedCycle.value)
  if (planPrice && cycle && cycle.months > 1) {
    return (parseFloat(planPrice.price) / cycle.months).toFixed(2)
  }
  return getMonthlyPrice(plan)
}

function getCycleLabel(): string {
  return billingCycles.find(c => c.value === selectedCycle.value)?.label ?? 'Monthly'
}

function getCycleSuffix(): string {
  const cycle = selectedCycle.value
  if (cycle === 'monthly') return '/mo'
  if (cycle === 'quarterly') return '/qtr'
  if (cycle === 'semi_annual') return '/6mo'
  if (cycle === 'annual') return '/yr'
  return '/mo'
}

// Internal provisioning keys that should never be shown to visitors
const internalKeys = new Set([
  'synergy_package_id',
  'enhance_package_id',
  'pterodactyl_package_id',
  'synergy_server_id',
])

function isDisplayableFeature(key: string): boolean {
  return !internalKeys.has(key)
}

const featureLabels: Record<string, string> = {
  vcpu: 'vCPU',
  cpu: 'CPU',
  ram: 'RAM',
  storage: 'Storage',
  bandwidth: 'Bandwidth',
  ip_addresses: 'IP Addresses',
  backups: 'Backups',
  ddos_protection: 'DDoS Protection',
  support: 'Support',
  uptime_sla: 'Uptime SLA',
}

function humanizeFeatureKey(key: string): string {
  if (featureLabels[key]) return featureLabels[key]
  return key
    .replace(/_/g, ' ')
    .replace(/\b\w/g, c => c.toUpperCase())
}

function getDisplayFeatures(plan: Plan): Array<{ key: string; value: string }> {
  if (!plan.features) return []
  return Object.entries(plan.features)
    .filter(([key]) => isDisplayableFeature(key))
    .map(([key, value]) => ({ key, value }))
}

function getMonthlyPrice(plan: Plan): string {
  const price = parseFloat(plan.price ?? '0') || 0
  return price % 1 === 0 ? price.toString() : price.toFixed(2)
}

function isPopular(index: number): boolean {
  return filteredPlans.value.length > 1 && index === 1
}

function isBestValue(index: number): boolean {
  return filteredPlans.value.length > 2 && index === filteredPlans.value.length - 1
}

// Feature comparison data filtered to active tab
const featureComparison = computed(() => {
  if (filteredPlans.value.length === 0) return []
  const allFeatures = new Set<string>()
  filteredPlans.value.forEach((plan: Plan) => {
    if (plan.features) {
      Object.keys(plan.features)
        .filter(isDisplayableFeature)
        .forEach(f => allFeatures.add(f))
    }
  })
  return Array.from(allFeatures).map(feature => ({
    feature: humanizeFeatureKey(feature),
    key: feature,
    plans: filteredPlans.value.map((plan: Plan) => ({
      value: plan.features?.[feature] ?? null,
    })),
  }))
})

// Currency selector
const currencies = [
  { code: 'USD', symbol: '$', label: 'USD ($)' },
  { code: 'EUR', symbol: '\u20AC', label: 'EUR (\u20AC)' },
  { code: 'GBP', symbol: '\u00A3', label: 'GBP (\u00A3)' },
  { code: 'CAD', symbol: 'C$', label: 'CAD (C$)' },
  { code: 'AUD', symbol: 'A$', label: 'AUD (A$)' },
]

const selectedCurrency = ref<string>(
  (typeof window !== 'undefined' && localStorage.getItem('ezscale-currency')) || 'USD',
)

watch(selectedCurrency, (val) => {
  if (typeof window !== 'undefined') {
    localStorage.setItem('ezscale-currency', val)
  }
})

function getCurrencySymbol(): string {
  return currencies.find(c => c.code === selectedCurrency.value)?.symbol ?? '$'
}

const faqs = [
  {
    question: 'Can I upgrade my plan later?',
    answer: 'Yes! You can upgrade or downgrade your plan at any time from your account dashboard. Changes take effect immediately and billing is prorated.',
  },
  {
    question: 'What payment methods do you accept?',
    answer: 'We accept all major credit cards (Visa, Mastercard, American Express) via Stripe, as well as PayPal. Your payment information is always kept safe and secure.',
  },
  {
    question: 'Is there a money-back guarantee?',
    answer: 'Yes, all plans come with a 14-day money-back guarantee. If you\'re not satisfied, contact support for a full refund.',
  },
  {
    question: 'Do you offer custom configurations?',
    answer: 'Absolutely. Contact our sales team for custom server configurations, bulk pricing, or enterprise solutions tailored to your needs.',
  },
]

const openFaq = ref<number | undefined>(undefined)
</script>

<template>
  <Head title="Pricing | EZSCALE" />
  <div class="pricing-page">
    <!-- Hero Section -->
    <section class="pricing-hero">
      <div class="pricing-hero__mesh" />
      <div class="pricing-hero__grid" />
      <VContainer style="position: relative; z-index: 1;">
        <div class="text-center py-16">
          <VChip
            color="primary"
            variant="tonal"
            class="mb-5 pricing-hero__badge"
          >
            <VIcon
              icon="tabler-sparkles"
              size="14"
              class="me-1"
            />
            Simple, transparent pricing
          </VChip>

          <h1 class="pricing-hero__title mb-4">
            Find the<br class="d-sm-none"> <span class="pricing-hero__gradient-text">Perfect Plan</span>
          </h1>

          <p
            class="text-body-1 text-sm-h6 font-weight-regular text-medium-emphasis mx-auto mb-2 px-4 px-sm-0"
            style="max-inline-size: 560px;"
          >
            Enterprise-grade infrastructure with transparent, predictable pricing. No hidden fees, no surprises.
          </p>
        </div>
      </VContainer>
    </section>

    <!-- Main Content -->
    <VContainer class="pricing-content">
      <!-- Pricing Mode Toggle (Preset / BYO) -->
      <div
        v-if="hasByoGroups && publicPlans.length"
        class="d-flex justify-center mb-6"
      >
        <div class="pricing-mode-toggle">
          <button
            :class="['pricing-mode-toggle__item', { 'pricing-mode-toggle__item--active': pricingMode === 'preset' }]"
            @click="pricingMode = 'preset'"
          >
            <VIcon
              icon="tabler-layout-grid"
              size="18"
              class="me-2"
            />
            Preset Plans
          </button>
          <button
            :class="['pricing-mode-toggle__item', { 'pricing-mode-toggle__item--active': pricingMode === 'byo' }]"
            @click="pricingMode = 'byo'"
          >
            <VIcon
              icon="tabler-adjustments"
              size="18"
              class="me-2"
            />
            Build Your Own
          </button>
        </div>
      </div>

      <!-- Service Type Tabs -->
      <div
        v-if="(pricingMode === 'preset' ? availableServiceTypes : byoServiceTypes).length > 1"
        class="d-flex justify-center mb-10"
      >
        <ScrollReveal>
          <div class="service-tabs">
            <button
              v-for="st in (pricingMode === 'preset' ? availableServiceTypes : byoServiceTypes)"
              :key="st.value"
              :class="['service-tabs__item', { 'service-tabs__item--active': effectiveTab === st.value }]"
              @click="activeTab = st.value"
            >
              <VIcon
                :icon="st.icon"
                size="18"
                class="me-2"
              />
              {{ st.label }}
            </button>
          </div>
        </ScrollReveal>
      </div>

      <!-- Billing Cycle Toggle -->
      <ScrollReveal v-if="publicPlans.length && pricingMode === 'preset'">
        <div class="d-flex flex-column align-center mb-12">
          <div class="billing-toggle">
            <button
              v-for="cycle in billingCycles"
              :key="cycle.value"
              :class="['billing-toggle__item', { 'billing-toggle__item--active': selectedCycle === cycle.value }]"
              @click="selectedCycle = cycle.value"
            >
              {{ cycle.label }}
            </button>
          </div>

          <!-- Savings callout -->
          <Transition name="savings-pop">
            <div
              v-if="currentDiscount > 0"
              :class="['savings-badge mt-4', { 'savings-badge--animate': savingsAnimating }]"
            >
              <VIcon
                icon="tabler-discount-2"
                size="16"
                class="me-1"
              />
              Save {{ currentDiscount }}% with {{ getCycleLabel() }} billing
            </div>
          </Transition>

          <!-- Currency Selector -->
          <div class="mt-4">
            <VSelect
              v-model="selectedCurrency"
              :items="currencies"
              item-title="label"
              item-value="code"
              density="compact"
              variant="outlined"
              hide-details
              style="max-width: 160px;"
              prepend-inner-icon="tabler-currency-dollar"
            />
          </div>
        </div>
      </ScrollReveal>

      <!-- Build Your Own Configurator -->
      <div v-if="pricingMode === 'byo' && activeByoGroup">
        <BuildYourOwn
          :config-group="activeByoGroup"
          :billing-cycle="selectedCycle"
          :account-url="accountUrl"
        />
      </div>

      <div
        v-else-if="pricingMode === 'byo' && !activeByoGroup"
        class="text-center py-8"
      >
        <VIcon
          icon="tabler-adjustments-off"
          size="48"
          class="text-medium-emphasis mb-4"
        />
        <h3 class="text-h5 font-weight-bold mb-2">
          Custom Configuration Coming Soon
        </h3>
        <p class="text-body-1 text-medium-emphasis">
          Build Your Own is not yet available for this service type. Switch to Preset Plans or choose a different service.
        </p>
      </div>

      <!-- Plan Cards -->
      <div
        v-else-if="filteredPlans.length && pricingMode === 'preset'"
        class="plan-cards-grid"
      >
        <ScrollReveal>
          <VRow justify="center">
            <VCol
              v-for="(plan, index) in filteredPlans"
              :key="plan.id"
              cols="12"
              sm="6"
              :md="filteredPlans.length <= 3 ? 4 : 3"
              :lg="filteredPlans.length <= 3 ? 4 : 3"
            >
              <div
                :class="[
                  'plan-card',
                  { 'plan-card--popular': isPopular(index) },
                  { 'plan-card--best-value': isBestValue(index) },
                  { 'plan-card--contact': !hasPrices(plan) && !hasConfigGroupsOnly(plan) },
                  `fade-in-up stagger-${index + 1}`,
                ]"
              >
                <!-- Popular Badge -->
                <div
                  v-if="isPopular(index)"
                  class="plan-card__popular-badge"
                >
                  <VIcon
                    icon="tabler-star-filled"
                    size="12"
                    class="me-1"
                  />
                  Most Popular
                </div>

                <!-- Best Value Badge -->
                <div
                  v-if="isBestValue(index)"
                  class="plan-card__best-value-badge"
                >
                  <VIcon
                    icon="tabler-trophy"
                    size="12"
                    class="me-1"
                  />
                  Best Value
                </div>

                <div class="plan-card__inner">
                  <!-- Plan Header -->
                  <div class="plan-card__header">
                    <h3 class="plan-card__name">
                      {{ plan.name }}
                    </h3>
                    <p class="plan-card__description">
                      {{ plan.description || 'High performance hosting' }}
                    </p>
                  </div>

                  <!-- Price -->
                  <div class="plan-card__price-block">
                    <template v-if="hasPrices(plan)">
                      <div class="plan-card__price">
                        <span class="plan-card__currency">$</span>
                        <span class="plan-card__amount">{{ getCyclePrice(plan) }}</span>
                        <span class="plan-card__period">{{ getCycleSuffix() }}</span>
                      </div>
                      <div
                        v-if="selectedCycle !== 'monthly'"
                        class="plan-card__equivalent"
                      >
                        ${{ getMonthlyEquivalent(plan) }}/mo equivalent
                      </div>
                      <div
                        v-else
                        class="plan-card__equivalent"
                      >
                        Billed monthly
                      </div>
                    </template>
                    <template v-else-if="hasConfigGroupsOnly(plan)">
                      <div class="plan-card__price">
                        <span class="plan-card__currency">$</span>
                        <span class="plan-card__amount">0</span>
                        <span class="plan-card__period">/mo base</span>
                      </div>
                      <div class="plan-card__equivalent">
                        Configure options to build your price
                      </div>
                    </template>
                    <template v-else>
                      <div class="plan-card__custom-price">
                        Custom Pricing
                      </div>
                      <div class="plan-card__equivalent">
                        Tailored to your needs
                      </div>
                    </template>
                  </div>

                  <!-- CTA Buttons -->
                  <div class="plan-card__cta">
                    <a
                      v-if="isOrderable(plan)"
                      :href="accountUrl + '/checkout/' + plan.id + '?cycle=' + selectedCycle"
                      class="text-decoration-none d-block"
                    >
                      <VBtn
                        block
                        size="large"
                        rounded="lg"
                        :color="isPopular(index) ? 'primary' : undefined"
                        :variant="isPopular(index) ? 'flat' : 'outlined'"
                        :class="{ 'plan-card__cta-btn--popular': isPopular(index), 'plan-card__cta-btn': !isPopular(index) }"
                      >
                        {{ hasConfigGroupsOnly(plan) ? 'Configure & Order' : 'Get Started' }}
                        <VIcon
                          :icon="hasConfigGroupsOnly(plan) ? 'tabler-settings' : 'tabler-arrow-right'"
                          size="18"
                          end
                        />
                      </VBtn>
                    </a>
                    <a
                      v-if="isOrderable(plan) && hasPrices(plan)"
                      :href="accountUrl + '/cart?add=' + plan.id + '&cycle=' + selectedCycle"
                      class="text-decoration-none d-block mt-2"
                    >
                      <VBtn
                        block
                        size="small"
                        variant="text"
                        color="primary"
                      >
                        <VIcon icon="tabler-shopping-cart-plus" size="16" start />
                        Add to Cart
                      </VBtn>
                    </a>
                    <a
                      v-if="!isOrderable(plan)"
                      href="/contact"
                      class="text-decoration-none d-block"
                    >
                      <VBtn
                        block
                        size="large"
                        rounded="lg"
                        variant="outlined"
                        class="plan-card__cta-btn--contact"
                      >
                        Get a Quote
                        <VIcon
                          icon="tabler-arrow-right"
                          size="18"
                          end
                        />
                      </VBtn>
                    </a>
                  </div>

                  <!-- Divider -->
                  <div class="plan-card__divider" />

                  <!-- Features -->
                  <ul class="plan-card__features">
                    <li
                      v-for="feat in getDisplayFeatures(plan)"
                      :key="feat.key"
                      class="plan-card__feature"
                    >
                      <VIcon
                        icon="tabler-circle-check-filled"
                        size="18"
                        :color="isPopular(index) ? 'primary' : 'success'"
                        class="plan-card__feature-icon"
                      />
                      <span class="plan-card__feature-label">{{ humanizeFeatureKey(feat.key) }}</span>
                      <span class="plan-card__feature-value">{{ feat.value }}</span>
                    </li>
                  </ul>
                </div>
              </div>
            </VCol>
          </VRow>
        </ScrollReveal>
      </div>

      <!-- Empty state -->
      <div
        v-else-if="pricingMode === 'preset' && publicPlans.length === 0"
        class="text-center py-16"
      >
        <div class="empty-state-icon mb-6">
          <VIcon
            icon="tabler-package"
            size="48"
            class="text-medium-emphasis"
          />
        </div>
        <h3 class="text-h5 font-weight-bold mb-2">
          Plans Coming Soon
        </h3>
        <p class="text-body-1 text-medium-emphasis">
          We're finalizing our plans. Check back soon or sign up to be notified.
        </p>
      </div>

      <!-- Money-back guarantee -->
      <ScrollReveal v-if="publicPlans.length && pricingMode === 'preset'">
        <div class="guarantee-banner mt-12">
          <div class="guarantee-banner__inner">
            <div class="guarantee-banner__icon">
              <VIcon
                icon="tabler-shield-check"
                size="24"
              />
            </div>
            <div>
              <span class="guarantee-banner__title">14-Day Money-Back Guarantee</span>
              <span class="guarantee-banner__subtitle">Try risk-free. Not satisfied? Get a full refund, no questions asked.</span>
            </div>
          </div>
        </div>
      </ScrollReveal>
    </VContainer>

    <!-- Feature Comparison -->
    <section
      v-if="pricingMode === 'preset' && filteredPlans.length && featureComparison.length"
      class="comparison-section"
    >
      <VContainer>
        <ScrollReveal>
          <div class="text-center mb-12">
            <VChip
              color="primary"
              variant="tonal"
              class="mb-4"
            >
              Compare Plans
            </VChip>
            <h2 class="text-h4 font-weight-bold mb-3">
              Detailed <span class="hero-gradient-text">Comparison</span>
            </h2>
            <p
              class="text-body-1 text-medium-emphasis mx-auto"
              style="max-inline-size: 500px;"
            >
              See exactly what each plan includes so you can make the right choice.
            </p>
          </div>

          <div class="comparison-table-wrapper">
            <table class="comparison-table">
              <thead>
                <tr>
                  <th class="comparison-table__feature-header">
                    Features
                  </th>
                  <th
                    v-for="(plan, index) in filteredPlans"
                    :key="plan.id"
                    :class="['comparison-table__plan-header', { 'comparison-table__plan-header--popular': isPopular(index) }]"
                  >
                    <div class="comparison-table__plan-name">
                      {{ plan.name }}
                      <VIcon
                        v-if="isPopular(index)"
                        icon="tabler-star-filled"
                        size="14"
                        color="primary"
                        class="ms-1"
                      />
                    </div>
                    <div class="comparison-table__plan-price">
                      <template v-if="hasPrices(plan)">
                        ${{ getCyclePrice(plan) }}{{ getCycleSuffix() }}
                      </template>
                      <template v-else-if="hasConfigGroupsOnly(plan)">
                        Configurable
                      </template>
                      <template v-else>
                        Custom
                      </template>
                    </div>
                  </th>
                </tr>
              </thead>

              <tbody>
                <tr
                  v-for="row in featureComparison"
                  :key="row.feature"
                  class="comparison-table__row"
                >
                  <td class="comparison-table__feature-name">
                    {{ row.feature }}
                  </td>
                  <td
                    v-for="(planData, pIndex) in row.plans"
                    :key="pIndex"
                    :class="['comparison-table__cell', { 'comparison-table__cell--popular': isPopular(pIndex) }]"
                  >
                    <template v-if="planData.value">
                      <span class="comparison-table__value">{{ planData.value }}</span>
                    </template>
                    <VIcon
                      v-else
                      icon="tabler-minus"
                      size="16"
                      class="text-disabled"
                    />
                  </td>
                </tr>
              </tbody>

              <tfoot>
                <tr>
                  <td />
                  <td
                    v-for="(plan, index) in filteredPlans"
                    :key="plan.id"
                    class="comparison-table__footer-cell"
                  >
                    <a
                      v-if="isOrderable(plan)"
                      :href="accountUrl + '/checkout/' + plan.id + '?cycle=' + selectedCycle"
                      class="text-decoration-none"
                    >
                      <VBtn
                        :variant="isPopular(index) ? 'flat' : 'outlined'"
                        :color="isPopular(index) ? 'primary' : undefined"
                        rounded="lg"
                        size="small"
                      >
                        {{ hasConfigGroupsOnly(plan) ? 'Configure & Order' : 'Choose Plan' }}
                      </VBtn>
                    </a>
                    <a
                      v-else
                      href="/contact"
                      class="text-decoration-none"
                    >
                      <VBtn
                        variant="outlined"
                        rounded="lg"
                        size="small"
                      >
                        Get a Quote
                      </VBtn>
                    </a>
                  </td>
                </tr>
              </tfoot>
            </table>
          </div>
        </ScrollReveal>
      </VContainer>
    </section>

    <!-- FAQ Section -->
    <section class="faq-section">
      <VContainer>
        <ScrollReveal>
          <div class="text-center mb-10">
            <VChip
              color="primary"
              variant="tonal"
              class="mb-4"
            >
              FAQ
            </VChip>
            <h2 class="text-h4 font-weight-bold mb-3">
              Frequently Asked <span class="hero-gradient-text">Questions</span>
            </h2>
            <p
              class="text-body-1 text-medium-emphasis mx-auto"
              style="max-inline-size: 480px;"
            >
              Everything you need to know about our plans and billing.
            </p>
          </div>

          <VRow justify="center">
            <VCol
              cols="12"
              md="8"
              lg="7"
            >
              <div class="faq-list">
                <div
                  v-for="(faq, index) in faqs"
                  :key="faq.question"
                  :class="['faq-item', { 'faq-item--open': openFaq === index }]"
                >
                  <button
                    class="faq-item__trigger"
                    @click="openFaq = openFaq === index ? undefined : index"
                  >
                    <span class="faq-item__question">{{ faq.question }}</span>
                    <VIcon
                      :icon="openFaq === index ? 'tabler-minus' : 'tabler-plus'"
                      size="20"
                      class="faq-item__icon"
                    />
                  </button>
                  <Transition name="faq-expand">
                    <div
                      v-if="openFaq === index"
                      class="faq-item__answer"
                    >
                      <p>{{ faq.answer }}</p>
                    </div>
                  </Transition>
                </div>
              </div>
            </VCol>
          </VRow>
        </ScrollReveal>
      </VContainer>
    </section>

    <!-- Bottom CTA -->
    <section class="bottom-cta">
      <VContainer class="text-center">
        <ScrollReveal>
          <h2 class="text-h4 font-weight-bold mb-3">
            Ready to get started?
          </h2>
          <p
            class="text-body-1 text-medium-emphasis mx-auto mb-8"
            style="max-inline-size: 460px;"
          >
            Deploy in under 60 seconds. No credit card required for your trial.
          </p>
          <div class="d-flex ga-3 justify-center flex-wrap">
            <a
              :href="accountUrl + '/register'"
              class="text-decoration-none"
            >
              <VBtn
                color="primary"
                size="large"
                rounded="lg"
              >
                Start Free Trial
                <VIcon
                  icon="tabler-arrow-right"
                  size="18"
                  end
                />
              </VBtn>
            </a>
            <a
              href="/contact"
              class="text-decoration-none"
            >
              <VBtn
                variant="outlined"
                size="large"
                rounded="lg"
              >
                Talk to Sales
              </VBtn>
            </a>
          </div>
        </ScrollReveal>
      </VContainer>
    </section>
  </div>
</template>

<style lang="scss" scoped>
// ━━━ Hero Section ━━━
.pricing-hero {
  position: relative;
  overflow: hidden;
  background: #0f172a;
  color: #fff;
  padding-block-start: 2rem;

  &__mesh {
    position: absolute;
    inset: 0;
    background:
      radial-gradient(ellipse 50% 80% at 20% 40%, rgba(#1d4ed8, 0.15) 0%, transparent 70%),
      radial-gradient(ellipse 50% 60% at 80% 30%, rgba(#06b6d4, 0.1) 0%, transparent 70%),
      radial-gradient(ellipse 40% 50% at 50% 80%, rgba(#3b82f6, 0.08) 0%, transparent 70%);
    pointer-events: none;
    animation: mesh-drift 20s ease-in-out infinite alternate;
  }

  &__grid {
    position: absolute;
    inset: 0;
    background-image:
      linear-gradient(rgba(255, 255, 255, 0.03) 1px, transparent 1px),
      linear-gradient(90deg, rgba(255, 255, 255, 0.03) 1px, transparent 1px);
    background-size: 60px 60px;
    mask-image: radial-gradient(ellipse 80% 80% at 50% 0%, black 40%, transparent 100%);
    -webkit-mask-image: radial-gradient(ellipse 80% 80% at 50% 0%, black 40%, transparent 100%);
    pointer-events: none;
  }

  &__badge {
    backdrop-filter: blur(8px);
  }

  &__title {
    font-size: clamp(2rem, 5vw, 3.25rem);
    font-weight: 800;
    line-height: 1.15;
    letter-spacing: -0.02em;
    color: #fff;
  }

  &__gradient-text {
    background: linear-gradient(135deg, #3b82f6 0%, #06b6d4 50%, #3b82f6 100%);
    background-size: 200% auto;
    background-clip: text;
    -webkit-background-clip: text;
    -webkit-text-fill-color: transparent;
    animation: gradient-shine 4s ease infinite;
  }

  // Force light text overrides
  :deep(.text-medium-emphasis) {
    color: rgba(255, 255, 255, 0.7) !important;
  }

  :deep(.v-chip) {
    border: 1px solid rgba(255, 255, 255, 0.1);
  }
}

// ━━━ Pricing Content ━━━
.pricing-content {
  position: relative;
  z-index: 1;
  margin-block-start: -2rem;
}

// ━━━ Pricing Mode Toggle ━━━
.pricing-mode-toggle {
  display: inline-flex;
  gap: 2px;
  padding: 4px;
  background: rgba(var(--v-theme-on-surface), 0.04);
  border: 2px solid rgba(var(--v-theme-primary), 0.15);
  border-radius: 14px;

  &__item {
    display: inline-flex;
    align-items: center;
    padding: 10px 22px;
    border: none;
    border-radius: 10px;
    background: transparent;
    color: rgba(var(--v-theme-on-surface), 0.6);
    font-family: 'Plus Jakarta Sans', sans-serif;
    font-size: 0.875rem;
    font-weight: 600;
    cursor: pointer;
    transition: all 250ms ease;
    white-space: nowrap;

    &:hover {
      color: rgba(var(--v-theme-on-surface), 0.9);
      background: rgba(var(--v-theme-on-surface), 0.04);
    }

    &--active {
      background: rgb(var(--v-theme-primary));
      color: #fff;
      box-shadow: 0 4px 12px rgba(#1d4ed8, 0.25);

      &:hover {
        background: rgb(var(--v-theme-primary));
        color: #fff;
      }
    }
  }
}

// ━━━ Service Type Tabs ━━━
.service-tabs {
  display: inline-flex;
  gap: 4px;
  padding: 4px;
  background: rgba(var(--v-theme-on-surface), 0.04);
  border: 1px solid rgba(var(--v-theme-on-surface), 0.08);
  border-radius: 14px;
  flex-wrap: wrap;
  justify-content: center;

  &__item {
    display: inline-flex;
    align-items: center;
    padding: 10px 20px;
    border: none;
    border-radius: 10px;
    background: transparent;
    color: rgba(var(--v-theme-on-surface), 0.6);
    font-family: 'Plus Jakarta Sans', sans-serif;
    font-size: 0.875rem;
    font-weight: 600;
    cursor: pointer;
    transition: all 250ms ease;
    white-space: nowrap;

    &:hover {
      color: rgba(var(--v-theme-on-surface), 0.9);
      background: rgba(var(--v-theme-on-surface), 0.04);
    }

    &--active {
      background: rgb(var(--v-theme-primary));
      color: #fff;
      box-shadow: 0 4px 12px rgba(#1d4ed8, 0.25);

      &:hover {
        background: rgb(var(--v-theme-primary));
        color: #fff;
      }
    }
  }
}

// ━━━ Billing Cycle Toggle ━━━
.billing-toggle {
  display: inline-flex;
  gap: 2px;
  padding: 4px;
  background: rgba(var(--v-theme-on-surface), 0.04);
  border: 1px solid rgba(var(--v-theme-on-surface), 0.08);
  border-radius: 12px;
  flex-wrap: wrap;
  justify-content: center;

  &__item {
    padding: 8px 18px;
    border: none;
    border-radius: 8px;
    background: transparent;
    color: rgba(var(--v-theme-on-surface), 0.6);
    font-family: 'Plus Jakarta Sans', sans-serif;
    font-size: 0.8125rem;
    font-weight: 600;
    cursor: pointer;
    transition: all 200ms ease;
    white-space: nowrap;

    &:hover {
      color: rgba(var(--v-theme-on-surface), 0.9);
    }

    &--active {
      background: rgb(var(--v-theme-surface));
      color: rgba(var(--v-theme-on-surface), 0.9);
      box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1), 0 1px 2px rgba(0, 0, 0, 0.06);
    }
  }
}

// ━━━ Savings Badge ━━━
.savings-badge {
  display: inline-flex;
  align-items: center;
  padding: 6px 14px;
  background: linear-gradient(135deg, rgba(#10b981, 0.1), rgba(#06b6d4, 0.1));
  border: 1px solid rgba(#10b981, 0.2);
  border-radius: 999px;
  color: #10b981;
  font-size: 0.8125rem;
  font-weight: 600;

  &--animate {
    animation: savings-pop 0.5s cubic-bezier(0.175, 0.885, 0.32, 1.275);
  }
}

.savings-pop-enter-active {
  animation: savings-pop 0.4s cubic-bezier(0.175, 0.885, 0.32, 1.275);
}

.savings-pop-leave-active {
  animation: savings-pop 0.2s ease reverse;
}

// ━━━ Plan Cards ━━━
.plan-card {
  position: relative;
  height: 100%;
  border-radius: 16px;
  background: rgb(var(--v-theme-surface));
  border: 1px solid rgba(var(--v-theme-on-surface), 0.08);
  transition: transform 300ms cubic-bezier(0.22, 1, 0.36, 1), box-shadow 300ms ease, border-color 300ms ease;
  overflow: visible;

  &:hover {
    transform: translateY(-6px);
    box-shadow: 0 20px 40px -12px rgba(0, 0, 0, 0.12);
    border-color: rgba(var(--v-theme-on-surface), 0.15);
  }

  &__inner {
    padding: 28px 24px;
    height: 100%;
    display: flex;
    flex-direction: column;
  }

  // Popular plan
  &--popular {
    border-color: rgba(#1d4ed8, 0.3);
    box-shadow: 0 8px 30px -8px rgba(#1d4ed8, 0.15);
    z-index: 2;

    &::before {
      content: '';
      position: absolute;
      inset: -1px;
      border-radius: 16px;
      padding: 1px;
      background: linear-gradient(135deg, #1d4ed8, #06b6d4, #1d4ed8);
      background-size: 300% 300%;
      animation: border-shimmer 6s ease infinite;
      mask: linear-gradient(#fff 0 0) content-box, linear-gradient(#fff 0 0);
      mask-composite: exclude;
      -webkit-mask: linear-gradient(#fff 0 0) content-box, linear-gradient(#fff 0 0);
      -webkit-mask-composite: xor;
      pointer-events: none;
    }

    &:hover {
      transform: translateY(-8px);
      box-shadow: 0 24px 48px -12px rgba(#1d4ed8, 0.2);
    }
  }

  // Best Value
  &--best-value {
    border-color: rgba(#10b981, 0.2);

    &:hover {
      border-color: rgba(#10b981, 0.4);
      box-shadow: 0 20px 40px -12px rgba(#10b981, 0.1);
    }
  }

  // Contact-only plan
  &--contact {
    background: linear-gradient(135deg, rgba(var(--v-theme-surface), 1), rgba(var(--v-theme-primary), 0.03));
  }

  // Popular badge
  &__popular-badge {
    position: absolute;
    top: -12px;
    left: 50%;
    transform: translateX(-50%);
    display: inline-flex;
    align-items: center;
    padding: 5px 16px;
    background: linear-gradient(135deg, #1d4ed8, #3b82f6);
    color: #fff;
    font-size: 0.75rem;
    font-weight: 700;
    letter-spacing: 0.03em;
    border-radius: 999px;
    white-space: nowrap;
    box-shadow: 0 4px 12px rgba(#1d4ed8, 0.3);
    z-index: 3;
  }

  // Best value badge
  &__best-value-badge {
    position: absolute;
    top: -12px;
    left: 50%;
    transform: translateX(-50%);
    display: inline-flex;
    align-items: center;
    padding: 5px 16px;
    background: linear-gradient(135deg, #10b981, #06b6d4);
    color: #fff;
    font-size: 0.75rem;
    font-weight: 700;
    letter-spacing: 0.03em;
    border-radius: 999px;
    white-space: nowrap;
    box-shadow: 0 4px 12px rgba(#10b981, 0.3);
    z-index: 3;
  }

  // Header
  &__header {
    text-align: center;
    margin-block-end: 20px;
  }

  &__name {
    font-size: 1.25rem;
    font-weight: 700;
    margin-block-end: 4px;
    letter-spacing: -0.01em;
  }

  &__description {
    font-size: 0.875rem;
    color: rgba(var(--v-theme-on-surface), 0.55);
    margin: 0;
    line-height: 1.5;
  }

  // Price block
  &__price-block {
    text-align: center;
    margin-block-end: 24px;
  }

  &__price {
    display: flex;
    align-items: baseline;
    justify-content: center;
    gap: 2px;
  }

  &__currency {
    font-size: 1.25rem;
    font-weight: 600;
    color: rgba(var(--v-theme-on-surface), 0.5);
    align-self: flex-start;
    margin-top: 8px;
  }

  &__amount {
    font-size: 3rem;
    font-weight: 800;
    line-height: 1;
    letter-spacing: -0.03em;
    color: rgba(var(--v-theme-on-surface), 0.9);
  }

  &__period {
    font-size: 0.875rem;
    font-weight: 500;
    color: rgba(var(--v-theme-on-surface), 0.45);
    align-self: flex-end;
    margin-bottom: 6px;
  }

  &__equivalent {
    font-size: 0.8125rem;
    color: rgba(var(--v-theme-on-surface), 0.45);
    margin-top: 4px;
  }

  &__custom-price {
    font-size: 1.75rem;
    font-weight: 700;
    background: linear-gradient(135deg, #1d4ed8, #06b6d4);
    background-clip: text;
    -webkit-background-clip: text;
    -webkit-text-fill-color: transparent;
    padding-block: 10px;
  }

  // CTA
  &__cta {
    margin-block-end: 24px;
  }

  &__cta-btn {
    border-color: rgba(var(--v-theme-on-surface), 0.15) !important;
    transition: all 250ms ease !important;

    &:hover {
      border-color: rgb(var(--v-theme-primary)) !important;
      background: rgba(var(--v-theme-primary), 0.04) !important;
    }
  }

  &__cta-btn--popular {
    box-shadow: 0 4px 14px rgba(#1d4ed8, 0.25) !important;
  }

  &__cta-btn--contact {
    border-color: rgba(var(--v-theme-primary), 0.3) !important;
    color: rgb(var(--v-theme-primary)) !important;
  }

  // Divider
  &__divider {
    height: 1px;
    background: rgba(var(--v-theme-on-surface), 0.08);
    margin-block-end: 20px;
  }

  // Features
  &__features {
    list-style: none;
    padding: 0;
    margin: 0;
    flex: 1;
  }

  &__feature {
    display: flex;
    align-items: center;
    gap: 10px;
    padding-block: 7px;
    font-size: 0.875rem;
  }

  &__feature-icon {
    flex-shrink: 0;
  }

  &__feature-label {
    color: rgba(var(--v-theme-on-surface), 0.55);
    min-inline-size: 0;
  }

  &__feature-value {
    margin-inline-start: auto;
    font-weight: 600;
    color: rgba(var(--v-theme-on-surface), 0.85);
    white-space: nowrap;
  }
}

// ━━━ Guarantee Banner ━━━
.guarantee-banner {
  border-radius: 14px;
  background: linear-gradient(135deg, rgba(#1d4ed8, 0.04), rgba(#06b6d4, 0.04));
  border: 1px solid rgba(#1d4ed8, 0.1);
  padding: 20px 28px;

  &__inner {
    display: flex;
    align-items: center;
    gap: 16px;
    flex-wrap: wrap;
  }

  &__icon {
    display: flex;
    align-items: center;
    justify-content: center;
    width: 44px;
    height: 44px;
    border-radius: 12px;
    background: rgba(#1d4ed8, 0.08);
    color: #1d4ed8;
    flex-shrink: 0;
  }

  &__title {
    display: block;
    font-weight: 700;
    font-size: 0.9375rem;
    margin-block-end: 2px;
  }

  &__subtitle {
    display: block;
    font-size: 0.8125rem;
    color: rgba(var(--v-theme-on-surface), 0.55);
  }
}

// ━━━ Feature Comparison ━━━
.comparison-section {
  padding-block: 80px;
  background: rgba(var(--v-theme-on-surface), 0.02);
}

.comparison-table-wrapper {
  overflow-x: auto;
  border-radius: 16px;
  border: 1px solid rgba(var(--v-theme-on-surface), 0.08);
  background: rgb(var(--v-theme-surface));
}

.comparison-table {
  width: 100%;
  border-collapse: collapse;
  font-size: 0.875rem;

  thead {
    position: sticky;
    top: 0;
    z-index: 2;
    background: rgb(var(--v-theme-surface));
  }

  th,
  td {
    padding: 14px 20px;
    text-align: center;
    border-bottom: 1px solid rgba(var(--v-theme-on-surface), 0.06);
  }

  &__feature-header {
    text-align: start !important;
    font-weight: 700;
    font-size: 0.8125rem;
    text-transform: uppercase;
    letter-spacing: 0.05em;
    color: rgba(var(--v-theme-on-surface), 0.45);
    min-inline-size: 140px;
  }

  &__plan-header {
    padding-block: 20px !important;
    vertical-align: bottom;

    &--popular {
      background: rgba(#1d4ed8, 0.03);
    }
  }

  &__plan-name {
    font-weight: 700;
    font-size: 0.9375rem;
    margin-block-end: 4px;
    display: inline-flex;
    align-items: center;
  }

  &__plan-price {
    font-size: 0.8125rem;
    color: rgba(var(--v-theme-on-surface), 0.5);
    font-weight: 500;
  }

  &__row {
    transition: background 150ms ease;

    &:hover {
      background: rgba(var(--v-theme-on-surface), 0.02);
    }

    &:nth-child(even) {
      background: rgba(var(--v-theme-on-surface), 0.015);

      &:hover {
        background: rgba(var(--v-theme-on-surface), 0.035);
      }
    }
  }

  &__feature-name {
    text-align: start !important;
    font-weight: 500;
    color: rgba(var(--v-theme-on-surface), 0.75);
  }

  &__cell {
    &--popular {
      background: rgba(#1d4ed8, 0.02);
    }
  }

  &__value {
    font-weight: 600;
    color: rgba(var(--v-theme-on-surface), 0.85);
  }

  &__footer-cell {
    padding-block: 20px !important;
    border-bottom: none;
  }

  tfoot td {
    border-bottom: none;
  }
}

// ━━━ FAQ Section ━━━
.faq-section {
  padding-block: 80px;
}

.faq-list {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.faq-item {
  border-radius: 12px;
  border: 1px solid rgba(var(--v-theme-on-surface), 0.08);
  background: rgb(var(--v-theme-surface));
  overflow: hidden;
  transition: border-color 250ms ease, box-shadow 250ms ease;

  &:hover {
    border-color: rgba(var(--v-theme-on-surface), 0.15);
  }

  &--open {
    border-color: rgba(#1d4ed8, 0.15);
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.04);
  }

  &__trigger {
    display: flex;
    align-items: center;
    justify-content: space-between;
    width: 100%;
    padding: 18px 20px;
    border: none;
    background: transparent;
    cursor: pointer;
    text-align: start;
    gap: 16px;
    font-family: 'Plus Jakarta Sans', sans-serif;
  }

  &__question {
    font-size: 0.9375rem;
    font-weight: 600;
    color: rgba(var(--v-theme-on-surface), 0.85);
  }

  &__icon {
    flex-shrink: 0;
    color: rgba(var(--v-theme-on-surface), 0.4);
    transition: transform 200ms ease;
  }

  &__answer {
    padding: 0 20px 18px;

    p {
      margin: 0;
      font-size: 0.875rem;
      line-height: 1.7;
      color: rgba(var(--v-theme-on-surface), 0.6);
    }
  }
}

// FAQ expand transition
.faq-expand-enter-active {
  animation: faq-slide-down 250ms ease;
}

.faq-expand-leave-active {
  animation: faq-slide-down 200ms ease reverse;
}

// ━━━ Bottom CTA ━━━
.bottom-cta {
  padding-block: 80px;
  background: linear-gradient(180deg, transparent, rgba(var(--v-theme-primary), 0.03));
}

// ━━━ Keyframes ━━━
@keyframes mesh-drift {
  0% {
    opacity: 1;
    transform: scale(1);
  }

  100% {
    opacity: 0.8;
    transform: scale(1.05);
  }
}

@keyframes gradient-shine {
  0% {
    background-position: 0% center;
  }

  50% {
    background-position: 100% center;
  }

  100% {
    background-position: 0% center;
  }
}

@keyframes border-shimmer {
  0% {
    background-position: 0% 50%;
  }

  50% {
    background-position: 100% 50%;
  }

  100% {
    background-position: 0% 50%;
  }
}

@keyframes savings-pop {
  0% {
    transform: scale(0.8);
    opacity: 0;
  }

  50% {
    transform: scale(1.05);
  }

  100% {
    transform: scale(1);
    opacity: 1;
  }
}

@keyframes faq-slide-down {
  from {
    max-height: 0;
    opacity: 0;
  }

  to {
    max-height: 200px;
    opacity: 1;
  }
}

// ━━━ Accessibility ━━━
@media (prefers-reduced-motion: reduce) {
  .pricing-hero__mesh {
    animation: none;
  }

  .pricing-hero__gradient-text {
    animation: none;
  }

  .plan-card--popular::before {
    animation: none;
  }

  .plan-card {
    transition: none;

    &:hover {
      transform: none;
    }
  }

  .savings-badge--animate {
    animation: none;
  }

  .faq-expand-enter-active,
  .faq-expand-leave-active {
    animation: none;
  }
}

// ━━━ Responsive ━━━
@media (max-width: 600px) {
  .pricing-hero {
    &__title {
      font-size: 1.75rem;
    }

    :deep(.v-container) {
      padding-inline: 1.25rem !important;
    }
  }

  .pricing-mode-toggle {
    flex-wrap: wrap;
    justify-content: center;

    &__item {
      padding: 8px 16px;
      font-size: 0.8125rem;
    }
  }

  .service-tabs {
    gap: 2px;
    padding: 3px;
    max-width: 100%;
    flex-wrap: wrap;
    justify-content: center;
    overflow-x: visible;

    &__item {
      padding: 8px 14px;
      font-size: 0.8125rem;
    }
  }

  .billing-toggle {
    gap: 1px;
    padding: 3px;
    max-width: 100%;
    overflow-x: auto;
    -webkit-overflow-scrolling: touch;
    scrollbar-width: none;

    &::-webkit-scrollbar {
      display: none;
    }

    &__item {
      padding: 7px 12px;
      font-size: 0.75rem;
    }
  }

  .plan-card {
    &__amount {
      font-size: 2.5rem;
    }

    &__inner {
      padding: 24px 20px;
    }
  }

  .comparison-table {
    font-size: 0.8125rem;

    th,
    td {
      padding: 10px 12px;
    }
  }

  .faq-item {
    &__trigger {
      padding: 14px 16px;
    }

    &__answer {
      padding: 0 16px 14px;
    }
  }
}

@media (min-width: 600px) and (max-width: 960px) {
  .pricing-content {
    :deep(.v-container) {
      padding-inline: 2rem !important;
    }
  }
}
</style>
