import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card"
import { Input } from "@/components/ui/input"
import { Label } from "@/components/ui/label"
import { Switch } from "@/components/ui/switch"
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select"
import { Textarea } from "@/components/ui/textarea"
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, resolveGlobalColor } from "@/components/ui/global-color-picker"
import { GlobalTypographyPicker } from "@/components/ui/global-typography-picker"
import { StyleSettings, FormSettings } from "../../types"
import { Palette, FileText, LayoutTemplate, Bell, Square, MousePointer, RectangleHorizontal, ChevronDown, Minus, Plus, Layout, Type } from "lucide-react"
import { useState, type CSSProperties } from "react"
import { usePro } from "@/contexts/pro-context"
import { ProIndicator } from "@/components/pro/pro-indicator"

type FormDesignType = StyleSettings['formDesign']

interface CustomizationTabProps {
  styleSettings: StyleSettings
  formSettings: FormSettings
  updateStyleSettings: <K extends keyof StyleSettings>(key: K, value: StyleSettings[K]) => void
  updateFormSettings: <K extends keyof FormSettings>(key: K, value: FormSettings[K]) => void
}

// Template configurations with metadata
interface StylePreset {
  id: FormDesignType
  name: string
  description: string
  config: Omit<StyleSettings, 'formDesign'>
}

const stylePresets: StylePreset[] = [
  {
    id: 'modern-minimal',
    name: 'Modern Minimal',
    description: 'Clean inline form',
    config: {
      primaryColor: '#00226b',
      textColor: '#1f2937',
      backgroundColor: '#f3f4f6',
      borderRadius: 8,
      buttonStyle: 'filled',
      formLayout: 'inline',
      contentAlignment: 'left',
      showIcon: false,
      padding: 20,
      margin: 16,
      borderWidth: 1,
      borderColor: '#e5e7eb',
      boxShadow: 'none',
      iconBackgroundColor: '#00226b',
      iconColor: '#ffffff',
      iconBorderRadius: 50,
      iconSize: 20,
      buttonTextColor: '#ffffff',
      buttonBorderColor: '',
      buttonBorderWidth: 1,
      buttonBorderRadius: 8,
      buttonPadding: 12,
      inputBorderColor: '#d1d5db',
      inputBorderWidth: 1,
      inputBackgroundColor: '#ffffff',
      inputTextColor: '#1f2937',
      inputBorderRadius: 8,
      fontFamily: '',
    },
  },
  {
    id: 'classic-card',
    name: 'Classic Card',
    description: 'Stacked card with bell',
    config: {
      primaryColor: '#00226b',
      textColor: '#1f2937',
      backgroundColor: '#f3f4f6',
      borderRadius: 12,
      buttonStyle: 'filled',
      formLayout: 'stacked',
      contentAlignment: 'center',
      showIcon: true,
      padding: 24,
      margin: 16,
      borderWidth: 0,
      borderColor: '#e5e7eb',
      boxShadow: 'small',
      iconBackgroundColor: '#00226b',
      iconColor: '#ffffff',
      iconBorderRadius: 50,
      iconSize: 20,
      buttonTextColor: '#ffffff',
      buttonBorderColor: '',
      buttonBorderWidth: 1,
      buttonBorderRadius: 8,
      buttonPadding: 12,
      inputBorderColor: '#d1d5db',
      inputBorderWidth: 1,
      inputBackgroundColor: '#ffffff',
      inputTextColor: '#1f2937',
      inputBorderRadius: 8,
      fontFamily: '',
    },
  },
]

