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 { 
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/components/ui/select"
import { TemplateGrid, Template } from "@/components/ui/template-grid"
import { LivePreview as LivePreviewContainer } from "@/components/ui/live-preview"
import { Collapsible, CollapsibleContent, CollapsibleTrigger } from "@/components/ui/collapsible"
import { GlobalColorPicker } from "@/components/ui/global-color-picker"
import { GlobalTypographyPicker } from "@/components/ui/global-typography-picker"
import { RadioGroup, RadioGroupItem } from "@/components/ui/radio-group"
import { Button } from "@/components/ui/button"
import { Switch } from "@/components/ui/switch"
import { 
  Palette, 
  Type, 
  Square, 
  Maximize2,
  LayoutTemplate,
  Layers,
  X,
  ChevronDown,
  AlignLeft,
  AlignCenter,
  AlignRight,
  Minus,
  Plus,
  RotateCcw,
  Sparkles,
  Image,
  CheckCircle2,
} from "lucide-react"
import { usePro } from "@/contexts/pro-context"
import { ProIndicator } from "@/components/pro/pro-indicator"
import { AddedToCartPopupPreview } from "../popup-preview"
import { 
  PopupStyleSettings,
  AddedToCartSettings,
  fontSizeOptions,
  borderRadiusOptions,
  shadowOptions,
  stylePresets
} from "../../config"

interface CustomizationTabProps {
  styles: PopupStyleSettings
  popupDesign: AddedToCartSettings['popupDesign']
  updateStyles: <K extends keyof PopupStyleSettings>(key: K, value: PopupStyleSettings[K]) => void
  resetStyles: () => void
  // Button & heading state for Live Preview (controls moved to Settings tab)
  showViewCartButton: boolean
  showCheckoutButton: boolean
  showContinueShoppingButton: boolean
  viewCartButtonText: string
  checkoutButtonText: string
  continueShoppingButtonText: string
  popupHeadingText: string
  showSuccessIcon: boolean
  cartDisplay: AddedToCartSettings['cartDisplay']
  showRelatedProducts: boolean
  relatedProductsCount: number
  animationDuration: number
  updateSettings: <K extends keyof AddedToCartSettings>(key: K, value: AddedToCartSettings[K]) => void
}

/** 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="space-y-2">
      {label && <Label className="text-sm">{label}</Label>}
      <div className="flex items-center rounded-md border bg-background w-fit">
        <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({ 
  styles, 
  popupDesign,
  updateStyles,
  resetStyles,
  showViewCartButton,
  showCheckoutButton,
  showContinueShoppingButton,
  viewCartButtonText,
  checkoutButtonText,
  continueShoppingButtonText,
  popupHeadingText,
  showSuccessIcon,
  cartDisplay,
  showRelatedProducts,
  relatedProductsCount,
  animationDuration,
  updateSettings
}: CustomizationTabProps) {
  const { isPro } = usePro()

  // Accordion state for custom styling sections
  const [expandedSections, setExpandedSections] = useState<Record<string, boolean>>({
    content: false,
    colors: false,
    buttons: false,
    background: false,
    typography: false,
    spacing: false,
    border: false,
    icon: false,
    closeButton: false,
    animation: false,
    textAlignment: false,
  })

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

  // Build templates list — 3 Free presets
  const templates: Template[] = stylePresets.map(preset => ({
    id: preset.id,
    name: preset.name,
    description: preset.description,
  }))

  // Apply a preset template
  const applyPreset = (presetId: string) => {
    updateSettings('popupDesign', presetId as AddedToCartSettings['popupDesign'])
    const preset = stylePresets.find(p => p.id === presetId)
    if (preset) {
      Object.entries(preset.styles).forEach(([key, value]) => {
        if (value !== undefined) {
          updateStyles(key as keyof PopupStyleSettings, value as PopupStyleSettings[keyof PopupStyleSettings])
        }
      })
    }
  }

  // Preview props
  const previewProps = {
    styles,
    showViewCartButton,
    showCheckoutButton,
    showContinueShoppingButton,
    viewCartButtonText,
    checkoutButtonText,
    continueShoppingButtonText,
    headingText: popupHeadingText || 'Product added to cart!',
    showSuccessIcon,
    showRelatedProducts,
    relatedProductsCount,
  }

  return (
    <div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
      {/* Left Column - Options */}
      <div className="space-y-6 min-w-0">

        {/* Template Selection */}
        <Card>
          <CardHeader>
            <CardTitle className="flex items-center gap-2">
              <LayoutTemplate className="h-5 w-5" />
              Templates
            </CardTitle>
            <CardDescription>
              Choose a pre-designed style for your popup
            </CardDescription>
          </CardHeader>
          <CardContent>
            <TemplateGrid
              templates={templates}
              selectedId={popupDesign}
              onSelect={applyPreset}
              columns={3}
              size="sm"
              isPro={isPro}
            />
          </CardContent>
        </Card>

        {/* Customize Design — always visible (no Custom mode gating) */}
        <Card>
          <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
            <div>
              <CardTitle>Customize Design</CardTitle>
              <CardDescription>
                {isPro ? 'Fine-tune every aspect of your popup design' : 'Customize the colors of your popup design'}
              </CardDescription>
            </div>
            <Button variant="outline" size="sm" onClick={resetStyles}>
              <RotateCcw className="h-3 w-3 mr-1" />
              Reset
            </Button>
          </CardHeader>
            <CardContent className="space-y-0">
              {/* Content Section — Always Free */}
              <Collapsible open={expandedSections.content} onOpenChange={() => toggleSection('content')}>
                <CollapsibleTrigger className="flex w-full items-center justify-between py-3 text-sm font-medium hover:text-primary">
                  <span className="flex items-center gap-2">
                    <Type className="h-4 w-4" />
                    Content
                  </span>
                  <ChevronDown className={`h-4 w-4 transition-transform ${expandedSections.content ? 'rotate-180' : ''}`} />
                </CollapsibleTrigger>
                <CollapsibleContent className="space-y-4 pt-2 pb-4">
                  <div className="space-y-2">
                    <Label htmlFor="popup-heading">Popup Heading Text</Label>
                    <Input
                      id="popup-heading"
                      value={popupHeadingText}
                      onChange={(e) => updateSettings('popupHeadingText', e.target.value)}
                      placeholder="Product added to cart!"
                    />
                    <p className="text-xs text-muted-foreground">
                      The main heading shown at the top of the popup
                    </p>
                  </div>
                  <div className="flex items-center justify-between gap-4 rounded-lg border p-3">
                    <div className="space-y-1">
                      <Label htmlFor="show-success-icon" className="cursor-pointer">
                        Show Success Icon
                      </Label>
                      <p className="text-xs text-muted-foreground">
                        Display the confirmation icon beside the popup heading
                      </p>
                    </div>
                    <Switch
                      id="show-success-icon"
                      checked={showSuccessIcon}
                      onCheckedChange={(checked) => updateSettings('showSuccessIcon', checked)}
                    />
                  </div>
                </CollapsibleContent>
              </Collapsible>

              {/* Colors Section — Always 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">
                  <span className="flex items-center gap-2">
                    <Palette className="h-4 w-4" />
                    Colors
                  </span>
                  <ChevronDown className={`h-4 w-4 transition-transform ${expandedSections.colors ? 'rotate-180' : ''}`} />
                </CollapsibleTrigger>
                <CollapsibleContent className="space-y-4 pt-2 pb-4">
                  <div className="grid gap-4 sm:grid-cols-2">
                    <GlobalColorPicker
                      label="Overlay Color"
                      value={styles.overlayColor}
                      onChange={(v) => updateStyles('overlayColor', v)}
                    />
                    <NumberStepper
                      label="Overlay Opacity"
                      value={styles.overlayOpacity}
                      onChange={(value) => updateStyles('overlayOpacity', value)}
                      min={0}
                      max={100}
                      step={5}
                      unit="%"
                    />
                    <GlobalColorPicker
                      label="Text Color"
                      value={styles.textColor}
                      onChange={(v) => updateStyles('textColor', v)}
                      globalTokenId="text"
                      featureDefault="#1f2937"
                    />
                    <GlobalColorPicker
                      label="Heading Color"
                      value={styles.headingColor}
                      onChange={(v) => updateStyles('headingColor', v)}
                      globalTokenId="text"
                      featureDefault="#111827"
                    />
                    <GlobalColorPicker
                      label="Price Color"
                      value={styles.priceColor}
                      onChange={(v) => updateStyles('priceColor', v)}
                      globalTokenId="success"
                      featureDefault="#047857"
                    />
                    <GlobalColorPicker
                      label="Border Color"
                      value={styles.borderColor}
                      onChange={(v) => updateStyles('borderColor', v)}
                      fullWidth
                    />
                    <GlobalColorPicker
                      label="Success Icon"
                      value={styles.iconColor}
                      onChange={(v) => updateStyles('iconColor', v)}
                      globalTokenId="primary"
                      featureDefault="#00226b"
                    />
                    <GlobalColorPicker
                      label="Icon Background"
                      value={styles.iconBackgroundColor}
                      onChange={(v) => updateStyles('iconBackgroundColor', v)}
                      globalTokenId="accent"
                      featureDefault="#eef4ff"
                    />
                  </div>
                </CollapsibleContent>
              </Collapsible>

              {/* Button Colors Section — Free */}
              <Collapsible open={expandedSections.buttons} onOpenChange={() => toggleSection('buttons')}>
                <CollapsibleTrigger className="flex w-full items-center justify-between py-3 text-sm font-medium hover:text-primary border-t">
                  <span className="flex items-center gap-2">
                    <Layers className="h-4 w-4" />
                    Button Colors
                  </span>
                  <ChevronDown className={`h-4 w-4 transition-transform ${expandedSections.buttons ? 'rotate-180' : ''}`} />
                </CollapsibleTrigger>
                <CollapsibleContent className="space-y-6 pt-2 pb-4">
                  <div className="space-y-4">
                    <Label className="text-base font-medium">Primary Button (Checkout)</Label>
                    <div className="grid gap-4 sm:grid-cols-3">
                      <GlobalColorPicker
                        label="Background"
                        value={styles.primaryButtonBg}
                        onChange={(v) => updateStyles('primaryButtonBg', v)}
                        globalTokenId="primary"
                        featureDefault="#00226b"
                      />
                      <GlobalColorPicker
                        label="Text"
                        value={styles.primaryButtonText}
                        onChange={(v) => updateStyles('primaryButtonText', v)}
                      />
                      <GlobalColorPicker
                        label="Hover Background"
                        value={styles.primaryButtonHoverBg}
                        onChange={(v) => updateStyles('primaryButtonHoverBg', v)}
                        globalTokenId="secondary"
                        featureDefault="#001a52"
                      />
                    </div>
                  </div>
                  <div className="space-y-4 pt-4 border-t">
                    <Label className="text-base font-medium">Secondary Buttons (View Cart, Continue Shopping)</Label>
                    <div className="grid gap-4 sm:grid-cols-3">
                      <GlobalColorPicker
                        label="Background"
                        value={styles.secondaryButtonBg}
                        onChange={(v) => updateStyles('secondaryButtonBg', v)}
                      />
                      <GlobalColorPicker
                        label="Text"
                        value={styles.secondaryButtonText}
                        onChange={(v) => updateStyles('secondaryButtonText', v)}
                      />
                      <GlobalColorPicker
                        label="Hover Background"
                        value={styles.secondaryButtonHoverBg}
                        onChange={(v) => updateStyles('secondaryButtonHoverBg', v)}
                      />
                    </div>
                  </div>
                </CollapsibleContent>
              </Collapsible>

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

              {/* Background Styling Section — Pro only */}
              {isPro && (
              <Collapsible open={expandedSections.background} onOpenChange={() => toggleSection('background')}>
                <CollapsibleTrigger className="flex w-full items-center justify-between py-3 text-sm font-medium hover:text-primary border-t">
                  <span className="flex items-center gap-2">
                    <Image className="h-4 w-4" />
                    Background
                  </span>
                  <div className="flex items-center gap-2">
                    <ProIndicator size="sm" />
                    <ChevronDown className={`h-4 w-4 transition-transform ${expandedSections.background ? 'rotate-180' : ''}`} />
                  </div>
                </CollapsibleTrigger>
                <CollapsibleContent className="space-y-4 pt-2 pb-4">
                  <div className="grid gap-4 sm:grid-cols-2">
                    <GlobalColorPicker
                      label="Popup Background"
                      value={styles.backgroundColor}
                      onChange={(v) => updateStyles('backgroundColor', v)}
                      globalTokenId="background"
                      featureDefault="#ffffff"
                    />
                    <GlobalColorPicker
                      label="Product Row Background"
                      value={styles.productAreaBgColor || ''}
                      onChange={(v) => updateStyles('productAreaBgColor', v)}
                    />
                  </div>
                  {styles.productAreaBgColor && (
                    <Button
                      variant="ghost"
                      size="sm"
                      onClick={() => updateStyles('productAreaBgColor', '' as string)}
                      className="text-xs"
                    >
                      <RotateCcw className="h-3 w-3 mr-1" />
                      Reset product row background
                    </Button>
                  )}
                </CollapsibleContent>
              </Collapsible>
              )}

              {/* Typography Section — Pro only */}
              {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">
                  <span className="flex items-center gap-2">
                    <Type className="h-4 w-4" />
                    Typography
                  </span>
                  <div className="flex items-center gap-2">
                    <ProIndicator size="sm" />
                    <ChevronDown className={`h-4 w-4 transition-transform ${expandedSections.typography ? 'rotate-180' : ''}`} />
                  </div>
                </CollapsibleTrigger>
                <CollapsibleContent className="space-y-4 pt-2 pb-4">
                  <GlobalTypographyPicker
                    label="Font Family"
                    value={styles.fontFamily}
                    onChange={(value) => updateStyles('fontFamily', value)}
                    globalTokenId="body"
                    featureDefault="inherit"
                  />
                  <div className="grid gap-4 sm:grid-cols-2">
                    <div className="space-y-2">
                      <Label>Body Font Size</Label>
                      <Select value={styles.fontSize} onValueChange={(value) => updateStyles('fontSize', value)}>
                        <SelectTrigger><SelectValue /></SelectTrigger>
                        <SelectContent>
                          {fontSizeOptions.map((option) => (
                            <SelectItem key={option.value} value={option.value}>{option.label}</SelectItem>
                          ))}
                        </SelectContent>
                      </Select>
                    </div>
                    <div className="space-y-2">
                      <Label>Heading Font Size</Label>
                      <Select value={styles.headingFontSize} onValueChange={(value) => updateStyles('headingFontSize', value)}>
                        <SelectTrigger><SelectValue /></SelectTrigger>
                        <SelectContent>
                          <SelectItem value="16">16px</SelectItem>
                          <SelectItem value="18">18px (Default)</SelectItem>
                          <SelectItem value="20">20px</SelectItem>
                          <SelectItem value="22">22px</SelectItem>
                          <SelectItem value="24">24px</SelectItem>
                        </SelectContent>
                      </Select>
                    </div>
                  </div>
                </CollapsibleContent>
              </Collapsible>
              )}

              {/* Text Alignment Section — Pro only */}
              {isPro && (
              <Collapsible open={expandedSections.textAlignment} onOpenChange={() => toggleSection('textAlignment')}>
                <CollapsibleTrigger className="flex w-full items-center justify-between py-3 text-sm font-medium hover:text-primary border-t">
                  <span className="flex items-center gap-2">
                    <AlignLeft className="h-4 w-4" />
                    Text Alignment
                  </span>
                  <div className="flex items-center gap-2">
                    <ProIndicator size="sm" />
                    <ChevronDown className={`h-4 w-4 transition-transform ${expandedSections.textAlignment ? 'rotate-180' : ''}`} />
                  </div>
                </CollapsibleTrigger>
                <CollapsibleContent className="space-y-4 pt-2 pb-4">
                  <p className="text-sm text-muted-foreground">
                    Controls the alignment of all text elements including heading, product info, prices, and button positioning.
                  </p>
                  <RadioGroup
                    value={styles.textAlign || 'left'}
                    onValueChange={(value) => updateStyles('textAlign', value as PopupStyleSettings['textAlign'])}
                    className="flex gap-4"
                  >
                    <div className="flex items-center space-x-2">
                      <RadioGroupItem value="left" id="align-left" />
                      <Label htmlFor="align-left" className="flex items-center gap-1.5 cursor-pointer">
                        <AlignLeft className="h-4 w-4" />
                        Left
                      </Label>
                    </div>
                    <div className="flex items-center space-x-2">
                      <RadioGroupItem value="center" id="align-center" />
                      <Label htmlFor="align-center" className="flex items-center gap-1.5 cursor-pointer">
                        <AlignCenter className="h-4 w-4" />
                        Center
                      </Label>
                    </div>
                    <div className="flex items-center space-x-2">
                      <RadioGroupItem value="right" id="align-right" />
                      <Label htmlFor="align-right" className="flex items-center gap-1.5 cursor-pointer">
                        <AlignRight className="h-4 w-4" />
                        Right
                      </Label>
                    </div>
                  </RadioGroup>
                </CollapsibleContent>
              </Collapsible>
              )}

              {/* Spacing & Dimensions Section — Pro only */}
              {isPro && (
              <Collapsible open={expandedSections.spacing} onOpenChange={() => toggleSection('spacing')}>
                <CollapsibleTrigger className="flex w-full items-center justify-between py-3 text-sm font-medium hover:text-primary border-t">
                  <span className="flex items-center gap-2">
                    <Maximize2 className="h-4 w-4" />
                    Spacing & Dimensions
                  </span>
                  <div className="flex items-center gap-2">
                    <ProIndicator size="sm" />
                    <ChevronDown className={`h-4 w-4 transition-transform ${expandedSections.spacing ? 'rotate-180' : ''}`} />
                  </div>
                </CollapsibleTrigger>
                <CollapsibleContent className="pt-2 pb-4">
                  <div className="grid gap-4 sm:grid-cols-3">
                    <NumberStepper
                      label="Popup Width"
                      value={parseInt(styles.popupWidth)}
                      onChange={(value) => updateStyles('popupWidth', value.toString())}
                      min={320}
                      max={800}
                      step={20}
                    />
                    <NumberStepper
                      label="Content Padding"
                      value={parseInt(styles.padding)}
                      onChange={(value) => updateStyles('padding', value.toString())}
                      min={12}
                      max={48}
                      step={4}
                    />
                    <NumberStepper
                      label="Item Spacing"
                      value={parseInt(styles.itemSpacing)}
                      onChange={(value) => updateStyles('itemSpacing', value.toString())}
                      min={8}
                      max={32}
                      step={4}
                    />
                    <NumberStepper
                      label="Product Row Padding"
                      value={parseInt(styles.productAreaPadding || '0')}
                      onChange={(value) => updateStyles('productAreaPadding', value.toString())}
                      min={0}
                      max={32}
                      step={2}
                    />
                    <NumberStepper
                      label="Related Product Gap"
                      value={parseInt(styles.relatedProductsGap || '16')}
                      onChange={(value) => updateStyles('relatedProductsGap', value.toString())}
                      min={4}
                      max={32}
                      step={2}
                    />
                    <NumberStepper
                      label="Related to Buttons Gap"
                      value={parseInt(styles.relatedButtonsGap || '16')}
                      onChange={(value) => updateStyles('relatedButtonsGap', value.toString())}
                      min={0}
                      max={48}
                      step={2}
                    />
                    <NumberStepper
                      label="Button Gap"
                      value={parseInt(styles.buttonGap || '8')}
                      onChange={(value) => updateStyles('buttonGap', value.toString())}
                      min={0}
                      max={24}
                      step={2}
                    />
                  </div>
                </CollapsibleContent>
              </Collapsible>
              )}

              {/* Border & Shadow Section — Pro only */}
              {isPro && (
              <Collapsible open={expandedSections.border} onOpenChange={() => toggleSection('border')}>
                <CollapsibleTrigger className="flex w-full items-center justify-between py-3 text-sm font-medium hover:text-primary border-t">
                  <span className="flex items-center gap-2">
                    <Square className="h-4 w-4" />
                    Border & Shadow
                  </span>
                  <div className="flex items-center gap-2">
                    <ProIndicator size="sm" />
                    <ChevronDown className={`h-4 w-4 transition-transform ${expandedSections.border ? 'rotate-180' : ''}`} />
                  </div>
                </CollapsibleTrigger>
                <CollapsibleContent className="space-y-4 pt-2 pb-4">
                  <div className="grid gap-4 sm:grid-cols-3">
                    <NumberStepper
                      label="Border Width"
                      value={parseInt(styles.borderWidth)}
                      onChange={(value) => updateStyles('borderWidth', value.toString())}
                      min={0}
                      max={4}
                      step={1}
                    />
                    <div className="space-y-2">
                      <Label>Popup Radius</Label>
                      <Select value={styles.borderRadius} onValueChange={(value) => updateStyles('borderRadius', value)}>
                        <SelectTrigger><SelectValue /></SelectTrigger>
                        <SelectContent>
                          {borderRadiusOptions.map((option) => (
                            <SelectItem key={option.value} value={option.value}>{option.label}</SelectItem>
                          ))}
                        </SelectContent>
                      </Select>
                    </div>
                    <div className="space-y-2">
                      <Label>Shadow</Label>
                      <Select value={styles.shadow} onValueChange={(value) => updateStyles('shadow', value)}>
                        <SelectTrigger><SelectValue /></SelectTrigger>
                        <SelectContent>
                          {shadowOptions.map((option) => (
                            <SelectItem key={option.value} value={option.value}>{option.label}</SelectItem>
                          ))}
                        </SelectContent>
                      </Select>
                    </div>
                  </div>
                  <div className="pt-4 border-t">
                    <NumberStepper
                      label="Product Row Radius"
                      value={parseInt(styles.productAreaBorderRadius || '0')}
                      onChange={(value) => updateStyles('productAreaBorderRadius', value.toString())}
                      min={0}
                      max={24}
                      step={2}
                    />
                    <p className="text-xs text-muted-foreground mt-2">
                      Applies when a product row background or padding is used.
                    </p>
                  </div>
                  {/* Independent Button Border Radius */}
                  <div className="pt-4 border-t">
                    <div className="space-y-2">
                      <Label>Button Border Radius</Label>
                      <Select value={styles.buttonBorderRadius || styles.borderRadius} onValueChange={(value) => updateStyles('buttonBorderRadius', value)}>
                        <SelectTrigger><SelectValue /></SelectTrigger>
                        <SelectContent>
                          {borderRadiusOptions.map((option) => (
                            <SelectItem key={option.value} value={option.value}>{option.label}</SelectItem>
                          ))}
                        </SelectContent>
                      </Select>
                      <p className="text-xs text-muted-foreground">
                        Controls the roundness of popup buttons independently from the popup container
                      </p>
                    </div>
                  </div>
                </CollapsibleContent>
              </Collapsible>
              )}

              {/* Success Icon Styling Section — Pro only */}
              {isPro && (
              <Collapsible open={expandedSections.icon} onOpenChange={() => toggleSection('icon')}>
                <CollapsibleTrigger className="flex w-full items-center justify-between py-3 text-sm font-medium hover:text-primary border-t">
                  <span className="flex items-center gap-2">
                    <CheckCircle2 className="h-4 w-4" />
                    Success Icon
                  </span>
                  <div className="flex items-center gap-2">
                    <ProIndicator size="sm" />
                    <ChevronDown className={`h-4 w-4 transition-transform ${expandedSections.icon ? 'rotate-180' : ''}`} />
                  </div>
                </CollapsibleTrigger>
                <CollapsibleContent className="space-y-4 pt-2 pb-4">
                  <div className="grid gap-4 sm:grid-cols-2">
                    <NumberStepper
                      label="Icon Size"
                      value={parseInt(styles.iconSize || '36')}
                      onChange={(value) => updateStyles('iconSize', value.toString())}
                      min={28}
                      max={64}
                      step={2}
                    />
                    <NumberStepper
                      label="Corner Radius"
                      value={parseInt(styles.iconBorderRadius || '28')}
                      onChange={(value) => updateStyles('iconBorderRadius', value.toString())}
                      min={0}
                      max={50}
                      step={2}
                      unit="%"
                    />
                  </div>
                </CollapsibleContent>
              </Collapsible>
              )}

              {/* Close Button Styling Section — Pro only */}
              {isPro && (
              <Collapsible open={expandedSections.closeButton} onOpenChange={() => toggleSection('closeButton')}>
                <CollapsibleTrigger className="flex w-full items-center justify-between py-3 text-sm font-medium hover:text-primary border-t">
                  <span className="flex items-center gap-2">
                    <X className="h-4 w-4" />
                    Close Button
                  </span>
                  <div className="flex items-center gap-2">
                    <ProIndicator size="sm" />
                    <ChevronDown className={`h-4 w-4 transition-transform ${expandedSections.closeButton ? 'rotate-180' : ''}`} />
                  </div>
                </CollapsibleTrigger>
                <CollapsibleContent className="space-y-4 pt-2 pb-4">
                  <NumberStepper
                    label="Button Size"
                    value={parseInt(styles.closeButtonSize || '32')}
                    onChange={(value) => updateStyles('closeButtonSize', value.toString())}
                    min={24}
                    max={44}
                    step={2}
                  />
                  <div className="grid gap-4 sm:grid-cols-2">
                    <GlobalColorPicker
                      label="Icon Color"
                      value={styles.closeButtonColor || '#6b7280'}
                      onChange={(v) => updateStyles('closeButtonColor', v)}
                      featureDefault="#6b7280"
                    />
                    <GlobalColorPicker
                      label="Background Color"
                      value={styles.closeButtonBgColor || 'transparent'}
                      onChange={(v) => updateStyles('closeButtonBgColor', v)}
                      featureDefault="transparent"
                    />
                  </div>
                </CollapsibleContent>
              </Collapsible>
              )}

              {/* Animation Section — Pro only */}
              {isPro && (
              <Collapsible open={expandedSections.animation} onOpenChange={() => toggleSection('animation')}>
                <CollapsibleTrigger className="flex w-full items-center justify-between py-3 text-sm font-medium hover:text-primary border-t">
                  <span className="flex items-center gap-2">
                    <Sparkles className="h-4 w-4" />
                    Animation
                  </span>
                  <div className="flex items-center gap-2">
                    <ProIndicator size="sm" />
                    <ChevronDown className={`h-4 w-4 transition-transform ${expandedSections.animation ? 'rotate-180' : ''}`} />
                  </div>
                </CollapsibleTrigger>
                <CollapsibleContent className="space-y-4 pt-2 pb-4">
                  <p className="text-sm text-muted-foreground">
                    Choose an entrance animation for your popup. The animation adapts automatically to each template type.
                  </p>
                  <div className="space-y-2">
                    <Label>Entrance Animation</Label>
                    <Select
                      value={styles.animationType}
                      onValueChange={(value) => updateStyles('animationType', value as PopupStyleSettings['animationType'])}
                    >
                      <SelectTrigger>
                        <SelectValue />
                      </SelectTrigger>
                      <SelectContent>
                        <SelectItem value="default">Default (Template Native)</SelectItem>
                        <SelectItem value="fade">Fade In</SelectItem>
                        <SelectItem value="slide-up">Slide Up</SelectItem>
                        <SelectItem value="slide-down">Slide Down</SelectItem>
                        <SelectItem value="zoom">Zoom In</SelectItem>
                        <SelectItem value="bounce">Bounce</SelectItem>
                        <SelectItem value="flip">Flip</SelectItem>
                      </SelectContent>
                    </Select>
                  </div>
                  <div className="rounded-md bg-muted/50 p-3">
                    <p className="text-xs text-muted-foreground">
                      <strong>Default</strong> uses each template's native animation — scale for Classic, slide-right for Flyout, slide-up for Solid Bar. Other options override the default with a unified animation style.
                    </p>
                  </div>
                </CollapsibleContent>
              </Collapsible>
              )}
            </CardContent>
          </Card>
      </div>

      {/* Right Column - Sticky Preview */}
      <LivePreviewContainer
        title="Live Preview"
        description="See your changes in real-time"
        minHeight={480}
      >
        <div className="w-full">
          <AddedToCartPopupPreview
            {...previewProps}
            popupDesign={popupDesign}
            cartDisplay={cartDisplay}
            animationDuration={animationDuration}
          />
        </div>
      </LivePreviewContainer>
    </div>
  )
}
