/**
 * Subscriptions Customization Tab
 * Quick Start presets + always-visible design controls + live preview
 */

import { useState } from "react"
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card"
import { Label } from "@/components/ui/label"
import { Input } from "@/components/ui/input"
import { GlobalColorPicker } from "@/components/ui/global-color-picker"
import { GlobalTypographyPicker } from "@/components/ui/global-typography-picker"
import { Button } from "@/components/ui/button"
import { Switch } from "@/components/ui/switch"
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/components/ui/select"
import {
  Collapsible,
  CollapsibleContent,
  CollapsibleTrigger,
} from "@/components/ui/collapsible"
import { LivePreview } from "@/components/ui/live-preview"
import { ProIndicator } from "@/components/pro/pro-indicator"
import {
  ChevronDown,
  Palette,
  RotateCcw,
  CreditCard,
  ShoppingCart,
  ShoppingBag,
  Type,
  BoxSelect,
  Square,
  LayoutPanelTop,
  AlignLeft,
  AlignCenter,
  AlignRight,
  Columns2,
  Rows3,
  Maximize2,
  Minus,
  Plus,
  Eye,
  EyeOff,
  TextCursorInput,
} from "lucide-react"

// ─── Customization Interface ──────────────────────────────────────────────────

export interface SubscriptionCustomization {
  // Layout
  layout: 'vertical' | 'horizontal'
  priceAlignment: 'left' | 'center' | 'right'

  // Button styles
  buttonBgColor: string
  buttonTextColor: string
  buttonBorderRadius: number
  buttonFontSize: number
  buttonFontWeight: string
  buttonPadding: number
  buttonStyle: 'filled' | 'outline'
  buttonWidth: 'auto' | 'full'

  // Price display
  priceColor: string
  priceFontSize: number
  periodColor: string
  periodFontSize: number

  // Sign-up fee and trial
  signUpFeeColor: string
  signUpFeeFontSize: number
  trialColor: string
  trialFontSize: number
  showSignUpFee: boolean
  showTrialText: boolean

  // Text labels
  signUpFeeLabel: string
  trialLabel: string
  periodSeparator: string

  // Typography
  fontFamily: string

  // Container
  containerBgColor: string
  containerBorderColor: string
  containerBorderRadius: number
  containerPadding: number
}

export const defaultSubscriptionCustomization: SubscriptionCustomization = {
  layout: 'vertical',
  priceAlignment: 'left',
  buttonBgColor: '#002269',
  buttonTextColor: '#ffffff',
  buttonBorderRadius: 8,
  buttonFontSize: 14,
  buttonFontWeight: '600',
  buttonPadding: 12,
  buttonStyle: 'filled',
  buttonWidth: 'full',
  priceColor: '#111827',
  priceFontSize: 24,
  periodColor: '#6b7280',
  periodFontSize: 14,
  signUpFeeColor: '#6b7280',
  signUpFeeFontSize: 14,
  trialColor: '#002269',
  trialFontSize: 14,
  showSignUpFee: true,
  showTrialText: true,
  signUpFeeLabel: 'and a %s sign-up fee',
  trialLabel: 'with a %1$d %2$s free trial',
  periodSeparator: '/',
  fontFamily: '',
  containerBgColor: '#ffffff',
  containerBorderColor: '#e5e7eb',
  containerBorderRadius: 12,
  containerPadding: 24,
}

// ─── Quick Start Presets ──────────────────────────────────────────────────────

interface Preset {
  id: string
  name: string
  customization: SubscriptionCustomization
}

const PRESETS: Preset[] = [
  {
    id: 'brand',
    name: 'Brand',
    customization: {
      layout: 'vertical',
      priceAlignment: 'left',
      buttonBgColor: '#002269',
      buttonTextColor: '#ffffff',
      buttonBorderRadius: 8,
      buttonFontSize: 14,
      buttonFontWeight: '600',
      buttonPadding: 12,
      buttonStyle: 'filled',
      buttonWidth: 'full',
      priceColor: '#111827',
      priceFontSize: 24,
      periodColor: '#6b7280',
      periodFontSize: 14,
      signUpFeeColor: '#6b7280',
      signUpFeeFontSize: 14,
      trialColor: '#002269',
      trialFontSize: 14,
      showSignUpFee: true,
      showTrialText: true,
      signUpFeeLabel: 'and a %s sign-up fee',
      trialLabel: 'with a %1$d %2$s free trial',
      periodSeparator: '/',
      fontFamily: '',
      containerBgColor: '#ffffff',
      containerBorderColor: '#e5e7eb',
      containerBorderRadius: 12,
      containerPadding: 24,
    },
  },
  {
    id: 'dark',
    name: 'Dark',
    customization: {
      layout: 'vertical',
      priceAlignment: 'left',
      buttonBgColor: '#18181b',
      buttonTextColor: '#ffffff',
      buttonBorderRadius: 4,
      buttonFontSize: 13,
      buttonFontWeight: '500',
      buttonPadding: 10,
      buttonStyle: 'filled',
      buttonWidth: 'auto',
      priceColor: '#18181b',
      priceFontSize: 22,
      periodColor: '#71717a',
      periodFontSize: 13,
      signUpFeeColor: '#71717a',
      signUpFeeFontSize: 13,
      trialColor: '#71717a',
      trialFontSize: 13,
      showSignUpFee: true,
      showTrialText: true,
      signUpFeeLabel: 'and a %s sign-up fee',
      trialLabel: 'with a %1$d %2$s free trial',
      periodSeparator: '/',
      fontFamily: '',
      containerBgColor: '#fafafa',
      containerBorderColor: 'transparent',
      containerBorderRadius: 8,
      containerPadding: 20,
    },
  },
  {
    id: 'bold',
    name: 'Bold',
    customization: {
      layout: 'horizontal',
      priceAlignment: 'left',
      buttonBgColor: '#dc2626',
      buttonTextColor: '#ffffff',
      buttonBorderRadius: 24,
      buttonFontSize: 15,
      buttonFontWeight: '700',
      buttonPadding: 14,
      buttonStyle: 'filled',
      buttonWidth: 'auto',
      priceColor: '#dc2626',
      priceFontSize: 28,
      periodColor: '#6b7280',
      periodFontSize: 14,
      signUpFeeColor: '#dc2626',
      signUpFeeFontSize: 14,
      trialColor: '#16a34a',
      trialFontSize: 14,
      showSignUpFee: true,
      showTrialText: true,
      signUpFeeLabel: 'and a %s sign-up fee',
      trialLabel: 'with a %1$d %2$s free trial',
      periodSeparator: '/',
      fontFamily: '',
      containerBgColor: '#ffffff',
      containerBorderColor: '#fecaca',
      containerBorderRadius: 16,
      containerPadding: 28,
    },
  },
]