// Form Preview Component
function FormPreview({ 
  styleSettings, 
  formSettings 
}: { 
  styleSettings: StyleSettings
  formSettings: FormSettings
}) {
  const isStacked = styleSettings.formLayout === 'stacked'
  const primaryColor = resolveGlobalColor(styleSettings.primaryColor, 'primary', '#00226b')
  const textColor = resolveGlobalColor(styleSettings.textColor, 'text', '#1f2937')
  const backgroundColor = resolveGlobalColor(styleSettings.backgroundColor, 'background', '#f3f4f6')
  const buttonBorderColor = styleSettings.buttonBorderColor || primaryColor
  const shadowBySize: Record<StyleSettings['boxShadow'], string> = {
    none: 'none',
    small: '0 2px 6px rgb(3 7 18 / 0.1)',
    medium: '0 8px 16px rgb(3 7 18 / 0.14)',
  }
  const boxShadow = shadowBySize[styleSettings.boxShadow]
  const alignedEdge: Record<StyleSettings['contentAlignment'], CSSProperties['alignItems']> = {
    left: 'flex-start',
    center: 'center',
    right: 'flex-end',
  }
  const containerStyle: CSSProperties = {
    color: textColor,
    background: backgroundColor,
    borderRadius: `${styleSettings.borderRadius}px`,
    padding: `${styleSettings.padding}px`,
    margin: `${styleSettings.margin}px`,
    borderStyle: 'solid',
    borderWidth: `${styleSettings.borderWidth}px`,
    borderColor: styleSettings.borderColor,
    boxShadow,
    fontFamily: styleSettings.fontFamily || 'inherit',
    textAlign: styleSettings.contentAlignment,
  }

  return (
    <div 
      className={isStacked ? 'max-w-sm mx-auto' : ''}
      style={containerStyle}
    >
      <div
        className={`flex ${isStacked ? 'flex-col' : 'items-start'} gap-4`}
        style={isStacked ? { alignItems: alignedEdge[styleSettings.contentAlignment] } : undefined}
      >
        {styleSettings.showIcon && (
          <div 
            className="flex-shrink-0 flex items-center justify-center"
            style={{ 
              backgroundColor: styleSettings.iconBackgroundColor,
              borderRadius: `${styleSettings.iconBorderRadius}%`,
              width: `${styleSettings.iconSize + 20}px`,
              height: `${styleSettings.iconSize + 20}px`,
            }}
          >
            <svg 
              fill="none" 
              stroke="currentColor" 
              viewBox="0 0 24 24"
              style={{ 
                width: `${styleSettings.iconSize}px`, 
                height: `${styleSettings.iconSize}px`,
                color: styleSettings.iconColor,
              }}
            >
              <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M15 17h5l-1.405-1.405A2.032 2.032 0 0118 14.158V11a6.002 6.002 0 00-4-5.659V5a2 2 0 10-4 0v.341C7.67 6.165 6 8.388 6 11v3.159c0 .538-.214 1.055-.595 1.436L4 17h5m6 0v1a3 3 0 11-6 0v-1m6 0H9" />
            </svg>
          </div>
        )}
        <div className="flex-1 min-w-0 w-full">
          <h4 
            className="font-semibold mb-3 text-base leading-snug"
            style={{ color: textColor, textWrap: 'balance' }}
          >
            {formSettings.formTitle || 'Get Notified When Available'}
          </h4>
          <div className={`flex ${isStacked ? 'flex-col' : ''} items-stretch gap-2`}>
            <input 
              type="email" 
              placeholder={formSettings.emailPlaceholder || 'Enter your email address'}
              aria-label="Email address preview"
              className={`${isStacked ? 'w-full' : 'flex-1 min-w-0'} px-3 py-2 text-base leading-normal`}
              style={{ 
                borderRadius: `${styleSettings.inputBorderRadius}px`,
                border: `${styleSettings.inputBorderWidth}px solid ${styleSettings.inputBorderColor}`,
                backgroundColor: styleSettings.inputBackgroundColor,
                color: styleSettings.inputTextColor,
                minHeight: '44px',
                height: '44px',
                flex: isStacked ? '0 0 auto' : '1 1 auto',
                boxSizing: 'border-box',
              }}
              readOnly
            />
            <button 
              type="button"
              className={`text-sm font-semibold leading-tight transition-colors ${isStacked ? 'w-full' : 'shrink-0'}`}
              style={{
                background: styleSettings.buttonStyle === 'filled' ? primaryColor : 'transparent',
                color: styleSettings.buttonStyle === 'filled' ? styleSettings.buttonTextColor : primaryColor,
                borderRadius: `${styleSettings.buttonBorderRadius}px`,
                border: `${styleSettings.buttonBorderWidth}px solid ${buttonBorderColor}`,
                padding: `${styleSettings.buttonPadding}px ${styleSettings.buttonPadding * 2}px`,
                minHeight: '44px',
                boxSizing: 'border-box',
                boxShadow: 'none',
                appearance: 'none',
              }}
            >
              {formSettings.buttonText || 'Notify Me'}
            </button>
          </div>
        </div>
      </div>
    </div>
  )
}

