/**
 * Ajax Search Customization Tab
 * Templates, Customize Design (accordion sections), Text Labels, and sticky preview
 */

import { useState } from 'react';
import { Label } from '@/components/ui/label';
import { Input } from '@/components/ui/input';
import { Switch } from '@/components/ui/switch';
import { Button } from '@/components/ui/button';
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
import { RadioGroup, RadioGroupItem } from '@/components/ui/radio-group';
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from '@/components/ui/select';
import {
  Collapsible,
  CollapsibleContent,
  CollapsibleTrigger,
} from '@/components/ui/collapsible';

import {
  Palette,
  LayoutTemplate,
  Type,
  Square,
  Eye,
  Image,
  Tag,
  DollarSign,
  Star,
  Package,
  FileText,
  Search,
  MessageSquare,
  Copy,
  Check,
  Code,
  ChevronDown,
  Settings,
  Columns,
  Minus,
  Plus,
  X,
} from 'lucide-react';
import { AjaxSearchSettings, SHADOW_OPTIONS, TEMPLATE_PRESETS } from '../config';
import { ProIndicator } from '@/components/pro/pro-indicator';
import { GlobalColorPicker, resolveGlobalColor } from '@/components/ui/global-color-picker';
import { GlobalTypographyPicker, resolveGlobalTypography } from '@/components/ui/global-typography-picker';
import { LivePreview as LivePreviewContainer } from '@/components/ui/live-preview';
import { cn } from '@/lib/utils';

interface CustomizationTabProps {
  settings: AjaxSearchSettings;
  setSettings: React.Dispatch<React.SetStateAction<AjaxSearchSettings>>;
  isPro: boolean;
}