// ─── Props ────────────────────────────────────────────────────────────────────

interface CustomizationTabProps {
  settings: {
    button_text: string
    add_to_cart_text: string
    buy_now_subscribe_label: string
    buy_now_one_time_label: string
    buy_now_toggle_style: string
    buy_now_normal_bg: string
    buy_now_normal_text: string
    buy_now_normal_border: string
    buy_now_hover_bg: string
    buy_now_hover_text: string
    buy_now_hover_border: string
    buy_now_active_bg: string
    buy_now_active_text: string
    buy_now_active_border: string
    buy_now_border_radius: number
  }
  customization: SubscriptionCustomization
  onSettingChange: (key: string, value: any) => void
  onCustomizationChange: <K extends keyof SubscriptionCustomization>(key: K, value: SubscriptionCustomization[K]) => void
  resetCustomization: () => void
  isPro: boolean
}

// ─── Component ────────────────────────────────────────────────────────────────

/** Compact number input with +/- buttons — replaces Slider */
function NumberStepper({
  label,
  value,
  onChange,
  min,
  max,
  step = 1,
  unit = 'px',
}: {
  label: string
  value: number
  onChange: (v: number) => void
  min: number
  max: number
  step?: number
  unit?: string
}) {
  const clamp = (v: number) => Math.min(max, Math.max(min, v))
  return (
    <div className="flex items-center justify-between gap-2">
      <Label className="text-sm whitespace-nowrap">{label}</Label>
      <div className="inline-flex items-center rounded-md border bg-background">
        <button
          type="button"
          onClick={() => onChange(clamp(value - step))}
          disabled={value <= min}
          className="flex items-center justify-center h-8 w-8 text-muted-foreground hover:text-foreground disabled:opacity-30 transition-colors cursor-pointer"
        >
          <Minus className="h-3 w-3" />
        </button>
        <input
          type="text"
          value={`${value}${unit}`}
          onChange={(e) => {
            const parsed = parseInt(e.target.value, 10)
            if (!isNaN(parsed)) onChange(clamp(parsed))
          }}
          className="h-8 w-14 text-center text-sm border-x bg-transparent outline-none"
        />
        <button
          type="button"
          onClick={() => onChange(clamp(value + step))}
          disabled={value >= max}
          className="flex items-center justify-center h-8 w-8 text-muted-foreground hover:text-foreground disabled:opacity-30 transition-colors cursor-pointer"
        >
          <Plus className="h-3 w-3" />
        </button>
      </div>
    </div>
  )
}