/** 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({ 
  styleSettings,
  formSettings,
  updateStyleSettings,
  updateFormSettings,
}: CustomizationTabProps) {
  const { isPro } = usePro()

  // Accordion state for custom styling sections
  const [expandedSections, setExpandedSections] = useState<Record<string, boolean>>({
    layout: false,
    colors: true,
    typography: false,
    containerStyling: false,
    iconStyling: false,
    buttonStyling: false,
    inputStyling: false,
    formContent: false,
  })

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

  const templates: Template[] = [
    ...stylePresets.map(preset => ({
      id: preset.id,
      name: preset.name,
      description: preset.description,
    })),
    {
      id: 'custom',
      name: 'Custom',
      description: 'Build your own style',
      icon: Palette,
      isPro: true,
      alwaysVisible: true,
    },
  ]

  // Apply a preset template
  const applyPreset = (presetId: string) => {
    updateStyleSettings('formDesign', presetId as FormDesignType)

    const preset = stylePresets.find(p => p.id === presetId)
    if (preset) {
      Object.entries(preset.config).forEach(([key, value]) => {
        if (value !== undefined) {
          updateStyleSettings(key as keyof StyleSettings, value as StyleSettings[keyof StyleSettings])
        }
      })
    }
  }

  return (
    <div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
      {/* Left Column - Templates + Settings */}
      <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 notification form
            </CardDescription>
          </CardHeader>
          <CardContent>
            <TemplateGrid
              templates={templates}
              selectedId={styleSettings.formDesign}
              onSelect={applyPreset}
              columns={3}
              size="sm"
              isPro={isPro}
            />
          </CardContent>
        </Card>

        <Card>
          <CardHeader>
            <CardTitle className="flex items-center gap-2">
              <Palette className="h-5 w-5" />
              Customize Design
            </CardTitle>
            <CardDescription>
              {isPro
                ? 'Fine-tune every aspect of your form design'
                : 'Customize the colors of your form design'}
            </CardDescription>
          </CardHeader>
          <CardContent className="space-y-0">

            {/* Colors — always available for brand matching */}
            <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">
                <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="Primary Color"
                    value={styleSettings.primaryColor}
                    onChange={(v) => updateStyleSettings('primaryColor', v)}
                    globalTokenId="primary"
                    featureDefault="#00226b"
                  />
                  <GlobalColorPicker
                    label="Text Color"
                    value={styleSettings.textColor}
                    onChange={(v) => updateStyleSettings('textColor', v)}
                    globalTokenId="text"
                    featureDefault="#1f2937"
                  />
                  <GlobalColorPicker
                    label="Card Background Color"
                    value={styleSettings.backgroundColor}
                    onChange={(v) => updateStyleSettings('backgroundColor', v)}
                    globalTokenId="background"
                    featureDefault="#f3f4f6"
                    fullWidth
                  />
                </div>
              </CollapsibleContent>
            </Collapsible>

            {!isPro && (
              <p className="text-sm text-muted-foreground py-4 border-t">
                For full customization control including layout, typography, spacing, borders, icons,
                buttons, and input fields, 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">
                  <span className="flex items-center gap-2">
                    <Layout className="h-4 w-4" />
                    Layout & Display
                  </span>
                  <div className="flex items-center gap-2">
                    <ProIndicator size="sm" />
                    <ChevronDown className={`h-4 w-4 transition-transform ${expandedSections.layout ? 'rotate-180' : ''}`} />
                  </div>
                </CollapsibleTrigger>
                <CollapsibleContent className="space-y-4 pt-2 pb-4">
                  <div className="space-y-2">
                    <Label htmlFor="formLayout">Form layout</Label>
                    <Select
                      value={styleSettings.formLayout}
                      onValueChange={(value: StyleSettings['formLayout']) => updateStyleSettings('formLayout', value)}
                    >
                      <SelectTrigger id="formLayout">
                        <SelectValue />
                      </SelectTrigger>
                      <SelectContent>
                        <SelectItem value="inline">Inline (horizontal)</SelectItem>
                        <SelectItem value="stacked">Stacked (vertical)</SelectItem>
                      </SelectContent>
                    </Select>
                  </div>

                  <div className="space-y-2">
                    <Label htmlFor="contentAlignment">Content alignment</Label>
                    <Select
                      value={styleSettings.contentAlignment}
                      onValueChange={(value: StyleSettings['contentAlignment']) => updateStyleSettings('contentAlignment', value)}
                    >
                      <SelectTrigger id="contentAlignment">
                        <SelectValue />
                      </SelectTrigger>
                      <SelectContent>
                        <SelectItem value="left">Left</SelectItem>
                        <SelectItem value="center">Center</SelectItem>
                        <SelectItem value="right">Right</SelectItem>
                      </SelectContent>
                    </Select>
                  </div>

                  <div className="space-y-2">
                    <Label htmlFor="buttonStyle">Button style</Label>
                    <Select
                      value={styleSettings.buttonStyle}
                      onValueChange={(value: StyleSettings['buttonStyle']) => updateStyleSettings('buttonStyle', value)}
                    >
                      <SelectTrigger id="buttonStyle">
                        <SelectValue />
                      </SelectTrigger>
                      <SelectContent>
                        <SelectItem value="filled">Filled</SelectItem>
                        <SelectItem value="outlined">Outlined</SelectItem>
                      </SelectContent>
                    </Select>
                  </div>

                  <div className="flex items-center justify-between">
                    <div className="space-y-0.5">
                      <Label htmlFor="showIcon">Show bell icon</Label>
                      <p className="text-sm text-muted-foreground">Display the notification bell in the form</p>
                    </div>
                    <Switch
                      id="showIcon"
                      checked={styleSettings.showIcon}
                      onCheckedChange={(checked) => updateStyleSettings('showIcon', checked)}
                    />
                  </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">
                    <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={styleSettings.fontFamily}
                      onChange={(v) => updateStyleSettings('fontFamily', v)}
                      globalTokenId="body"
                      featureDefault=""
                    />
                  </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">
                    <span className="flex items-center gap-2">
                      <Square className="h-4 w-4" />
                      Container Styling
                    </span>
                    <div className="flex items-center gap-2">
                      <ProIndicator size="sm" />
                      <ChevronDown className={`h-4 w-4 transition-transform ${expandedSections.containerStyling ? 'rotate-180' : ''}`} />
                    </div>
                  </CollapsibleTrigger>
                  <CollapsibleContent className="space-y-4 pt-2 pb-4">
                    <NumberStepper
                      label="Card Border Radius"
                      value={styleSettings.borderRadius}
                      onChange={(value) => updateStyleSettings('borderRadius', value)}
                      min={0}
                      max={20}
                      step={1}
                    />
                    <NumberStepper
                      label="Padding"
                      value={styleSettings.padding}
                      onChange={(value) => updateStyleSettings('padding', value)}
                      min={0}
                      max={48}
                      step={2}
                    />
                    <NumberStepper
                      label="Margin"
                      value={styleSettings.margin}
                      onChange={(value) => updateStyleSettings('margin', value)}
                      min={0}
                      max={48}
                      step={2}
                    />
                    <NumberStepper
                      label="Border Width"
                      value={styleSettings.borderWidth}
                      onChange={(value) => updateStyleSettings('borderWidth', value)}
                      min={0}
                      max={4}
                      step={1}
                    />
                    <GlobalColorPicker
                      label="Border Color"
                      value={styleSettings.borderColor}
                      onChange={(v) => updateStyleSettings('borderColor', v)}
                      featureDefault="#e5e7eb"
                    />
                    <div className="space-y-2">
                      <Label htmlFor="boxShadow">Card shadow</Label>
                      <Select
                        value={styleSettings.boxShadow}
                        onValueChange={(value: StyleSettings['boxShadow']) => updateStyleSettings('boxShadow', value)}
                      >
                        <SelectTrigger id="boxShadow">
                          <SelectValue />
                        </SelectTrigger>
                        <SelectContent>
                          <SelectItem value="none">None</SelectItem>
                          <SelectItem value="small">Small</SelectItem>
                          <SelectItem value="medium">Medium</SelectItem>
                        </SelectContent>
                      </Select>
                    </div>
                  </CollapsibleContent>
                </Collapsible>
              )}

              {/* Icon Styling — Pro */}
              {isPro && (
                <Collapsible open={expandedSections.iconStyling} onOpenChange={() => toggleSection('iconStyling')}>
                  <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">
                      <Bell className="h-4 w-4" />
                      Icon Styling
                    </span>
                    <div className="flex items-center gap-2">
                      <ProIndicator size="sm" />
                      <ChevronDown className={`h-4 w-4 transition-transform ${expandedSections.iconStyling ? 'rotate-180' : ''}`} />
                    </div>
                  </CollapsibleTrigger>
                  <CollapsibleContent className="space-y-4 pt-2 pb-4">
                    <div className="grid gap-4 sm:grid-cols-2">
                      <GlobalColorPicker
                        label="Icon Background Color"
                        value={styleSettings.iconBackgroundColor}
                        onChange={(v) => updateStyleSettings('iconBackgroundColor', v)}
                        featureDefault="#00226b"
                      />
                      <GlobalColorPicker
                        label="Icon Color"
                        value={styleSettings.iconColor}
                        onChange={(v) => updateStyleSettings('iconColor', v)}
                        featureDefault="#ffffff"
                      />
                    </div>
                    <NumberStepper
                      label="Icon Size"
                      value={styleSettings.iconSize}
                      onChange={(value) => updateStyleSettings('iconSize', value)}
                      min={12}
                      max={32}
                      step={1}
                    />
                    <NumberStepper
                      label="Icon Border Radius"
                      value={styleSettings.iconBorderRadius}
                      onChange={(value) => updateStyleSettings('iconBorderRadius', value)}
                      min={0}
                      max={50}
                      step={5}
                      unit="%"
                    />
                  </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">
                    <span className="flex items-center gap-2">
                      <MousePointer className="h-4 w-4" />
                      Button Styling
                    </span>
                    <div className="flex items-center gap-2">
                      <ProIndicator size="sm" />
                      <ChevronDown className={`h-4 w-4 transition-transform ${expandedSections.buttonStyling ? 'rotate-180' : ''}`} />
                    </div>
                  </CollapsibleTrigger>
                  <CollapsibleContent className="space-y-4 pt-2 pb-4">
                    <div className="grid gap-4 sm:grid-cols-2">
                      <GlobalColorPicker
                        label="Button Background Color"
                        value={styleSettings.primaryColor}
                        onChange={(v) => updateStyleSettings('primaryColor', v)}
                        globalTokenId="primary"
                        featureDefault="#00226b"
                      />
                      <GlobalColorPicker
                        label="Button Text Color"
                        value={styleSettings.buttonTextColor}
                        onChange={(v) => updateStyleSettings('buttonTextColor', v)}
                        featureDefault="#ffffff"
                      />
                      <GlobalColorPicker
                        label="Button Border Color"
                        value={styleSettings.buttonBorderColor || resolveGlobalColor(styleSettings.primaryColor, 'primary', '#00226b')}
                        onChange={(v) => updateStyleSettings('buttonBorderColor', v)}
                        featureDefault="#00226b"
                        fullWidth
                      />
                    </div>
                    <NumberStepper
                      label="Button Border Width"
                      value={styleSettings.buttonBorderWidth}
                      onChange={(value) => updateStyleSettings('buttonBorderWidth', value)}
                      min={0}
                      max={6}
                      step={1}
                    />
                    <NumberStepper
                      label="Button Border Radius"
                      value={styleSettings.buttonBorderRadius}
                      onChange={(value) => updateStyleSettings('buttonBorderRadius', value)}
                      min={0}
                      max={24}
                      step={1}
                    />
                    <NumberStepper
                      label="Button Padding"
                      value={styleSettings.buttonPadding}
                      onChange={(value) => updateStyleSettings('buttonPadding', value)}
                      min={4}
                      max={24}
                      step={2}
                    />
                  </CollapsibleContent>
                </Collapsible>
              )}

              {/* Input Field Styling — Pro */}
              {isPro && (
                <Collapsible open={expandedSections.inputStyling} onOpenChange={() => toggleSection('inputStyling')}>
                  <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">
                      <RectangleHorizontal className="h-4 w-4" />
                      Input Field Styling
                    </span>
                    <div className="flex items-center gap-2">
                      <ProIndicator size="sm" />
                      <ChevronDown className={`h-4 w-4 transition-transform ${expandedSections.inputStyling ? 'rotate-180' : ''}`} />
                    </div>
                  </CollapsibleTrigger>
                  <CollapsibleContent className="space-y-4 pt-2 pb-4">
                    <div className="grid gap-4 sm:grid-cols-2">
                      <GlobalColorPicker
                        label="Input Background Color"
                        value={styleSettings.inputBackgroundColor}
                        onChange={(v) => updateStyleSettings('inputBackgroundColor', v)}
                        featureDefault="#ffffff"
                      />
                      <GlobalColorPicker
                        label="Input Text Color"
                        value={styleSettings.inputTextColor}
                        onChange={(v) => updateStyleSettings('inputTextColor', v)}
                        featureDefault="#1f2937"
                      />
                      <GlobalColorPicker
                        label="Input Border Color"
                        value={styleSettings.inputBorderColor}
                        onChange={(v) => updateStyleSettings('inputBorderColor', v)}
                        featureDefault="#d1d5db"
                      />
                    </div>
                    <NumberStepper
                      label="Input Border Width"
                      value={styleSettings.inputBorderWidth}
                      onChange={(value) => updateStyleSettings('inputBorderWidth', value)}
                      min={0}
                      max={6}
                      step={1}
                    />
                    <NumberStepper
                      label="Input Border Radius"
                      value={styleSettings.inputBorderRadius}
                      onChange={(value) => updateStyleSettings('inputBorderRadius', value)}
                      min={0}
                      max={16}
                      step={1}
                    />
                  </CollapsibleContent>
                </Collapsible>
              )}

              {/* Form Content — Pro */}
              {isPro && (
                <Collapsible open={expandedSections.formContent} onOpenChange={() => toggleSection('formContent')}>
                  <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">
                      <FileText className="h-4 w-4" />
                      Form Content
                    </span>
                    <div className="flex items-center gap-2">
                      <ProIndicator size="sm" />
                      <ChevronDown className={`h-4 w-4 transition-transform ${expandedSections.formContent ? 'rotate-180' : ''}`} />
                    </div>
                  </CollapsibleTrigger>
                  <CollapsibleContent className="space-y-4 pt-2 pb-4">
                    <div className="space-y-2">
                      <Label htmlFor="formTitle">Form title</Label>
                      <Input
                        id="formTitle"
                        value={formSettings.formTitle}
                        onChange={(e) => updateFormSettings('formTitle', e.target.value)}
                        placeholder="Get notified when available"
                      />
                    </div>
                    <div className="space-y-2">
                      <Label htmlFor="emailPlaceholder">Email placeholder</Label>
                      <Input
                        id="emailPlaceholder"
                        value={formSettings.emailPlaceholder}
                        onChange={(e) => updateFormSettings('emailPlaceholder', e.target.value)}
                        placeholder="Enter your email address"
                      />
                    </div>
                    <div className="space-y-2">
                      <Label htmlFor="buttonText">Button text</Label>
                      <Input
                        id="buttonText"
                        value={formSettings.buttonText}
                        onChange={(e) => updateFormSettings('buttonText', e.target.value)}
                        placeholder="Notify Me"
                      />
                    </div>
                    <div className="space-y-2">
                      <Label htmlFor="successMessage">Success message</Label>
                      <Textarea
                        id="successMessage"
                        value={formSettings.successMessage}
                        onChange={(e) => updateFormSettings('successMessage', e.target.value)}
                        placeholder="You'll be notified when this product is back in stock."
                        rows={2}
                      />
                    </div>
                    <div className="space-y-2">
                      <Label htmlFor="alreadySubscribedMessage">Already subscribed message</Label>
                      <Textarea
                        id="alreadySubscribedMessage"
                        value={formSettings.alreadySubscribedMessage}
                        onChange={(e) => updateFormSettings('alreadySubscribedMessage', e.target.value)}
                        placeholder="You're already subscribed to notifications for this product."
                        rows={2}
                      />
                    </div>
                    <div className="space-y-2">
                      <Label htmlFor="errorMessage">Error message</Label>
                      <Textarea
                        id="errorMessage"
                        value={formSettings.errorMessage}
                        onChange={(e) => updateFormSettings('errorMessage', e.target.value)}
                        placeholder="Something went wrong. Please try again."
                        rows={2}
                      />
                    </div>
                  </CollapsibleContent>
                </Collapsible>
              )}

            </CardContent>
          </Card>
      </div>

      {/* Right Column - Sticky Preview */}
      <LivePreviewContainer
        title="Live Preview"
        description="How the form will appear on your product pages"
      >
        <FormPreview 
          styleSettings={styleSettings}
          formSettings={formSettings}
        />
      </LivePreviewContainer>
    </div>
  )
}