/** 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>
  );
}

const SEARCH_PREVIEW_SHADOWS: Record<AjaxSearchSettings['boxShadow'], string> = {
  none: 'none',
  light: '0 1px 2px rgb(3 7 18 / 0.06)',
  medium: '0 8px 16px rgb(3 7 18 / 0.14)',
  heavy: '0 18px 32px rgb(3 7 18 / 0.18)',
};

function AjaxSearchPreview({ settings }: { settings: AjaxSearchSettings }) {
  const primaryColor = resolveGlobalColor(settings.primaryColor, 'primary', '#00226b');
  const textColor = resolveGlobalColor(settings.textColor, 'text', '#333333');
  const backgroundColor = resolveGlobalColor(settings.backgroundColor, 'background', '#ffffff');
  const borderColor = resolveGlobalColor(settings.inputBorderColor, 'border', '#dddddd');
  const isClassic = settings.template === 'classic';
  const isModal = settings.layout === 'modal';
  const borderRadius = settings.layout === 'fullwidth' || isClassic ? 0 : settings.borderRadius;
  const boxShadow = isClassic ? 'none' : SEARCH_PREVIEW_SHADOWS[settings.boxShadow];
  const fontFamily = resolveGlobalTypography(settings.fontFamily, 'body', 'inherit');
  const effectiveBorderColor = isClassic ? primaryColor : borderColor;

  const inputStyle: React.CSSProperties = {
    minHeight: `${settings.inputHeight}px`,
    color: textColor,
    backgroundColor,
    border: `${settings.inputBorderWidth}px solid ${effectiveBorderColor}`,
    borderRadius: `${borderRadius}px`,
    boxShadow,
    fontFamily,
    fontSize: `${settings.inputFontSize}px`,
  };
  const surfaceStyle: React.CSSProperties = {
    color: textColor,
    backgroundColor,
    border: `${settings.inputBorderWidth}px solid ${effectiveBorderColor}`,
    borderRadius: `${borderRadius}px`,
    boxShadow,
    fontFamily,
    fontSize: `${settings.fontSize}px`,
  };
  const resultsStyle: React.CSSProperties = isModal
    ? { ...surfaceStyle, border: 0, borderRadius: 0, boxShadow: 'none' }
    : surfaceStyle;
  const searchInputStyle: React.CSSProperties = isModal
    ? { ...inputStyle, boxShadow: 'none' }
    : inputStyle;

  const results = (
    <div className="overflow-hidden" style={resultsStyle}>
      {isModal && (
        <div className="border-b px-4 py-2 text-xs font-semibold text-gray-600">
          3 results for “sample”
        </div>
      )}
      <div
        className="grid p-2"
        style={{ gridTemplateColumns: `repeat(${settings.resultColumns}, minmax(0, 1fr))` }}
      >
        {['Sample Product', 'Another Product'].map((title, index) => (
          <div
            key={title}
            className="flex min-h-[72px] min-w-0 items-center gap-3 rounded-md p-3 text-left hover:bg-gray-50"
          >
            {settings.showImage && (
              <div className="relative h-14 w-14 shrink-0 overflow-hidden rounded-md bg-gray-100">
                {index === 0 && settings.showSaleBadge && (
                  <span className="absolute left-1 top-1 rounded bg-red-50 px-1 text-[9px] font-semibold text-red-700">
                    Sale
                  </span>
                )}
              </div>
            )}
            <div className="min-w-0 flex-1">
              <div
                className="break-words font-semibold leading-snug"
                style={{ color: textColor, fontSize: `${settings.titleFontSize}px` }}
              >
                {title}
              </div>
              {(settings.showCategories || settings.showSku || settings.showRating || settings.showStock) && (
                <div className="mt-1 flex flex-wrap items-center gap-x-2 gap-y-1 text-[10px] text-gray-500">
                  {settings.showCategories && <span>{index === 0 ? 'Electronics' : 'Clothing'}</span>}
                  {settings.showSku && <span>SKU: 12345</span>}
                  {settings.showRating && <span className="text-amber-600">★ 4.5</span>}
                  {settings.showStock && (
                    <span className="rounded bg-green-50 px-1.5 text-green-700">In Stock</span>
                  )}
                </div>
              )}
              {settings.showPrice && (
                <div
                  className="mt-1 flex flex-wrap items-baseline gap-1.5 font-semibold leading-snug tabular-nums"
                  style={{ color: primaryColor, fontSize: `${settings.fontSize}px` }}
                >
                  {index === 0 ? (
                    <>
                      <del className="font-normal text-gray-500">$99</del>
                      <ins className="bg-transparent no-underline">$79</ins>
                    </>
                  ) : '$49'}
                </div>
              )}
              {settings.showDescription && index === 0 && (
                <p className="mt-1 line-clamp-2 text-[11px] leading-normal text-gray-500">
                  This is a sample product description.
                </p>
              )}
            </div>
          </div>
        ))}
      </div>
      <div
        className="border-t bg-gray-50 px-3 py-2.5 text-center text-xs font-semibold"
        style={{ color: primaryColor }}
      >
        {settings.viewAllText} (3)
      </div>
    </div>
  );

  const searchField = (
    <div className={`flex items-stretch ${isClassic ? 'gap-0' : 'gap-2'}`}>
      <div className="flex min-w-0 flex-1 items-center" style={searchInputStyle}>
        <Search className="ml-3 h-5 w-5 shrink-0 text-gray-500" />
        <span className="min-w-0 flex-1 truncate px-3 text-left text-gray-500">
          {settings.placeholderText}
        </span>
      </div>
      {isModal && (
        <button
          type="button"
          aria-label="Close product search preview"
          className="mr-1 flex h-9 w-9 shrink-0 items-center justify-center rounded-md text-gray-500 hover:bg-gray-100"
        >
          <X className="h-4 w-4" />
        </button>
      )}
      {settings.showSearchButton && !isModal && (
        <button
          type="button"
          className="shrink-0 px-4 text-sm font-semibold text-white"
          style={{
            minHeight: `${settings.inputHeight}px`,
            backgroundColor: primaryColor,
            border: `1px solid ${primaryColor}`,
            borderRadius: `${borderRadius}px`,
          }}
        >
          {settings.searchButtonText}
        </button>
      )}
    </div>
  );

  if (isModal) {
    return (
      <div className="space-y-5">
        <div className="flex items-center gap-3 px-4" style={inputStyle}>
          <Search className="h-5 w-5 shrink-0 text-gray-500" />
          <span className="truncate text-gray-500">{settings.placeholderText}</span>
        </div>
        <div className="rounded-lg bg-gray-200 p-5">
          <div className="mx-auto max-w-md overflow-hidden" style={{ ...surfaceStyle, border: 0 }}>
            <div className="border-b p-3" style={{ backgroundColor }}>
              {searchField}
            </div>
            {results}
          </div>
        </div>
      </div>
    );
  }

  return (
    <div
      className={settings.layout === 'fullwidth' || settings.fullWidth ? 'w-full' : 'mx-auto w-full'}
      style={settings.layout === 'fullwidth' || settings.fullWidth ? undefined : { maxWidth: `${settings.maxWidth}px` }}
    >
      {searchField}
      <div className={settings.layout === 'fullwidth' ? 'mt-4' : 'mt-2'}>{results}</div>
    </div>
  );
}

export function AjaxSearchCustomizationTab({ settings, setSettings, isPro }: CustomizationTabProps) {
  const [copied, setCopied] = useState(false);
  const shortcode = '[swift_commerce_search]';

  const [expandedSections, setExpandedSections] = useState<Record<string, boolean>>({
    columns: false,
    colors: false,
    fieldStyle: false,
    borderEffects: false,
    typography: false,
    productInfo: false,
  });

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

  const copyShortcode = async () => {
    try {
      await navigator.clipboard.writeText(shortcode);
      setCopied(true);
      setTimeout(() => setCopied(false), 2000);
    } catch {
      const textArea = document.createElement('textarea');
      textArea.value = shortcode;
      document.body.appendChild(textArea);
      textArea.select();
      document.execCommand('copy');
      document.body.removeChild(textArea);
      setCopied(true);
      setTimeout(() => setCopied(false), 2000);
    }
  };

  return (
    <div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
      {/* Left Column - Settings */}
      <div className="space-y-6 min-w-0">
        {/* Templates */}
        <Card>
          <CardHeader>
            <CardTitle className="text-base flex items-center gap-2">
              <LayoutTemplate className="h-5 w-5 text-primary" />
              Templates
            </CardTitle>
            <CardDescription>
              Choose a design starting point. Customize further below.
            </CardDescription>
          </CardHeader>
          <CardContent>
            <RadioGroup
              value={settings.template}
              onValueChange={(value) => {
                const preset = TEMPLATE_PRESETS[value];
                if (preset) {
                  setSettings((prev) => ({ ...prev, ...preset, template: value as AjaxSearchSettings['template'] }));
                }
              }}
              className="grid grid-cols-3 gap-3"
            >
              {/* Modern Template */}
              <div>
                <RadioGroupItem value="modern" id="template-modern" className="peer sr-only" />
                <Label
                  htmlFor="template-modern"
                  className="flex flex-col rounded-lg border-2 border-muted bg-popover hover:bg-accent hover:text-accent-foreground peer-data-[state=checked]:border-primary [&:has([data-state=checked])]:border-primary cursor-pointer overflow-hidden"
                >
                  <div className="bg-muted/40 p-2.5 pb-2">
                    <div className="flex items-center gap-1.5 bg-white rounded-full shadow-md px-2 py-1.5">
                      <div className="w-2 h-2 rounded-full border border-gray-300" />
                      <div className="flex-1 h-1.5 rounded-full bg-gray-200" />
                    </div>
                    <div className="mt-1.5 bg-white rounded-xl shadow-sm p-1.5 space-y-1">
                      <div className="flex items-center gap-1.5">
                        <div className="w-4 h-4 rounded-md bg-gray-100 shrink-0" />
                        <div className="space-y-0.5 flex-1">
                          <div className="h-1 w-3/4 rounded bg-gray-200" />
                          <div className="h-0.5 w-1/2 rounded bg-gray-100" />
                        </div>
                      </div>
                      <div className="flex items-center gap-1.5">
                        <div className="w-4 h-4 rounded-md bg-gray-100 shrink-0" />
                        <div className="space-y-0.5 flex-1">
                          <div className="h-1 w-2/3 rounded bg-gray-200" />
                          <div className="h-0.5 w-1/3 rounded bg-gray-100" />
                        </div>
                      </div>
                    </div>
                  </div>
                  <div className="p-2 pt-1.5 text-center">
                    <span className="text-xs font-medium">Modern</span>
                    <p className="text-[10px] text-muted-foreground mt-0.5">Rounded, shadowed</p>
                  </div>
                </Label>
              </div>

              {/* Classic Template */}
              <div>
                <RadioGroupItem value="classic" id="template-classic" className="peer sr-only" />
                <Label
                  htmlFor="template-classic"
                  className="flex flex-col rounded-lg border-2 border-muted bg-popover hover:bg-accent hover:text-accent-foreground peer-data-[state=checked]:border-primary [&:has([data-state=checked])]:border-primary cursor-pointer overflow-hidden"
                >
                  <div className="bg-muted/40 p-2.5 pb-2">
                    <div className="flex items-center gap-1">
                      <div className="flex items-center gap-1 bg-white border-2 border-[#00226b] px-2 py-1.5 flex-1">
                        <div className="w-2 h-2 border border-gray-300" />
                        <div className="flex-1 h-1.5 bg-gray-200" />
                      </div>
                      <div className="bg-[#00226b] text-white px-1.5 py-1.5 text-[6px] font-medium shrink-0">Search</div>
                    </div>
                    <div className="mt-1.5 bg-white border border-gray-300 p-1.5 space-y-1">
                      <div className="flex items-center gap-1.5">
                        <div className="w-4 h-4 bg-gray-100 shrink-0" />
                        <div className="space-y-0.5 flex-1">
                          <div className="h-1 w-3/4 bg-gray-200" />
                          <div className="h-0.5 w-1/2 bg-gray-100" />
                        </div>
                      </div>
                      <div className="flex items-center gap-1.5 border-t border-gray-100 pt-1">
                        <div className="w-4 h-4 bg-gray-100 shrink-0" />
                        <div className="space-y-0.5 flex-1">
                          <div className="h-1 w-2/3 bg-gray-200" />
                          <div className="h-0.5 w-1/3 bg-gray-100" />
                        </div>
                      </div>
                    </div>
                  </div>
                  <div className="p-2 pt-1.5 text-center">
                    <span className="text-xs font-medium">Classic</span>
                    <p className="text-[10px] text-muted-foreground mt-0.5">Bordered, with button</p>
                  </div>
                </Label>
              </div>

              {/* Modal Template */}
              <div>
                <RadioGroupItem value="modal" id="template-modal" className="peer sr-only" />
                <Label
                  htmlFor="template-modal"
                  className="flex flex-col rounded-lg border-2 border-muted bg-popover hover:bg-accent hover:text-accent-foreground peer-data-[state=checked]:border-primary [&:has([data-state=checked])]:border-primary cursor-pointer overflow-hidden"
                >
                  <div className="bg-muted/40 p-2.5 pb-2">
                    <div className="relative bg-gray-200/60 rounded-md p-2 min-h-[52px] flex items-center justify-center">
                      <div className="bg-white rounded-xl shadow-lg p-2 w-full space-y-1.5">
                        <div className="flex items-center gap-1 bg-gray-50 rounded-full px-2 py-1">
                          <div className="w-2 h-2 rounded-full border border-gray-300" />
                          <div className="flex-1 h-1 rounded-full bg-gray-200" />
                        </div>
                        <div className="flex items-center gap-1.5">
                          <div className="w-3 h-3 rounded bg-gray-100 shrink-0" />
                          <div className="h-1 w-2/3 rounded bg-gray-200" />
                        </div>
                        <div className="flex items-center gap-1.5">
                          <div className="w-3 h-3 rounded bg-gray-100 shrink-0" />
                          <div className="h-1 w-1/2 rounded bg-gray-200" />
                        </div>
                      </div>
                    </div>
                  </div>
                  <div className="p-2 pt-1.5 text-center">
                    <span className="text-xs font-medium">Modal</span>
                    <p className="text-[10px] text-muted-foreground mt-0.5">Centered overlay</p>
                  </div>
                </Label>
              </div>
            </RadioGroup>
          </CardContent>
        </Card>

        {/* Customize Design */}
        <Card>
          <CardHeader>
            <CardTitle className="text-base flex items-center gap-2">
              <Settings className="h-5 w-5 text-primary" />
              Customize Design
            </CardTitle>
            <CardDescription>
              Fine-tune colors, typography, field styles, and product display.
            </CardDescription>
          </CardHeader>
          <CardContent className="space-y-0 -mx-1">
            {/* ── Columns & Width ── */}
            <Collapsible open={expandedSections.columns} onOpenChange={() => toggleSection('columns')}>
              <CollapsibleTrigger className="flex items-center justify-between w-full py-3 px-1 text-sm font-medium hover:text-primary border-t">
                <div className="flex items-center gap-2">
                  <Columns className="h-4 w-4" />
                  <span>Columns & Width</span>
                </div>
                <ChevronDown className={cn("h-4 w-4 transition-transform", expandedSections.columns && "rotate-180")} />
              </CollapsibleTrigger>
              <CollapsibleContent className="px-1 pb-4 space-y-4">
                {/* Result Columns */}
                <div className="flex items-center justify-between">
                  <div className="space-y-0.5">
                    <Label>Result Columns</Label>
                    <p className="text-xs text-muted-foreground">
                      Single or double column layout.
                    </p>
                  </div>
                  <Select
                    value={String(settings.resultColumns)}
                    onValueChange={(value) =>
                      setSettings((prev) => ({
                        ...prev,
                        resultColumns: parseInt(value) as 1 | 2,
                      }))
                    }
                  >
                    <SelectTrigger className="w-28 h-9 text-sm">
                      <SelectValue />
                    </SelectTrigger>
                    <SelectContent>
                      <SelectItem value="1">1 Column</SelectItem>
                      <SelectItem value="2">2 Columns</SelectItem>
                    </SelectContent>
                  </Select>
                </div>

                {/* Width Control - Hidden when fullwidth layout is selected */}
                {settings.layout !== 'fullwidth' && (
                  <>
                    <div className="flex items-center justify-between">
                      <div className="space-y-0.5">
                        <Label>Full Width</Label>
                        <p className="text-xs text-muted-foreground">
                          Expand search to fill container width.
                        </p>
                      </div>
                      <Switch
                        checked={settings.fullWidth}
                        onCheckedChange={(checked) =>
                          setSettings((prev) => ({ ...prev, fullWidth: checked }))
                        }
                      />
                    </div>

                    {!settings.fullWidth && (
                      <NumberStepper
                        label="Maximum Width"
                        value={settings.maxWidth}
                        onChange={(value) =>
                          setSettings((prev) => ({ ...prev, maxWidth: value }))
                        }
                        min={300}
                        max={1200}
                        step={50}
                      />
                    )}
                  </>
                )}
              </CollapsibleContent>
            </Collapsible>

            {/* ── Colors ── (Free) */}
            <Collapsible open={expandedSections.colors} onOpenChange={() => toggleSection('colors')}>
              <CollapsibleTrigger className="flex items-center justify-between w-full py-3 px-1 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={cn("h-4 w-4 transition-transform", expandedSections.colors && "rotate-180")} />
              </CollapsibleTrigger>
              <CollapsibleContent className="px-1 pb-4 space-y-4">
                <div className="grid gap-4 grid-cols-2">
                  {/* Primary Color */}
                  <GlobalColorPicker
                    label="Primary"
                    value={settings.primaryColor}
                    onChange={(v) => setSettings((prev) => ({ ...prev, primaryColor: v }))}
                    globalTokenId="primary"
                    featureDefault="#00226b"
                  />

                  {/* Secondary Color */}
                  <GlobalColorPicker
                    label="Secondary"
                    value={settings.secondaryColor}
                    onChange={(v) => setSettings((prev) => ({ ...prev, secondaryColor: v }))}
                    globalTokenId="secondary"
                    featureDefault="#153372"
                  />

                  {/* Text Color */}
                  <GlobalColorPicker
                    label="Text"
                    value={settings.textColor}
                    onChange={(v) => setSettings((prev) => ({ ...prev, textColor: v }))}
                    globalTokenId="text"
                    featureDefault="#333333"
                  />

                  {/* Background Color */}
                  <GlobalColorPicker
                    label="Background"
                    value={settings.backgroundColor}
                    onChange={(v) => setSettings((prev) => ({ ...prev, backgroundColor: v }))}
                    globalTokenId="background"
                    featureDefault="#ffffff"
                  />
                </div>
              </CollapsibleContent>
            </Collapsible>

            {/* Subtle upgrade nudge below colors for free users */}
            {!isPro && (
              <p className="text-sm text-muted-foreground px-1 py-3 border-t">
                For full customization control including typography, field styles, borders,
                and more, upgrade to Swift Commerce Pro.
              </p>
            )}

            {/* ── Field Style ── (Pro) */}
            {isPro && (
            <Collapsible open={expandedSections.fieldStyle} onOpenChange={() => toggleSection('fieldStyle')}>
              <CollapsibleTrigger className="flex items-center justify-between w-full py-3 px-1 text-sm font-medium hover:text-primary border-t">
                <div className="flex items-center gap-2">
                  <Type className="h-4 w-4" />
                  <span>Field Style</span>
                </div>
                <div className="flex items-center gap-2">
                  <ProIndicator size="sm" />
                  <ChevronDown className={cn("h-4 w-4 transition-transform", expandedSections.fieldStyle && "rotate-180")} />
                </div>
              </CollapsibleTrigger>
              <CollapsibleContent className="px-1 pb-4 space-y-5">
                {/* Input Height */}
                <NumberStepper
                  label="Input Height"
                  value={settings.inputHeight}
                  onChange={(value) =>
                    setSettings((prev) => ({ ...prev, inputHeight: value }))
                  }
                  min={36}
                  max={60}
                  step={2}
                />

                {/* Font Size */}
                <NumberStepper
                  label="Input Font Size"
                  value={settings.inputFontSize}
                  onChange={(value) =>
                    setSettings((prev) => ({ ...prev, inputFontSize: value }))
                  }
                  min={12}
                  max={20}
                  step={1}
                />

                {/* Border Settings */}
                <div className="grid gap-4 grid-cols-2">
                  <GlobalColorPicker
                    label="Border Color"
                    value={settings.inputBorderColor}
                    onChange={(value) =>
                      setSettings((prev) => ({ ...prev, inputBorderColor: value }))
                    }
                    globalTokenId="border"
                    featureDefault="#dddddd"
                  />

                  <GlobalColorPicker
                    label="Focus Color"
                    value={settings.inputFocusBorderColor}
                    onChange={(value) =>
                      setSettings((prev) => ({ ...prev, inputFocusBorderColor: value }))
                    }
                    globalTokenId="primary"
                    featureDefault="#2271b1"
                  />
                </div>

                {/* Border Width */}
                <NumberStepper
                  label="Border Width"
                  value={settings.inputBorderWidth}
                  onChange={(value) =>
                    setSettings((prev) => ({ ...prev, inputBorderWidth: value }))
                  }
                  min={0}
                  max={3}
                  step={1}
                />
              </CollapsibleContent>
            </Collapsible>
            )}

            {/* ── Border & Effects ── (Pro) */}
            {isPro && (
            <Collapsible open={expandedSections.borderEffects} onOpenChange={() => toggleSection('borderEffects')}>
              <CollapsibleTrigger className="flex items-center justify-between w-full py-3 px-1 text-sm font-medium hover:text-primary border-t">
                <div className="flex items-center gap-2">
                  <Square className="h-4 w-4" />
                  <span>Border & Effects</span>
                </div>
                <div className="flex items-center gap-2">
                  <ProIndicator size="sm" />
                  <ChevronDown className={cn("h-4 w-4 transition-transform", expandedSections.borderEffects && "rotate-180")} />
                </div>
              </CollapsibleTrigger>
              <CollapsibleContent className="px-1 pb-4 space-y-5">
                {/* Border Radius */}
                <NumberStepper
                  label="Border Radius"
                  value={settings.borderRadius}
                  onChange={(value) =>
                    setSettings((prev) => ({ ...prev, borderRadius: value }))
                  }
                  min={0}
                  max={24}
                  step={2}
                />

                {/* Box Shadow */}
                <div className="space-y-3">
                  <Label>Box Shadow</Label>
                  <RadioGroup
                    value={settings.boxShadow}
                    onValueChange={(value) =>
                      setSettings((prev) => ({
                        ...prev,
                        boxShadow: value as AjaxSearchSettings['boxShadow'],
                      }))
                    }
                    className="flex flex-wrap gap-4"
                  >
                    {SHADOW_OPTIONS.map((option) => (
                      <div key={option.value} className="flex items-center space-x-2">
                        <RadioGroupItem value={option.value} id={`shadow-${option.value}`} />
                        <Label htmlFor={`shadow-${option.value}`} className="cursor-pointer text-sm">
                          {option.label}
                        </Label>
                      </div>
                    ))}
                  </RadioGroup>
                </div>
              </CollapsibleContent>
            </Collapsible>
            )}

            {/* ── Typography ── (Pro) */}
            {isPro && (
            <Collapsible open={expandedSections.typography} onOpenChange={() => toggleSection('typography')}>
              <CollapsibleTrigger className="flex items-center justify-between w-full py-3 px-1 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={cn("h-4 w-4 transition-transform", expandedSections.typography && "rotate-180")} />
                </div>
              </CollapsibleTrigger>
              <CollapsibleContent className="px-1 pb-4 space-y-4">
                {/* Font Family — with global typography support */}
                <GlobalTypographyPicker
                  label="Font Family"
                  value={settings.fontFamily}
                  onChange={(value) => setSettings(prev => ({ ...prev, fontFamily: value }))}
                  globalTokenId="body"
                  featureDefault="inherit"
                />

                {/* Result Font Size */}
                <NumberStepper
                  label="Result Font Size"
                  value={settings.fontSize}
                  onChange={(value) =>
                    setSettings((prev) => ({ ...prev, fontSize: value }))
                  }
                  min={11}
                  max={18}
                  step={1}
                />

                {/* Title Font Size */}
                <NumberStepper
                  label="Product Title Size"
                  value={settings.titleFontSize}
                  onChange={(value) =>
                    setSettings((prev) => ({ ...prev, titleFontSize: value }))
                  }
                  min={12}
                  max={20}
                  step={1}
                />
              </CollapsibleContent>
            </Collapsible>
            )}

            {/* ── Product Information ── (Pro) */}
            {isPro && (
            <Collapsible open={expandedSections.productInfo} onOpenChange={() => toggleSection('productInfo')}>
              <CollapsibleTrigger className="flex items-center justify-between w-full py-3 px-1 text-sm font-medium hover:text-primary border-t">
                <div className="flex items-center gap-2">
                  <Eye className="h-4 w-4" />
                  <span>Product Information</span>
                </div>
                <div className="flex items-center gap-2">
                  <ProIndicator size="sm" />
                  <ChevronDown className={cn("h-4 w-4 transition-transform", expandedSections.productInfo && "rotate-180")} />
                </div>
              </CollapsibleTrigger>
              <CollapsibleContent className="px-1 pb-4 space-y-3">
                {/* Show Image */}
                <div className="flex items-center justify-between rounded-lg border p-3">
                  <div className="flex items-center gap-3">
                    <Image className="h-4 w-4 text-muted-foreground" />
                    <Label className="text-sm">Product Image</Label>
                  </div>
                  <Switch
                    checked={settings.showImage}
                    onCheckedChange={(checked) =>
                      setSettings((prev) => ({ ...prev, showImage: checked }))
                    }
                  />
                </div>

                {/* Show Price */}
                <div className="flex items-center justify-between rounded-lg border p-3">
                  <div className="flex items-center gap-3">
                    <DollarSign className="h-4 w-4 text-muted-foreground" />
                    <Label className="text-sm">Product Price</Label>
                  </div>
                  <Switch
                    checked={settings.showPrice}
                    onCheckedChange={(checked) =>
                      setSettings((prev) => ({ ...prev, showPrice: checked }))
                    }
                  />
                </div>

                {/* Show Description */}
                <div className="flex items-center justify-between rounded-lg border p-3">
                  <div className="flex items-center gap-3">
                    <FileText className="h-4 w-4 text-muted-foreground" />
                    <Label className="text-sm">Product Description</Label>
                  </div>
                  <Switch
                    checked={settings.showDescription}
                    onCheckedChange={(checked) =>
                      setSettings((prev) => ({ ...prev, showDescription: checked }))
                    }
                  />
                </div>

                {/* Description Length — shown when description is on */}
                {settings.showDescription && (
                  <div className="pl-4 border-l-2 border-muted ml-2">
                    <NumberStepper
                      label="Description Length"
                      value={settings.descriptionLength}
                      onChange={(value) =>
                        setSettings((prev) => ({ ...prev, descriptionLength: value }))
                      }
                      min={20}
                      max={200}
                      step={10}
                      unit=" chars"
                    />
                  </div>
                )}

                {/* Show Categories */}
                <div className="flex items-center justify-between rounded-lg border p-3">
                  <div className="flex items-center gap-3">
                    <Tag className="h-4 w-4 text-muted-foreground" />
                    <Label className="text-sm">Category Name</Label>
                  </div>
                  <Switch
                    checked={settings.showCategories}
                    onCheckedChange={(checked) =>
                      setSettings((prev) => ({ ...prev, showCategories: checked }))
                    }
                  />
                </div>

                {/* Show SKU */}
                <div className="flex items-center justify-between rounded-lg border p-3">
                  <div className="flex items-center gap-3">
                    <Package className="h-4 w-4 text-muted-foreground" />
                    <Label className="text-sm">SKU</Label>
                  </div>
                  <Switch
                    checked={settings.showSku}
                    onCheckedChange={(checked) =>
                      setSettings((prev) => ({ ...prev, showSku: checked }))
                    }
                  />
                </div>

                {/* Show Rating */}
                <div className="flex items-center justify-between rounded-lg border p-3">
                  <div className="flex items-center gap-3">
                    <Star className="h-4 w-4 text-muted-foreground" />
                    <Label className="text-sm">Product Rating</Label>
                  </div>
                  <Switch
                    checked={settings.showRating}
                    onCheckedChange={(checked) =>
                      setSettings((prev) => ({ ...prev, showRating: checked }))
                    }
                  />
                </div>

                {/* Show Stock */}
                <div className="flex items-center justify-between rounded-lg border p-3">
                  <div className="flex items-center gap-3">
                    <Package className="h-4 w-4 text-muted-foreground" />
                    <Label className="text-sm">Stock Status</Label>
                  </div>
                  <Switch
                    checked={settings.showStock}
                    onCheckedChange={(checked) =>
                      setSettings((prev) => ({ ...prev, showStock: checked }))
                    }
                  />
                </div>

                {/* Show Sale Badge */}
                <div className="flex items-center justify-between rounded-lg border p-3">
                  <div className="flex items-center gap-3">
                    <Tag className="h-4 w-4 text-muted-foreground" />
                    <Label className="text-sm">Sale Badge</Label>
                  </div>
                  <Switch
                    checked={settings.showSaleBadge}
                    onCheckedChange={(checked) =>
                      setSettings((prev) => ({ ...prev, showSaleBadge: checked }))
                    }
                  />
                </div>
              </CollapsibleContent>
            </Collapsible>
            )}
          </CardContent>
        </Card>

        {/* Text Labels - Free */}
        <Card>
          <CardHeader>
            <CardTitle className="text-base flex items-center gap-2">
              <MessageSquare className="h-5 w-5 text-primary" />
              Text Labels
            </CardTitle>
            <CardDescription>
              Customize the text shown in the search interface.
            </CardDescription>
          </CardHeader>
          <CardContent className="space-y-4">
            <div className="grid gap-4 grid-cols-2">
              <div className="space-y-2">
                <Label htmlFor="placeholderText">Placeholder Text</Label>
                <Input
                  id="placeholderText"
                  value={settings.placeholderText}
                  onChange={(e) =>
                    setSettings((prev) => ({ ...prev, placeholderText: e.target.value }))
                  }
                  placeholder="Search products..."
                  className="h-9 text-sm"
                />
              </div>
              <div className="space-y-2">
                <Label htmlFor="searchingText">Searching Text</Label>
                <Input
                  id="searchingText"
                  value={settings.searchingText}
                  onChange={(e) =>
                    setSettings((prev) => ({ ...prev, searchingText: e.target.value }))
                  }
                  placeholder="Searching..."
                  className="h-9 text-sm"
                />
              </div>
              <div className="space-y-2">
                <Label htmlFor="noResultsText">No Results Text</Label>
                <Input
                  id="noResultsText"
                  value={settings.noResultsText}
                  onChange={(e) =>
                    setSettings((prev) => ({ ...prev, noResultsText: e.target.value }))
                  }
                  placeholder="No products found"
                  className="h-9 text-sm"
                />
              </div>
              <div className="space-y-2">
                <Label htmlFor="viewAllText">View All Text</Label>
                <Input
                  id="viewAllText"
                  value={settings.viewAllText}
                  onChange={(e) =>
                    setSettings((prev) => ({ ...prev, viewAllText: e.target.value }))
                  }
                  placeholder="View all results"
                  className="h-9 text-sm"
                />
              </div>
            </div>
          </CardContent>
        </Card>
      </div>

      {/* Right Column - Sticky Preview */}
      <div className="relative">
        <div className="sticky top-[100px]">
          <LivePreviewContainer
            title="Live Preview"
            description="How the search widget will appear on your storefront"
          >
            <AjaxSearchPreview settings={settings} />
          </LivePreviewContainer>

          {/* Shortcode Section */}
          <Card className="mt-4">
            <CardHeader className="pb-3">
              <CardTitle className="text-base flex items-center gap-2">
                <Code className="h-5 w-5 text-primary" />
                Shortcode
              </CardTitle>
              <CardDescription>
                Use this shortcode to add the search widget anywhere on your site.
              </CardDescription>
            </CardHeader>
            <CardContent>
              <div className="flex items-center gap-2 rounded-lg border bg-muted/50 p-3">
                <code className="flex-1 font-mono text-sm">{shortcode}</code>
                <Button
                  variant="outline"
                  size="sm"
                  onClick={copyShortcode}
                  className="shrink-0"
                >
                  {copied ? (
                    <>
                      <Check className="h-4 w-4 mr-1 text-green-500" />
                      Copied!
                    </>
                  ) : (
                    <>
                      <Copy className="h-4 w-4 mr-1" />
                      Copy
                    </>
                  )}
                </Button>
              </div>
              <p className="mt-2 text-xs text-muted-foreground">
                The shortcode will use all the customization settings configured above.
                For Elementor users, use the Ajax Search widget instead.
              </p>
            </CardContent>
          </Card>
        </div>
      </div>
    </div>
  );
}