export function CustomizationTab({
  settings,
  customization,
  onSettingChange,
  onCustomizationChange,
  resetCustomization,
  isPro,
}: CustomizationTabProps) {
  const [expandedSections, setExpandedSections] = useState<Record<string, boolean>>({ colors: true })
  const [buyNowColorState, setBuyNowColorState] = useState<'normal' | 'hover' | 'active'>('normal')

  const toggleSection = (section: string) => {
    setExpandedSections(prev => ({ ...prev, [section]: !prev[section] }))
  }

  const applyPreset = (preset: Preset) => {
    Object.entries(preset.customization).forEach(([key, value]) => {
      onCustomizationChange(key as keyof SubscriptionCustomization, value as any)
    })
  }

  // ─── Helpers ────────────────────────────────────────────────────────────────

  /** Format the sign-up fee label for preview */
  const formatSignUpFee = (amount: string) => {
    return customization.signUpFeeLabel.replace('%s', amount)
  }

  /** Format the trial label for preview */
  const formatTrialLabel = (length: number, period: string) => {
    return customization.trialLabel
      .replace('%1$d', String(length))
      .replace('%2$s', period)
  }

  // ─── Segmented Control ──────────────────────────────────────────────────────

  const SegmentedControl = ({
    value,
    options,
    onChange,
  }: {
    value: string
    options: { value: string; label: string; icon?: React.ReactNode }[]
    onChange: (value: string) => void
  }) => (
    <div className="flex gap-0.5 rounded-lg border bg-muted/40 p-0.5">
      {options.map((opt) => (
        <button
          key={opt.value}
          type="button"
          onClick={() => onChange(opt.value)}
          className={`flex items-center justify-center gap-1.5 rounded-md px-3 py-1.5 text-xs font-medium transition-all ${
            value === opt.value
              ? 'bg-background text-foreground shadow-sm'
              : 'text-muted-foreground hover:text-foreground'
          }`}
        >
          {opt.icon}
          {opt.label}
        </button>
      ))}
    </div>
  )

  // ─── Live Preview ───────────────────────────────────────────────────────────

  const renderLivePreview = () => {
    const isHorizontal = customization.layout === 'horizontal'
    const isOutline = customization.buttonStyle === 'outline'
    const isFullWidth = customization.buttonWidth === 'full'
    const alignment = customization.priceAlignment

    const alignClass =
      alignment === 'center' ? 'text-center items-center' :
      alignment === 'right' ? 'text-right items-end' :
      'text-left items-start'

    const buttonStyles: React.CSSProperties = {
      backgroundColor: isOutline ? 'transparent' : customization.buttonBgColor,
      color: isOutline ? customization.buttonBgColor : customization.buttonTextColor,
      borderRadius: `${customization.buttonBorderRadius}px`,
      fontSize: `${customization.buttonFontSize * 0.85}px`,
      fontWeight: customization.buttonFontWeight,
      padding: `${customization.buttonPadding * 0.75}px ${customization.buttonPadding * 1.5}px`,
      border: isOutline ? `2px solid ${customization.buttonBgColor}` : 'none',
      width: isFullWidth && !isHorizontal ? '100%' : 'auto',
    }

    return (
      <div className="p-4">
        <div
          className="flex gap-4 items-start transition-all"
          style={{ transformOrigin: 'top center' }}
        >
          {/* Product Card Preview */}
          <div
            className="flex-1 min-w-0 transition-all duration-200"
            style={{
              background: customization.containerBgColor,
              borderColor: customization.containerBorderColor,
              borderWidth: customization.containerBorderColor === 'transparent' ? '0' : '1px',
              borderStyle: 'solid',
              borderRadius: `${customization.containerBorderRadius}px`,
              padding: `${customization.containerPadding * 0.75}px`,
              boxShadow: '0 1px 3px 0 rgb(0 0 0 / 0.1)',
            }}
          >
            {/* Product Title */}
            <h3 className={`font-semibold text-sm mb-1.5 text-gray-900 ${alignment === 'center' ? 'text-center' : alignment === 'right' ? 'text-right' : ''}`}>
              Premium Plan
            </h3>

            {/* Content Area — vertical or horizontal layout */}
            <div className={isHorizontal
              ? 'flex items-center justify-between gap-3'
              : `flex flex-col ${alignClass}`
            }>
              {/* Price & Details */}
              <div className={`flex flex-col ${isHorizontal ? '' : alignClass}`}>
                {/* Price Display */}
                <div className={`flex items-baseline gap-1 mb-1 ${isHorizontal ? '' : alignment === 'center' ? 'justify-center' : alignment === 'right' ? 'justify-end' : ''}`}>
                  <span
                    className="font-bold"
                    style={{
                      color: customization.priceColor,
                      fontSize: `${customization.priceFontSize * 0.85}px`,
                    }}
                  >
                    $29.99
                  </span>
                  <span
                    style={{
                      color: customization.periodColor,
                      fontSize: `${customization.periodFontSize * 0.85}px`,
                    }}
                  >
                    {customization.periodSeparator} month
                  </span>
                </div>

                {/* Sign-up Fee */}
                {customization.showSignUpFee && (
                  <p
                    className="mb-0.5"
                    style={{
                      color: customization.signUpFeeColor,
                      fontSize: `${customization.signUpFeeFontSize * 0.85}px`,
                    }}
                  >
                    {formatSignUpFee('$50')}
                  </p>
                )}

                {/* Free Trial */}
                {customization.showTrialText && (
                  <p
                    className={isHorizontal ? '' : 'mb-3'}
                    style={{
                      color: customization.trialColor,
                      fontSize: `${customization.trialFontSize * 0.85}px`,
                    }}
                  >
                    {formatTrialLabel(7, 'day')}
                  </p>
                )}
              </div>

              {/* Subscribe Button */}
              <button
                className="flex items-center justify-center gap-1.5 transition-all duration-200 hover:opacity-90 shrink-0"
                style={buttonStyles}
              >
                <CreditCard className="w-3.5 h-3.5" />
                {settings.button_text || 'Sign Up Now'}
              </button>
            </div>
          </div>

          {/* Right side — Shop Page Button & Buy Now Toggle */}
          <div className="flex flex-col gap-4 shrink-0">
            {/* Shop Page Button Preview */}
            <div>
              <p className="text-[10px] text-muted-foreground mb-2">Shop Page Button</p>
              <button
                className="flex items-center justify-center gap-1.5 transition-all duration-200 hover:opacity-90"
                style={{
                  ...buttonStyles,
                  width: 'auto',
                }}
              >
                <ShoppingCart className="w-3.5 h-3.5" />
                {settings.add_to_cart_text || 'Subscribe'}
              </button>
            </div>

            {/* Buy Now Toggle Preview (Pro only) */}
            {isPro && (
              <div>
                <p className="text-[10px] text-muted-foreground mb-2">Buy Now Toggle</p>
              <div className="flex overflow-hidden" style={{ border: `1px solid ${settings.buy_now_active_border}`, borderRadius: `${settings.buy_now_border_radius}px` }}>
                <div
                  className="flex-1 text-center py-2 px-3 text-xs font-semibold"
                  style={{
                    backgroundColor: settings.buy_now_active_bg,
                    color: settings.buy_now_active_text,
                  }}
                >
                  {settings.buy_now_subscribe_label || 'Subscribe & Save'}
                </div>
                <div
                  className="flex-1 text-center py-2 px-3 text-xs font-semibold"
                  style={{
                    backgroundColor: settings.buy_now_normal_bg,
                    color: settings.buy_now_normal_text,
                  }}
                >
                  {settings.buy_now_one_time_label || 'Buy Once'}
                </div>
              </div>
            </div>
          )}
        </div>
      </div>
      </div>
    )
  }

  // ─── JSX ────────────────────────────────────────────────────────────────────

  return (
    <div className="grid gap-6 lg:grid-cols-2">
      {/* Left Column — Controls */}
      <div className="space-y-6">
        {/* Customize Design Card — always visible */}
        <Card>
          <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
            <div>
              <CardTitle className="flex items-center gap-2">
                <Palette className="h-5 w-5" />
                Customize Design
              </CardTitle>
              <CardDescription>
                {isPro
                  ? 'Full control over layout, colors, typography, and more'
                  : 'Customize the colors of your subscription display'}
              </CardDescription>
            </div>
            <Button
              variant="ghost"
              size="sm"
              onClick={resetCustomization}
              className="h-8 px-2 text-muted-foreground hover:text-foreground"
            >
              <RotateCcw className="h-4 w-4 mr-1" />
              Reset
            </Button>
          </CardHeader>
          <CardContent className="space-y-0">
            {/* Quick Start Presets — always visible */}
            <div className="pb-4">
              <Label className="text-xs text-muted-foreground mb-2 block">Quick Start</Label>
              <div className="flex gap-2">
                {PRESETS.map((preset) => (
                  <Button
                    key={preset.id}
                    variant="outline"
                    size="sm"
                    onClick={() => applyPreset(preset)}
                    className="h-8 text-xs"
                  >
                    <span
                      className="w-3 h-3 rounded-full mr-1.5 border border-black/10 shrink-0"
                      style={{ backgroundColor: preset.customization.buttonBgColor }}
                    />
                    {preset.name}
                  </Button>
                ))}
              </div>
            </div>

            {/* ── Colors — FREE ────────────────────────────────────────────── */}
            <Collapsible open={expandedSections.colors} onOpenChange={() => toggleSection('colors')}>
              <CollapsibleTrigger className="flex w-full items-center justify-between py-3 text-sm font-medium hover:text-primary border-t">
                <div className="flex items-center gap-2">
                  <Palette className="h-4 w-4" />
                  <span>Colors</span>
                </div>
                <ChevronDown className={`h-4 w-4 transition-transform duration-200 ${expandedSections.colors ? 'rotate-180' : ''}`} />
              </CollapsibleTrigger>
              <CollapsibleContent className="space-y-4 pb-4">
                {/* Button Colors */}
                <Label className="text-sm text-muted-foreground">Button Colors</Label>
                <div className="grid grid-cols-2 gap-4">
                  <GlobalColorPicker
                    label="Background"
                    value={customization.buttonBgColor}
                    onChange={(v) => onCustomizationChange('buttonBgColor', v)}
                    globalTokenId="primary"
                  />
                  <GlobalColorPicker
                    label="Text"
                    value={customization.buttonTextColor}
                    onChange={(v) => onCustomizationChange('buttonTextColor', v)}
                  />
                </div>

                {/* Price & Text Colors */}
                <Label className="text-sm text-muted-foreground">Price & Text Colors</Label>
                <div className="grid grid-cols-2 gap-4">
                  <GlobalColorPicker
                    label="Price"
                    value={customization.priceColor}
                    onChange={(v) => onCustomizationChange('priceColor', v)}
                    globalTokenId="text"
                  />
                  <GlobalColorPicker
                    label="Period"
                    value={customization.periodColor}
                    onChange={(v) => onCustomizationChange('periodColor', v)}
                    globalTokenId="secondary"
                  />
                  <GlobalColorPicker
                    label="Sign-up Fee"
                    value={customization.signUpFeeColor}
                    onChange={(v) => onCustomizationChange('signUpFeeColor', v)}
                  />
                  <GlobalColorPicker
                    label="Trial Text"
                    value={customization.trialColor}
                    onChange={(v) => onCustomizationChange('trialColor', v)}
                  />
                </div>

                {/* Container Colors */}
                <Label className="text-sm text-muted-foreground">Container Colors</Label>
                <div className="grid grid-cols-2 gap-4">
                  <GlobalColorPicker
                    label="Background"
                    value={customization.containerBgColor}
                    onChange={(v) => onCustomizationChange('containerBgColor', v)}
                    globalTokenId="background"
                  />
                  <GlobalColorPicker
                    label="Border"
                    value={customization.containerBorderColor}
                    onChange={(v) => onCustomizationChange('containerBorderColor', v)}
                    globalTokenId="border"
                  />
                </div>
              </CollapsibleContent>
            </Collapsible>

            {/* Upgrade nudge for Free users */}
            {!isPro && (
              <p className="text-sm text-muted-foreground py-4 border-t">
                For full customization control including layout, typography, spacing,
                and more, upgrade to Swift Commerce Pro.
              </p>
            )}

            {/* ── Layout & Display — PRO ───────────────────────────────────── */}
            {isPro && (
              <Collapsible open={expandedSections.layout} onOpenChange={() => toggleSection('layout')}>
                <CollapsibleTrigger className="flex w-full items-center justify-between py-3 text-sm font-medium hover:text-primary border-t">
                  <div className="flex items-center gap-2">
                    <LayoutPanelTop className="h-4 w-4" />
                    <span>Layout & Display</span>
                  </div>
                  <div className="flex items-center gap-2">
                    <ProIndicator size="sm" />
                    <ChevronDown className={`h-4 w-4 transition-transform duration-200 ${expandedSections.layout ? 'rotate-180' : ''}`} />
                  </div>
                </CollapsibleTrigger>
                <CollapsibleContent className="space-y-4 pb-4">
                  {/* Layout Direction */}
                  <div className="space-y-2">
                    <Label className="text-sm">Layout</Label>
                    <SegmentedControl
                      value={customization.layout}
                      options={[
                        { value: 'vertical', label: 'Vertical', icon: <Rows3 className="h-3.5 w-3.5" /> },
                        { value: 'horizontal', label: 'Horizontal', icon: <Columns2 className="h-3.5 w-3.5" /> },
                      ]}
                      onChange={(v) => onCustomizationChange('layout', v as 'vertical' | 'horizontal')}
                    />
                    <p className="text-xs text-muted-foreground">
                      Vertical stacks price above button. Horizontal places them side by side.
                    </p>
                  </div>

                  {/* Button Width */}
                  <div className="space-y-2">
                    <Label className="text-sm">Button Width</Label>
                    <SegmentedControl
                      value={customization.buttonWidth}
                      options={[
                        { value: 'auto', label: 'Auto', icon: <Minus className="h-3.5 w-3.5" /> },
                        { value: 'full', label: 'Full Width', icon: <Maximize2 className="h-3.5 w-3.5" /> },
                      ]}
                      onChange={(v) => onCustomizationChange('buttonWidth', v as 'auto' | 'full')}
                    />
                  </div>

                  {/* Price Alignment */}
                  <div className="space-y-2">
                    <Label className="text-sm">Price Alignment</Label>
                    <SegmentedControl
                      value={customization.priceAlignment}
                      options={[
                        { value: 'left', label: 'Left', icon: <AlignLeft className="h-3.5 w-3.5" /> },
                        { value: 'center', label: 'Center', icon: <AlignCenter className="h-3.5 w-3.5" /> },
                        { value: 'right', label: 'Right', icon: <AlignRight className="h-3.5 w-3.5" /> },
                      ]}
                      onChange={(v) => onCustomizationChange('priceAlignment', v as 'left' | 'center' | 'right')}
                    />
                  </div>

                  {/* Show / Hide Toggles */}
                  <div className="space-y-3 pt-2">
                    <Label className="text-sm text-muted-foreground">Visibility</Label>
                    <div className="flex items-center justify-between">
                      <div className="flex items-center gap-2">
                        {customization.showSignUpFee ? <Eye className="h-3.5 w-3.5 text-muted-foreground" /> : <EyeOff className="h-3.5 w-3.5 text-muted-foreground" />}
                        <Label className="text-sm font-normal">Show sign-up fee</Label>
                      </div>
                      <Switch
                        checked={customization.showSignUpFee}
                        onCheckedChange={(v) => onCustomizationChange('showSignUpFee', v)}
                      />
                    </div>
                    <div className="flex items-center justify-between">
                      <div className="flex items-center gap-2">
                        {customization.showTrialText ? <Eye className="h-3.5 w-3.5 text-muted-foreground" /> : <EyeOff className="h-3.5 w-3.5 text-muted-foreground" />}
                        <Label className="text-sm font-normal">Show free trial text</Label>
                      </div>
                      <Switch
                        checked={customization.showTrialText}
                        onCheckedChange={(v) => onCustomizationChange('showTrialText', v)}
                      />
                    </div>
                  </div>
                </CollapsibleContent>
              </Collapsible>
            )}

            {/* ── Button Styling — PRO ─────────────────────────────────────── */}
            {isPro && (
              <Collapsible open={expandedSections.buttonStyling} onOpenChange={() => toggleSection('buttonStyling')}>
                <CollapsibleTrigger className="flex w-full items-center justify-between py-3 text-sm font-medium hover:text-primary border-t">
                  <div className="flex items-center gap-2">
                    <Square className="h-4 w-4" />
                    <span>Button Styling</span>
                  </div>
                  <div className="flex items-center gap-2">
                    <ProIndicator size="sm" />
                    <ChevronDown className={`h-4 w-4 transition-transform duration-200 ${expandedSections.buttonStyling ? 'rotate-180' : ''}`} />
                  </div>
                </CollapsibleTrigger>
                <CollapsibleContent className="space-y-4 pb-4">
                  {/* Button Style */}
                  <div className="space-y-2">
                    <Label className="text-sm">Style</Label>
                    <SegmentedControl
                      value={customization.buttonStyle}
                      options={[
                        { value: 'filled', label: 'Filled' },
                        { value: 'outline', label: 'Outline' },
                      ]}
                      onChange={(v) => onCustomizationChange('buttonStyle', v as 'filled' | 'outline')}
                    />
                  </div>

                  {/* Border Radius */}
                  <NumberStepper
                    label="Border Radius"
                    value={customization.buttonBorderRadius}
                    onChange={(value) => onCustomizationChange('buttonBorderRadius', value)}
                    min={0}
                    max={24}
                    step={1}
                  />

                  {/* Font Size */}
                  <NumberStepper
                    label="Font Size"
                    value={customization.buttonFontSize}
                    onChange={(value) => onCustomizationChange('buttonFontSize', value)}
                    min={12}
                    max={18}
                    step={1}
                  />

                  {/* Font Weight */}
                  <div className="space-y-2">
                    <Label className="text-sm">Font Weight</Label>
                    <Select
                      value={customization.buttonFontWeight}
                      onValueChange={(v) => onCustomizationChange('buttonFontWeight', v)}
                    >
                      <SelectTrigger className="h-9 text-sm">
                        <SelectValue />
                      </SelectTrigger>
                      <SelectContent>
                        <SelectItem value="400">Normal (400)</SelectItem>
                        <SelectItem value="500">Medium (500)</SelectItem>
                        <SelectItem value="600">Semi-bold (600)</SelectItem>
                        <SelectItem value="700">Bold (700)</SelectItem>
                      </SelectContent>
                    </Select>
                  </div>

                  {/* Padding */}
                  <NumberStepper
                    label="Padding"
                    value={customization.buttonPadding}
                    onChange={(value) => onCustomizationChange('buttonPadding', value)}
                    min={8}
                    max={20}
                    step={1}
                  />
                </CollapsibleContent>
              </Collapsible>
            )}

            {/* ── Text & Labels — PRO ──────────────────────────────────────── */}
            {isPro && (
              <Collapsible open={expandedSections.textLabels} onOpenChange={() => toggleSection('textLabels')}>
                <CollapsibleTrigger className="flex w-full items-center justify-between py-3 text-sm font-medium hover:text-primary border-t">
                  <div className="flex items-center gap-2">
                    <TextCursorInput className="h-4 w-4" />
                    <span>Text & Labels</span>
                  </div>
                  <div className="flex items-center gap-2">
                    <ProIndicator size="sm" />
                    <ChevronDown className={`h-4 w-4 transition-transform duration-200 ${expandedSections.textLabels ? 'rotate-180' : ''}`} />
                  </div>
                </CollapsibleTrigger>
                <CollapsibleContent className="space-y-4 pb-4">
                  {/* Period Separator */}
                  <div className="space-y-2">
                    <Label className="text-sm">Period Separator</Label>
                    <Select
                      value={customization.periodSeparator}
                      onValueChange={(v) => onCustomizationChange('periodSeparator', v)}
                    >
                      <SelectTrigger className="h-9 text-sm">
                        <SelectValue />
                      </SelectTrigger>
                      <SelectContent>
                        <SelectItem value="/">$29.99 / month</SelectItem>
                        <SelectItem value=" per ">$29.99 per month</SelectItem>
                        <SelectItem value=" every ">$29.99 every month</SelectItem>
                      </SelectContent>
                    </Select>
                  </div>

                  {/* Sign-up Fee Label */}
                  <div className="space-y-2">
                    <Label className="text-sm">Sign-up Fee Label</Label>
                    <Select
                      value={customization.signUpFeeLabel}
                      onValueChange={(v) => onCustomizationChange('signUpFeeLabel', v)}
                    >
                      <SelectTrigger className="h-9 text-sm">
                        <SelectValue />
                      </SelectTrigger>
                      <SelectContent>
                        <SelectItem value="and a %s sign-up fee">and a $50 sign-up fee</SelectItem>
                        <SelectItem value="+ %s sign-up fee">+ $50 sign-up fee</SelectItem>
                        <SelectItem value="One-time fee: %s">One-time fee: $50</SelectItem>
                        <SelectItem value="Setup fee: %s">Setup fee: $50</SelectItem>
                      </SelectContent>
                    </Select>
                    <p className="text-xs text-muted-foreground">
                      %s is replaced with the fee amount
                    </p>
                  </div>

                  {/* Trial Label */}
                  <div className="space-y-2">
                    <Label className="text-sm">Trial Label</Label>
                    <Select
                      value={customization.trialLabel}
                      onValueChange={(v) => onCustomizationChange('trialLabel', v)}
                    >
                      <SelectTrigger className="h-9 text-sm">
                        <SelectValue />
                      </SelectTrigger>
                      <SelectContent>
                        <SelectItem value="with a %1$d %2$s free trial">with a 7 day free trial</SelectItem>
                        <SelectItem value="Includes %1$d %2$s free trial">Includes 7 day free trial</SelectItem>
                        <SelectItem value="Free trial: %1$d %2$s">Free trial: 7 days</SelectItem>
                        <SelectItem value="Try free for %1$d %2$s">Try free for 7 days</SelectItem>
                      </SelectContent>
                    </Select>
                    <p className="text-xs text-muted-foreground">
                      %1$d = number, %2$s = period (days, weeks, etc.)
                    </p>
                  </div>
                </CollapsibleContent>
              </Collapsible>
            )}

            {/* ── Typography — PRO ──────────────────────────────────────── */}
            {isPro && (
              <Collapsible open={expandedSections.typography} onOpenChange={() => toggleSection('typography')}>
                <CollapsibleTrigger className="flex w-full items-center justify-between py-3 text-sm font-medium hover:text-primary border-t">
                  <div className="flex items-center gap-2">
                    <Type className="h-4 w-4" />
                    <span>Typography</span>
                  </div>
                  <div className="flex items-center gap-2">
                    <ProIndicator size="sm" />
                    <ChevronDown className={`h-4 w-4 transition-transform duration-200 ${expandedSections.typography ? 'rotate-180' : ''}`} />
                  </div>
                </CollapsibleTrigger>
                <CollapsibleContent className="space-y-4 pb-4">
                  {/* Font Family */}
                  <GlobalTypographyPicker
                    label="Font Family"
                    value={customization.fontFamily}
                    onChange={(v) => onCustomizationChange('fontFamily', v)}
                    globalTokenId="body"
                  />

                  {/* Font Sizes */}
                  <Label className="text-sm text-muted-foreground pt-1">Font Sizes</Label>
                  <NumberStepper
                    label="Price"
                    value={customization.priceFontSize}
                    onChange={(value) => onCustomizationChange('priceFontSize', value)}
                    min={18}
                    max={36}
                    step={1}
                  />
                  <NumberStepper
                    label="Period"
                    value={customization.periodFontSize}
                    onChange={(value) => onCustomizationChange('periodFontSize', value)}
                    min={10}
                    max={20}
                    step={1}
                  />
                  <NumberStepper
                    label="Sign-up Fee"
                    value={customization.signUpFeeFontSize}
                    onChange={(value) => onCustomizationChange('signUpFeeFontSize', value)}
                    min={10}
                    max={20}
                    step={1}
                  />
                  <NumberStepper
                    label="Trial Text"
                    value={customization.trialFontSize}
                    onChange={(value) => onCustomizationChange('trialFontSize', value)}
                    min={10}
                    max={20}
                    step={1}
                  />
                </CollapsibleContent>
              </Collapsible>
            )}

            {/* ── Container Styling — PRO ──────────────────────────────────── */}
            {isPro && (
              <Collapsible open={expandedSections.containerStyling} onOpenChange={() => toggleSection('containerStyling')}>
                <CollapsibleTrigger className="flex w-full items-center justify-between py-3 text-sm font-medium hover:text-primary border-t">
                  <div className="flex items-center gap-2">
                    <BoxSelect className="h-4 w-4" />
                    <span>Container Styling</span>
                  </div>
                  <div className="flex items-center gap-2">
                    <ProIndicator size="sm" />
                    <ChevronDown className={`h-4 w-4 transition-transform duration-200 ${expandedSections.containerStyling ? 'rotate-180' : ''}`} />
                  </div>
                </CollapsibleTrigger>
                <CollapsibleContent className="space-y-4 pb-4">
                  <NumberStepper
                    label="Border Radius"
                    value={customization.containerBorderRadius}
                    onChange={(value) => onCustomizationChange('containerBorderRadius', value)}
                    min={0}
                    max={24}
                    step={1}
                  />
                  <NumberStepper
                    label="Padding"
                    value={customization.containerPadding}
                    onChange={(value) => onCustomizationChange('containerPadding', value)}
                    min={12}
                    max={40}
                    step={2}
                  />
                </CollapsibleContent>
              </Collapsible>
            )}

            {/* ── Button Text — PRO ────────────────────────────────────────── */}
            {isPro && (
              <Collapsible open={expandedSections.buttonText} onOpenChange={() => toggleSection('buttonText')}>
                <CollapsibleTrigger className="flex w-full items-center justify-between py-3 text-sm font-medium hover:text-primary border-t">
                  <div className="flex items-center gap-2">
                    <TextCursorInput className="h-4 w-4" />
                    <span>Button Text</span>
                  </div>
                  <div className="flex items-center gap-2">
                    <ProIndicator size="sm" />
                    <ChevronDown className={`h-4 w-4 transition-transform duration-200 ${expandedSections.buttonText ? 'rotate-180' : ''}`} />
                  </div>
                </CollapsibleTrigger>
                <CollapsibleContent className="space-y-4 pb-4">
                  <div className="space-y-2">
                    <Label htmlFor="button_text" className="text-sm">Subscribe Button Text</Label>
                    <Input
                      id="button_text"
                      value={settings.button_text}
                      onChange={(e) => onSettingChange('button_text', e.target.value)}
                      placeholder="Sign Up Now"
                      className="h-9 text-sm"
                    />
                    <p className="text-xs text-muted-foreground">
                      Text shown on the product page subscribe button
                    </p>
                  </div>
                  <div className="space-y-2">
                    <Label htmlFor="add_to_cart_text" className="text-sm">Add to Cart Text</Label>
                    <Input
                      id="add_to_cart_text"
                      value={settings.add_to_cart_text}
                      onChange={(e) => onSettingChange('add_to_cart_text', e.target.value)}
                      placeholder="Subscribe"
                      className="h-9 text-sm"
                    />
                    <p className="text-xs text-muted-foreground">
                      Text shown on shop page subscribe buttons
                    </p>
                  </div>
                </CollapsibleContent>
              </Collapsible>
            )}

            {/* ── Buy Now Toggle — PRO ─────────────────────────────────────── */}
            {isPro && (
              <Collapsible open={expandedSections.buyNow} onOpenChange={() => toggleSection('buyNow')}>
                <CollapsibleTrigger className="flex w-full items-center justify-between py-3 text-sm font-medium hover:text-primary border-t">
                  <div className="flex items-center gap-2">
                    <ShoppingBag className="h-4 w-4" />
                    <span>Buy Now Toggle</span>
                  </div>
                  <div className="flex items-center gap-2">
                    <ProIndicator size="sm" />
                    <ChevronDown className={`h-4 w-4 transition-transform duration-200 ${expandedSections.buyNow ? 'rotate-180' : ''}`} />
                  </div>
                </CollapsibleTrigger>
                <CollapsibleContent className="space-y-4 pb-4">
                  <p className="text-xs text-muted-foreground">
                    Customize the subscribe / buy-once toggle shown on products that have Buy Now enabled.
                  </p>

                  {/* Toggle Style */}
                  <div className="space-y-2">
                    <Label className="text-sm">Toggle Style</Label>
                    <Select
                      value={settings.buy_now_toggle_style}
                      onValueChange={(v) => onSettingChange('buy_now_toggle_style', v)}
                    >
                      <SelectTrigger className="h-9 text-sm">
                        <SelectValue />
                      </SelectTrigger>
                      <SelectContent>
                        <SelectItem value="pills">Pills</SelectItem>
                        <SelectItem value="buttons">Buttons</SelectItem>
                      </SelectContent>
                    </Select>
                  </div>

                  {/* Labels */}
                  <div className="space-y-2">
                    <Label htmlFor="buy_now_subscribe_label" className="text-sm">Subscribe Label</Label>
                    <Input
                      id="buy_now_subscribe_label"
                      value={settings.buy_now_subscribe_label}
                      onChange={(e) => onSettingChange('buy_now_subscribe_label', e.target.value)}
                      placeholder="Subscribe & Save"
                      className="h-9 text-sm"
                    />
                  </div>
                  <div className="space-y-2">
                    <Label htmlFor="buy_now_one_time_label" className="text-sm">Buy Once Label</Label>
                    <Input
                      id="buy_now_one_time_label"
                      value={settings.buy_now_one_time_label}
                      onChange={(e) => onSettingChange('buy_now_one_time_label', e.target.value)}
                      placeholder="Buy Once"
                      className="h-9 text-sm"
                    />
                  </div>

                  {/* Toggle Colors — sub-tabs: Normal / Hover / Active */}
                  <div className="space-y-3">
                    <SegmentedControl
                      value={buyNowColorState}
                      options={[
                        { value: 'normal', label: 'Normal' },
                        { value: 'hover', label: 'Hover' },
                        { value: 'active', label: 'Active' },
                      ]}
                      onChange={(v) => setBuyNowColorState(v as 'normal' | 'hover' | 'active')}
                    />

                    {buyNowColorState === 'normal' && (
                      <div className="grid grid-cols-3 gap-3">
                        <GlobalColorPicker
                          label="Background"
                          value={settings.buy_now_normal_bg}
                          onChange={(v) => onSettingChange('buy_now_normal_bg', v)}
                        />
                        <GlobalColorPicker
                          label="Text"
                          value={settings.buy_now_normal_text}
                          onChange={(v) => onSettingChange('buy_now_normal_text', v)}
                        />
                        <GlobalColorPicker
                          label="Border"
                          value={settings.buy_now_normal_border}
                          onChange={(v) => onSettingChange('buy_now_normal_border', v)}
                        />
                      </div>
                    )}

                    {buyNowColorState === 'hover' && (
                      <div className="grid grid-cols-3 gap-3">
                        <GlobalColorPicker
                          label="Background"
                          value={settings.buy_now_hover_bg}
                          onChange={(v) => onSettingChange('buy_now_hover_bg', v)}
                        />
                        <GlobalColorPicker
                          label="Text"
                          value={settings.buy_now_hover_text}
                          onChange={(v) => onSettingChange('buy_now_hover_text', v)}
                        />
                        <GlobalColorPicker
                          label="Border"
                          value={settings.buy_now_hover_border}
                          onChange={(v) => onSettingChange('buy_now_hover_border', v)}
                        />
                      </div>
                    )}

                    {buyNowColorState === 'active' && (
                      <div className="grid grid-cols-3 gap-3">
                        <GlobalColorPicker
                          label="Background"
                          value={settings.buy_now_active_bg}
                          onChange={(v) => onSettingChange('buy_now_active_bg', v)}
                          globalTokenId="primary"
                        />
                        <GlobalColorPicker
                          label="Text"
                          value={settings.buy_now_active_text}
                          onChange={(v) => onSettingChange('buy_now_active_text', v)}
                        />
                        <GlobalColorPicker
                          label="Border"
                          value={settings.buy_now_active_border}
                          onChange={(v) => onSettingChange('buy_now_active_border', v)}
                          globalTokenId="primary"
                        />
                      </div>
                    )}
                  </div>

                  {/* Border Radius */}
                  <div className="pt-2">
                    <NumberStepper
                      label="Border Radius"
                      value={settings.buy_now_border_radius}
                      onChange={(v) => onSettingChange('buy_now_border_radius', v)}
                      min={0}
                      max={24}
                      step={1}
                    />
                  </div>
                </CollapsibleContent>
              </Collapsible>
            )}
          </CardContent>
        </Card>
      </div>

      {/* Right Column — Live Preview (Sticky) */}
      <LivePreview
        title="Live Preview"
        description="See how your subscription will appear"
        stickyTop={100}
        minHeight={350}
        showPattern={true}
        headerActions={
          <Button variant="outline" size="sm" onClick={resetCustomization} className="h-8">
            <RotateCcw className="h-3 w-3 mr-1.5" />
            Reset
          </Button>
        }
      >
        {renderLivePreview()}
      </LivePreview>
    </div>
  )
}
