/**
 * Appearance Preset Detail/Edit Page
 * 
 * Week 21 V2 Refactor - Stacked Layout:
 * 1. Basic Info (full width)
 * 2. Global Values (full width)
 * 3. General Chat View Section (settings + preview)
 * 4. Widget Sections (Calendar, Product, Contact, LeadForm, Survey, etc.)
 * 
 * @since 1.3.0
 * @updated 1.5.0 - Stacked layout refactor
 */

import { useState, useEffect, useMemo, useRef } from 'react'
import { useAppearanceFontCss } from '../hooks/useAppearanceFontCss'
import { useParams, useNavigate, useSearchParams } from 'react-router-dom'
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query'
import { ArrowRight, Save, Bot, Code, Type, AlertTriangle, Info } from 'lucide-react'
import { PageHeader } from '@/components/layout/PageHeader'
import { Card, CardHeader, CardTitle, CardContent } from '@/components/common/Card'
import { LinkedBotsSection } from '@/components/common/LinkedBotsSection'
import { 
    GeneralChatViewSection,
    CalendarWidgetSection,
    ProductCardSection,
    CartSection,
    ContactCardSection,
    LeadFormSection,
    SurveySection,
    WhatsAppSection,
    GallerySection,
    YouTubeSection,
    CouponSection,
    BundleBuilderSection,
} from '@/components/appearance/WidgetSections'
import { 
    PresetGlobalValues, 
    ElementSettings, 
    WidgetSettings,
    DEFAULT_GLOBAL_VALUES,
    DEFAULT_ELEMENT_SETTINGS,
    DEFAULT_WIDGET_SETTINGS,
    toDefaultRefSettings,
    migrateColorIds,
} from '@/types/appearance'
import { apiClient } from '@/api/client'
import { t, sprintf } from '@/lib/i18n'
import { useLanguage } from '@/contexts/LanguageContext'
import { DefaultPresetProvider } from '@/contexts/DefaultPresetContext'
import { UnsavedChangesModal } from '@/components/common/UnsavedChangesModal'
import { useUnsavedChanges } from '@/hooks/useUnsavedChanges'
import { PresetColorField } from '@/components/appearance/PresetColorField'
import { PresetTypographyField } from '@/components/appearance/PresetTypographyField'

interface AppearancePreset {
    id: number
    name: string
    slug: string
    description: string | null
    is_default: number
    is_system: number
    language?: string
    primary_color: string
    secondary_color: string
    background_color: string
    header_background: string
    header_text_color: string
    user_message_bg: string
    user_message_text: string
    bot_message_bg: string
    bot_message_text: string
    input_bg: string
    input_text: string
    input_border: string
    button_bg: string
    button_text: string
    button_hover_bg: string
    link_color: string
    font_family: string
    font_size_base: string
    font_size_header: string
    font_weight_normal: string
    font_weight_bold: string
    line_height: string
    letter_spacing: string
    bubble_size: string
    bubble_icon: string
    bubble_custom_icon: string | null
    bubble_animation: string
    window_width: string
    window_height: string
    window_border_radius: string
    window_shadow: string
    custom_css: string | null
    // Week 21 V2 - Visual Editor fields
    global_values: PresetGlobalValues | null
    element_settings: ElementSettings | null
    widget_settings: WidgetSettings | null
}

const defaultFormData: Partial<AppearancePreset> = {
    name: '',
    slug: '',
    description: '',
    primary_color: '#3BC2D0',
    secondary_color: '#E32774',
    background_color: '#FFFFFF',
    header_background: '#3BC2D0',
    header_text_color: '#FFFFFF',
    user_message_bg: '#3BC2D0',
    user_message_text: '#FFFFFF',
    bot_message_bg: '#F3F4F6',
    bot_message_text: '#1F2937',
    input_bg: '#FFFFFF',
    input_text: '#1F2937',
    input_border: '#E5E7EB',
    button_bg: '#3BC2D0',
    button_text: '#FFFFFF',
    button_hover_bg: '#2BA8B5',
    link_color: '#3BC2D0',
    font_family: 'inherit',
    font_size_base: '14px',
    font_size_header: '18px',
    font_weight_normal: '400',
    font_weight_bold: '600',
    line_height: '1.5',
    letter_spacing: 'normal',
    bubble_size: '60px',
    bubble_icon: 'robot',
    bubble_animation: 'pulse',
    window_width: '380px',
    window_height: '600px',
    window_border_radius: '16px',
    window_shadow: '0 10px 40px rgba(0,0,0,0.15)',
    custom_css: '',
    // New presets start with all non-color fields linked to the default preset
    global_values: null,
    element_settings: toDefaultRefSettings(DEFAULT_ELEMENT_SETTINGS),
    widget_settings: toDefaultRefSettings(DEFAULT_WIDGET_SETTINGS),
}

export function AppearancePresetDetail() {
    const { id } = useParams<{ id: string }>()
    const navigate = useNavigate()
    const [searchParams] = useSearchParams()
    const queryClient = useQueryClient()
    const { currentLanguage } = useLanguage()
    const isNew = !id || id === 'new'
    const returnTo = searchParams.get('returnTo')

    const [formData, setFormData] = useState<Partial<AppearancePreset>>(defaultFormData)
    const [isSaving, setIsSaving] = useState(false)
    const [showSavedAnimation, setShowSavedAnimation] = useState(false)
    const [showCustomCss, setShowCustomCss] = useState(false)
    const [isDataLoaded, setIsDataLoaded] = useState(false)
    // Redirect to archive when language changes while editing an existing entity
    const prevLangRef = useRef(currentLanguage)
    useEffect(() => {
        if (prevLangRef.current !== currentLanguage && !isNew) {
            navigate('/appearance-presets')
        }
        prevLangRef.current = currentLanguage
    }, [currentLanguage, isNew, navigate])

    // Fix: Prevent save-button flicker between "Saved" and "Unsaved" states.
    const justSavedRef = useRef(false)
    const saveCooldownRef = useRef(false)

    const { data: presetData, isLoading } = useQuery({
        queryKey: ['appearance-preset', id],
        queryFn: () => apiClient.get<{ data: { preset: AppearancePreset; custom_font_css?: string } }>(`appearance-presets/${id}`),
        enabled: !isNew,
    })

    // Fetch fallback global values (per-language scoped)
    const { data: globalValuesData } = useQuery({
        queryKey: ['appearance-global-values', currentLanguage],
        queryFn: () => apiClient.get<{ data: { global_values: PresetGlobalValues; custom_font_css?: string } }>('appearance-presets/global-values', { language: currentLanguage }),
    })

    // Fetch the default preset so non-default presets can show inherited values
    const { data: defaultPresetData } = useQuery({
        queryKey: ['appearance-presets-default', currentLanguage],
        queryFn: () => apiClient.get<{ data: { presets: AppearancePreset[] } }>(`appearance-presets?language=${currentLanguage}`),
        select: (data) => {
            const presets = data?.data?.presets || [];
            return presets.find((p: AppearancePreset) => p.is_default === 1) || null;
        },
    })

    const isCurrentDefault = !isNew && Number(formData.is_default) === 1;
    const defaultPresetContextValue = useMemo(() => ({
        isDefaultPreset: isCurrentDefault,
        defaultElementSettings: isCurrentDefault ? null : (defaultPresetData?.element_settings ?? null),
        defaultWidgetSettings: isCurrentDefault ? null : (defaultPresetData?.widget_settings ?? null),
    }), [isCurrentDefault, defaultPresetData]);

    const customFontCss = presetData?.data?.custom_font_css || globalValuesData?.data?.custom_font_css
    const fontCssVersion = useAppearanceFontCss(customFontCss)

    // IMPORTANT: Use the PRESET's own global_values first, then fallback to API defaults
    // This ensures the preview shows the correct colors for this specific preset
    // Deep merge with DEFAULT_GLOBAL_VALUES to ensure new typography scales are always available
    // System global values - these are the system-wide defaults that presets can link to
    const systemGlobalValues = globalValuesData?.data?.global_values ?? DEFAULT_GLOBAL_VALUES

    const rawGlobalValues = useMemo(() => {
        if (isDataLoaded && formData.global_values) {
            return formData.global_values;
        }
        if (presetData?.data?.preset?.global_values) {
            return presetData.data.preset.global_values;
        }
        return globalValuesData?.data?.global_values ?? DEFAULT_GLOBAL_VALUES;
    }, [isDataLoaded, formData.global_values, presetData, globalValuesData]);

    // Resolve preset-global links to system globals (persisted in global_values._links)
    const resolveSystemRef = (ref: string | undefined | null): unknown => {
        if (!ref || typeof ref !== 'string') return undefined;
        const parts = ref.split('.');
        let cur: any = systemGlobalValues ?? DEFAULT_GLOBAL_VALUES;
        for (const p of parts) {
            if (!cur || typeof cur !== 'object') return undefined;
            cur = cur[p];
        }
        return cur;
    };

    const globalValues: PresetGlobalValues = useMemo(() => ({
        ...DEFAULT_GLOBAL_VALUES,
        ...rawGlobalValues,
        typography: {
            ...DEFAULT_GLOBAL_VALUES.typography,
            ...rawGlobalValues.typography,
            // Preserve custom scales from the saved data
            custom: rawGlobalValues.typography?.custom ?? DEFAULT_GLOBAL_VALUES.typography.custom ?? [],
        },
        colors: {
            ...DEFAULT_GLOBAL_VALUES.colors,
            ...rawGlobalValues.colors,
            // Apply linked refs (if any) on top of saved values for runtime/preview consistency
            ...(Object.entries(((rawGlobalValues as any)?._links?.colors || {}) as Record<string, unknown>).reduce(
                (acc, [k, ref]) => {
                    if (typeof ref !== 'string' || !ref) return acc;
                    const v = resolveSystemRef(ref);
                    if (typeof v === 'string') acc[k] = v;
                    return acc;
                },
                {} as Record<string, string>
            )),
        },
        // Legacy sections: merge if present in raw data (backwards compat with old presets)
        ...((rawGlobalValues as any).effects ? { effects: (rawGlobalValues as any).effects } : {}),
        ...((rawGlobalValues as any).buttons ? { buttons: (rawGlobalValues as any).buttons } : {}),
        ...((rawGlobalValues as any).formFields ? { formFields: (rawGlobalValues as any).formFields } : {}),
        ...((rawGlobalValues as any).sizes ? { sizes: (rawGlobalValues as any).sizes } : {}),
        ...((rawGlobalValues as any).spacing ? { spacing: (rawGlobalValues as any).spacing } : {}),
        _links: (rawGlobalValues as any)?._links,
    }), [rawGlobalValues, systemGlobalValues]);

    const createPreset = useMutation({
        mutationFn: (data: Partial<AppearancePreset>) =>
            apiClient.post<{ data: { preset: AppearancePreset } }>('appearance-presets', { ...data, language: currentLanguage }),
        onSuccess: (result) => {
            queryClient.invalidateQueries({ queryKey: ['appearance-presets', currentLanguage] })
            if (result?.data?.preset?.id) {
                navigate(`/appearance-presets/${result.data.preset.id}`)
            }
        },
    })

    const updatePreset = useMutation({
        mutationFn: (data: Partial<AppearancePreset>) =>
            apiClient.put<{ data: { preset: AppearancePreset } }>(`appearance-presets/${id}`, data),
        onSuccess: () => {
            queryClient.invalidateQueries({ queryKey: ['appearance-presets', currentLanguage] })
            queryClient.invalidateQueries({ queryKey: ['appearance-preset', id] })
        },
    })

    useEffect(() => {
        if (presetData?.data?.preset) {
            if (justSavedRef.current) {
                justSavedRef.current = false
                return
            }
            const preset = presetData.data.preset
            if (preset.global_values?.colors?.custom) {
                const migrated = migrateColorIds(
                    preset.global_values,
                    preset.element_settings,
                    preset.widget_settings
                )
                if (migrated.migrated) {
                    setFormData({
                        ...preset,
                        global_values: migrated.globalValues,
                        element_settings: migrated.elementSettings,
                        widget_settings: migrated.widgetSettings,
                    })
                    setIsDataLoaded(true)
                    return
                }
            }
            setFormData(preset)
            setIsDataLoaded(true)
        }
    }, [presetData])

    const handleChange = (field: keyof AppearancePreset, value: string) => {
        setFormData((prev) => ({ ...prev, [field]: value }))
    }

    // Helper: update a single color in global_values using prev state (avoids stale closure bugs)
    const handleColorChange = (colorKey: string, value: string) => {
        setFormData((prev) => {
            const base = prev.global_values ?? globalValues;
            return {
                ...prev,
                global_values: {
                    ...base,
                    colors: {
                        ...(base as any).colors,
                        [colorKey]: value,
                    },
                },
            };
        });
    }

    // Helper: update a color link in global_values._links using prev state
    const handleColorLinkChange = (colorKey: string, ref: string | null | undefined) => {
        setFormData((prev) => {
            const base = (prev.global_values ?? globalValues) as any;
            const nextLinks = {
                ...(base._links || {}),
                colors: {
                    ...(base._links?.colors || {}),
                    [colorKey]: ref || undefined,
                },
            };
            return {
                ...prev,
                global_values: {
                    ...base,
                    _links: nextLinks,
                },
            };
        });
    }

    const handleSave = async () => {
        if (!formData.name) {
            alert(t('Please enter a name'))
            return
        }
        setIsSaving(true)
        try {
            if (isNew) {
                await createPreset.mutateAsync(formData)
            } else {
                await updatePreset.mutateAsync(formData)
                // Fix: Tell the load effect to skip overwriting formData on the next refetch
                justSavedRef.current = true
                // Show cute robot animation on successful save
                saveCooldownRef.current = true
                setShowSavedAnimation(true)
                setTimeout(() => {
                    setShowSavedAnimation(false)
                    saveCooldownRef.current = false
                }, 2000)
                // Reset original data after successful save
                setOriginalData()
            }
        } finally {
            setIsSaving(false)
        }
    }

    // Unsaved changes detection
    const {
        hasUnsavedChanges,
        checkNavigationSafe,
        setOriginalData,
        showModal: showUnsavedModal,
        saveError,
        modalActions,
    } = useUnsavedChanges({
        currentData: formData,
        onSave: async () => { await handleSave() },
        onDiscard: (original) => {
            setFormData(original)
        },
        isLoaded: isNew || isDataLoaded,
    })

    // Handle back navigation with unsaved changes check
    const handleBack = () => {
        checkNavigationSafe(() => {
            navigate(returnTo || '/appearance-presets')
        })
    }

    // Handle widget settings changes
    const handleWidgetSettingsChange = <K extends keyof WidgetSettings>(
        widgetKey: K,
        settings: WidgetSettings[K]
    ) => {
        const currentWidgetSettings = formData.widget_settings ?? DEFAULT_WIDGET_SETTINGS
        setFormData(prev => ({
            ...prev,
            widget_settings: {
                ...currentWidgetSettings,
                [widgetKey]: settings,
            },
        }))
    }

    // Handle saving a new global typography scale from a TypographyControl
    const handleSaveAsGlobalTypographyScale = (scale: { 
        id: string; 
        name: string; 
        fontSize: string; 
        fontWeight: string; 
        lineHeight: string; 
        textTransform: string; 
        fontStyle: string; 
        textDecoration: string; 
        letterSpacing: string; 
        textShadow: string;
    }) => {
        const currentCustomScales = globalValues.typography?.custom || []
        setFormData(prev => ({
            ...prev,
            global_values: {
                ...globalValues,
                typography: {
                    ...globalValues.typography,
                    custom: [
                        ...currentCustomScales,
                        scale,
                    ],
                },
            },
        }))
    }

    if (!isNew && isLoading) {
        return (
            <div className="flex items-center justify-center min-h-[400px]">
                <div className="animate-spin rounded-full h-12 w-12 border-b-2 border-primary-600" />
            </div>
        )
    }

    return (
        <DefaultPresetProvider value={defaultPresetContextValue}>
        <div className="space-y-6 animate-fade-in w-full">
            {/* Unsaved Changes Modal */}
            <UnsavedChangesModal
                isOpen={showUnsavedModal}
                onCancel={modalActions.onCancel}
                onDiscard={modalActions.onDiscard}
                onSave={modalActions.onSave}
                onSaveAlways={modalActions.onSaveAlways}
                isSaving={isSaving}
                errorMessage={saveError}
            />

            {/* Page Header */}
            <PageHeader
                title={isNew ? t('New Appearance Preset') : sprintf(t('Edit %s'), formData.name ?? '')}
                subtitle={isNew ? t('Create a new design for bots') : t('Edit appearance settings')}
            >
                <div className="flex gap-2">
                    <button
                        onClick={handleBack}
                        className="flex items-center gap-2 px-4 py-2 border border-gray-300 text-gray-700 rounded-lg hover:bg-gray-50 transition-colors"
                    >
                        <ArrowRight className="w-4 h-4" />
                        {t('Back')}
                    </button>
                    <button
                        onClick={handleSave}
                        disabled={isSaving || !formData.name}
                        className={`flex items-center gap-2 px-4 py-2 rounded-lg transition-all disabled:opacity-50 disabled:cursor-not-allowed ${
                            showSavedAnimation 
                                ? 'bg-green-500 hover:bg-green-600' 
                                : (hasUnsavedChanges && !saveCooldownRef.current)
                                    ? 'bg-amber-500 hover:bg-amber-600 animate-pulse'
                                    : 'bg-primary-600 hover:bg-primary-700'
                        } text-white`}
                    >
                        {showSavedAnimation ? (
                            <Bot className="w-4 h-4 animate-wiggle" />
                        ) : (
                            <Save className="w-4 h-4" />
                        )}
                        {isSaving ? t('Saving...') : showSavedAnimation ? t('Saved! ✓') : (hasUnsavedChanges && !saveCooldownRef.current) ? t('Save Changes') : t('Save')}
                    </button>
                </div>
            </PageHeader>

            {/* Unsaved changes indicator — suppressed during save animation cooldown */}
            {hasUnsavedChanges && !showSavedAnimation && !saveCooldownRef.current && (
                <div className="fixed bottom-4 left-4 bg-amber-100 text-amber-800 px-4 py-2 rounded-lg shadow-lg flex items-center gap-2 text-sm z-40">
                    <AlertTriangle className="w-4 h-4" />
                    {t('You have unsaved changes')}
                </div>
            )}

            {/* Global Default Template Banner */}
            {isCurrentDefault && (
                <div className="flex items-start gap-3 bg-indigo-50 border border-indigo-200 rounded-lg p-4">
                    <Info className="w-5 h-5 text-indigo-600 flex-shrink-0 mt-0.5" />
                    <div>
                        <p className="text-sm font-semibold text-indigo-800">
                            {t('Global Default Template')}
                        </p>
                        <p className="text-sm text-indigo-700 mt-1">
                            {t('This is the global default template. Changes here will affect all other presets in fields that haven\'t been manually customized.')}
                        </p>
                    </div>
                </div>
            )}

            {/* ============================================ */}
            {/* SECTION 1: Basic Info (Full Width) */}
            {/* ============================================ */}
            <Card>
                <CardHeader>
                    <CardTitle>{t('Basic Details')}</CardTitle>
                </CardHeader>
                <CardContent className="space-y-4">
                    <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                        <div>
                            <label className="block text-sm font-medium text-gray-700 mb-1">
                                {t('Name')} *
                            </label>
                            <input
                                type="text"
                                value={formData.name || ''}
                                onChange={(e) => handleChange('name', e.target.value)}
                                placeholder={t('e.g.: Dark theme')}
                                className="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-primary-500 focus:border-transparent"
                            />
                        </div>
                        <div>
                            <label className="block text-sm font-medium text-gray-700 mb-1">
                                {t('Slug')}
                            </label>
                            <input
                                type="text"
                                value={formData.slug || ''}
                                onChange={(e) => handleChange('slug', e.target.value)}
                                placeholder="dark-theme"
                                className="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-primary-500 focus:border-transparent"
                                dir="ltr"
                            />
                        </div>
                    </div>
                    <div>
                        <label className="block text-sm font-medium text-gray-700 mb-1">
                            {t('Description')}
                        </label>
                        <textarea
                            value={formData.description || ''}
                            onChange={(e) => handleChange('description', e.target.value)}
                            placeholder={t('Short description of the design')}
                            rows={2}
                            className="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-primary-500 focus:border-transparent resize-none"
                        />
                    </div>
                </CardContent>
            </Card>

            {/* ============================================ */}
            {/* SECTION 2: Preset Colors (Global Values) */}
            {/* ============================================ */}
            <Card>
                <CardHeader>
                    <CardTitle className="flex items-center gap-2">
                        <span className="text-2xl">🎨</span>
                        {t('Preset Colors')}
                    </CardTitle>
                </CardHeader>
                <CardContent>
                    <p className="text-sm text-gray-500 mb-4">
                        {t('Set the main colors for this preset. These colors serve as default values for all linked elements. You can link each color to a system global value or set a custom value.')}
                    </p>
                    <div style={{
                        display: 'grid',
                        gridTemplateColumns: 'repeat(auto-fill, minmax(220px, 1fr))',
                        gap: '16px',
                    }}>
                        {/* Primary Color */}
                        <PresetColorField
                            label={t('Primary Color')}
                            value={globalValues.colors?.primary || '#3BC2D0'}
                            colorKey="primary"
                            systemGlobalValues={systemGlobalValues}
                            defaultValue="#3BC2D0"
                            linkedRef={(formData.global_values as any)?._links?.colors?.primary || null}
                            onLinkChange={(ref) => handleColorLinkChange('primary', ref)}
                            onChange={(value) => handleColorChange('primary', value)}
                        />
                        
                        {/* Secondary Color */}
                        <PresetColorField
                            label={t('Secondary Color')}
                            value={globalValues.colors?.secondary || '#E32774'}
                            colorKey="secondary"
                            systemGlobalValues={systemGlobalValues}
                            defaultValue="#E32774"
                            linkedRef={(formData.global_values as any)?._links?.colors?.secondary || null}
                            onLinkChange={(ref) => handleColorLinkChange('secondary', ref)}
                            onChange={(value) => handleColorChange('secondary', value)}
                        />
                        
                        {/* Accent Color */}
                        <PresetColorField
                            label={t('Accent Color')}
                            value={globalValues.colors?.accent || '#6366F1'}
                            colorKey="accent"
                            systemGlobalValues={systemGlobalValues}
                            defaultValue="#6366F1"
                            linkedRef={(formData.global_values as any)?._links?.colors?.accent || null}
                            onLinkChange={(ref) => handleColorLinkChange('accent', ref)}
                            onChange={(value) => handleColorChange('accent', value)}
                        />
                        
                        {/* Text Color */}
                        <PresetColorField
                            label={t('Text Color')}
                            value={globalValues.colors?.text || '#1F2937'}
                            colorKey="text"
                            systemGlobalValues={systemGlobalValues}
                            defaultValue="#1F2937"
                            linkedRef={(formData.global_values as any)?._links?.colors?.text || null}
                            onLinkChange={(ref) => handleColorLinkChange('text', ref)}
                            onChange={(value) => handleColorChange('text', value)}
                        />
                        
                        {/* Text Muted Color */}
                        <PresetColorField
                            label={t('Muted Text')}
                            value={globalValues.colors?.textMuted || '#6B7280'}
                            colorKey="textMuted"
                            systemGlobalValues={systemGlobalValues}
                            defaultValue="#6B7280"
                            linkedRef={(formData.global_values as any)?._links?.colors?.textMuted || null}
                            onLinkChange={(ref) => handleColorLinkChange('textMuted', ref)}
                            onChange={(value) => handleColorChange('textMuted', value)}
                        />
                        
                        {/* Text Light Color */}
                        <PresetColorField
                            label={t('Light Text')}
                            value={globalValues.colors?.textLight || '#FFFFFF'}
                            colorKey="textLight"
                            systemGlobalValues={systemGlobalValues}
                            defaultValue="#FFFFFF"
                            linkedRef={(formData.global_values as any)?._links?.colors?.textLight || null}
                            onLinkChange={(ref) => handleColorLinkChange('textLight', ref)}
                            onChange={(value) => handleColorChange('textLight', value)}
                        />
                        
                        {/* Background Color */}
                        <PresetColorField
                            label={t('Background Color')}
                            value={globalValues.colors?.background || '#FFFFFF'}
                            colorKey="background"
                            systemGlobalValues={systemGlobalValues}
                            defaultValue="#FFFFFF"
                            linkedRef={(formData.global_values as any)?._links?.colors?.background || null}
                            onLinkChange={(ref) => handleColorLinkChange('background', ref)}
                            onChange={(value) => handleColorChange('background', value)}
                        />
                        
                        {/* Background Dark Color */}
                        <PresetColorField
                            label={t('Dark Background')}
                            value={globalValues.colors?.backgroundDark || '#1F2937'}
                            colorKey="backgroundDark"
                            systemGlobalValues={systemGlobalValues}
                            defaultValue="#1F2937"
                            linkedRef={(formData.global_values as any)?._links?.colors?.backgroundDark || null}
                            onLinkChange={(ref) => handleColorLinkChange('backgroundDark', ref)}
                            onChange={(value) => handleColorChange('backgroundDark', value)}
                        />
                        
                        {/* Surface Color */}
                        <PresetColorField
                            label={t('Surface')}
                            value={globalValues.colors?.surface || '#F9FAFB'}
                            colorKey="surface"
                            systemGlobalValues={systemGlobalValues}
                            defaultValue="#F9FAFB"
                            linkedRef={(formData.global_values as any)?._links?.colors?.surface || null}
                            onLinkChange={(ref) => handleColorLinkChange('surface', ref)}
                            onChange={(value) => handleColorChange('surface', value)}
                        />
                        
                        {/* Border Color */}
                        <PresetColorField
                            label={t('Borders')}
                            value={globalValues.colors?.border || '#E5E7EB'}
                            colorKey="border"
                            systemGlobalValues={systemGlobalValues}
                            defaultValue="#E5E7EB"
                            linkedRef={(formData.global_values as any)?._links?.colors?.border || null}
                            onLinkChange={(ref) => handleColorLinkChange('border', ref)}
                            onChange={(value) => handleColorChange('border', value)}
                        />
                        
                        {/* Success Color */}
                        <PresetColorField
                            label={t('Success')}
                            value={globalValues.colors?.success || '#10B981'}
                            colorKey="success"
                            systemGlobalValues={systemGlobalValues}
                            defaultValue="#10B981"
                            linkedRef={(formData.global_values as any)?._links?.colors?.success || null}
                            onLinkChange={(ref) => handleColorLinkChange('success', ref)}
                            onChange={(value) => handleColorChange('success', value)}
                        />
                        
                        {/* Warning Color */}
                        <PresetColorField
                            label={t('Warning')}
                            value={globalValues.colors?.warning || '#F59E0B'}
                            colorKey="warning"
                            systemGlobalValues={systemGlobalValues}
                            defaultValue="#F59E0B"
                            linkedRef={(formData.global_values as any)?._links?.colors?.warning || null}
                            onLinkChange={(ref) => handleColorLinkChange('warning', ref)}
                            onChange={(value) => handleColorChange('warning', value)}
                        />
                        
                        {/* Error Color */}
                        <PresetColorField
                            label={t('Error')}
                            value={globalValues.colors?.error || '#EF4444'}
                            colorKey="error"
                            systemGlobalValues={systemGlobalValues}
                            defaultValue="#EF4444"
                            linkedRef={(formData.global_values as any)?._links?.colors?.error || null}
                            onLinkChange={(ref) => handleColorLinkChange('error', ref)}
                            onChange={(value) => handleColorChange('error', value)}
                        />
                    </div>
                </CardContent>
            </Card>

            {/* ============================================ */}
            {/* SECTION 2.5: Preset Typography (Global Values) */}
            {/* ============================================ */}
            <Card key={`typography-${fontCssVersion}`}>
                <CardHeader>
                    <CardTitle className="flex items-center gap-2">
                        <Type className="w-5 h-5 text-gray-600" />
                        {t('Typography')}
                    </CardTitle>
                </CardHeader>
                <CardContent>
                    <p className="text-sm text-gray-500 mb-4">
                        {t('Set the main font for this preset. You can link to a system global value or set a custom font.')}
                    </p>
                    <PresetTypographyField
                        label={t('Primary Font Family')}
                        value={globalValues.typography}
                        systemGlobalValues={systemGlobalValues}
                        onChange={(typography) => setFormData(prev => ({
                            ...prev,
                            global_values: {
                                ...globalValues,
                                typography,
                            },
                        }))}
                    />
                </CardContent>
            </Card>

            {/* ============================================ */}
            {/* SECTION 3: General Chat View (Two Columns) */}
            {/* ============================================ */}
            {/* Key includes fontCssVersion to force re-render when custom fonts are loaded */}
            <GeneralChatViewSection
                key={`chat-view-${fontCssVersion}`}
                settings={formData.element_settings ?? null}
                globalValues={globalValues}
                onChange={(settings) => setFormData(prev => ({ ...prev, element_settings: settings }))}
                onSaveAsGlobalTypographyScale={handleSaveAsGlobalTypographyScale}
                presetLanguage={(formData as AppearancePreset).language || presetData?.data?.preset?.language || currentLanguage}
            />

            {/* ============================================ */}
            {/* SECTION 4+: Widget Sections */}
            {/* ============================================ */}
            {/* Key includes fontCssVersion to force re-render when custom fonts are loaded */}
            <div className="space-y-4" key={`widgets-${fontCssVersion}`}>
                <div className="flex items-center gap-3 mb-6">
                    <div className="h-px flex-1 bg-gradient-to-l from-transparent via-gray-300 to-transparent" />
                    <h2 className="text-lg font-semibold text-gray-700 px-4">
                        ⚡ {t('Widget Styling')}
                    </h2>
                    <div className="h-px flex-1 bg-gradient-to-r from-transparent via-gray-300 to-transparent" />
                </div>
                <p className="text-center text-sm text-gray-500 -mt-4 mb-6">
                    {t('Style each widget the bot displays in conversations - calendars, product cards, forms and more')}
                </p>

                {/* Calendar Widget */}
                <CalendarWidgetSection
                    settings={formData.widget_settings?.calendar ?? null}
                    globalValues={globalValues}
                    onChange={(settings) => handleWidgetSettingsChange('calendar', settings)}
                />

                {/* Product Card Widget */}
                <ProductCardSection
                    settings={formData.widget_settings?.productCard ?? null}
                    globalValues={globalValues}
                    onChange={(settings) => handleWidgetSettingsChange('productCard', settings)}
                />

                {/* Contact Card Widget */}
                <ContactCardSection
                    settings={formData.widget_settings?.contactCard ?? null}
                    globalValues={globalValues}
                    onChange={(settings) => handleWidgetSettingsChange('contactCard', settings)}
                />

                {/* Lead Form Widget */}
                <LeadFormSection
                    settings={formData.widget_settings?.leadForm ?? null}
                    globalValues={globalValues}
                    onChange={(settings) => handleWidgetSettingsChange('leadForm', settings)}
                />

                {/* Survey Widget */}
                <SurveySection
                    settings={formData.widget_settings?.survey ?? null}
                    globalValues={globalValues}
                    onChange={(settings) => handleWidgetSettingsChange('survey', settings)}
                />

                {/* WhatsApp Widget */}
                <WhatsAppSection
                    settings={formData.widget_settings?.whatsapp ?? null}
                    globalValues={globalValues}
                    onChange={(settings) => handleWidgetSettingsChange('whatsapp', settings)}
                />

                {/* Gallery Widget */}
                <GallerySection
                    settings={formData.widget_settings?.gallery ?? null}
                    globalValues={globalValues}
                    onChange={(settings) => handleWidgetSettingsChange('gallery', settings)}
                />

                {/* YouTube Widget */}
                <YouTubeSection
                    settings={formData.widget_settings?.youtube ?? null}
                    globalValues={globalValues}
                    onChange={(settings) => handleWidgetSettingsChange('youtube', settings)}
                />

                {/* WooCommerce Widgets — only shown when WooCommerce is active */}
                {(window as any).boostbotAdmin?.woocommerce_active && (
                    <>
                        {/* Coupon Widget */}
                        <CartSection
                            settings={formData.widget_settings?.cart ?? null}
                            globalValues={globalValues}
                            onChange={(settings) => handleWidgetSettingsChange('cart', settings)}
                        />

                        {/* Coupon Widget */}
                        <CouponSection
                            settings={formData.widget_settings?.coupon ?? null}
                            globalValues={globalValues}
                            onChange={(settings) => handleWidgetSettingsChange('coupon', settings)}
                        />

                        {/* Bundle Builder Widget */}
                        <BundleBuilderSection
                            settings={formData.widget_settings?.bundleBuilder ?? null}
                            globalValues={globalValues}
                            onChange={(settings) => handleWidgetSettingsChange('bundleBuilder', settings)}
                        />
                    </>
                )}
            </div>

            {/* ============================================ */}
            {/* SECTION: Custom CSS (Collapsible) */}
            {/* ============================================ */}
            <Card>
                <CardHeader>
                    <button
                        onClick={() => setShowCustomCss(!showCustomCss)}
                        className="w-full flex items-center justify-between"
                    >
                        <CardTitle className="flex items-center gap-2">
                            <Code className="w-5 h-5 text-gray-500" />
                            {t('Custom CSS')}
                        </CardTitle>
                        <span className="text-gray-400">
                            {showCustomCss ? '▲' : '▼'}
                        </span>
                    </button>
                </CardHeader>
                {showCustomCss && (
                    <CardContent className="pt-0">
                        <textarea
                            value={formData.custom_css || ''}
                            onChange={(e) => handleChange('custom_css', e.target.value)}
                            placeholder={`/* Custom CSS */
.boostbot-widget {
  /* Add styles here */
}`}
                            rows={12}
                            className="w-full px-4 py-3 border border-gray-300 rounded-lg font-mono text-sm bg-gray-50"
                            dir="ltr"
                        />
                        <p className="text-xs text-gray-500 mt-2">
                            {t('Add custom CSS that will apply to the bot. Caution: invalid CSS may cause display issues.')}
                        </p>
                    </CardContent>
                )}
            </Card>

            {/* Linked Bots Section - only show for existing presets */}
            {!isNew && (
                <LinkedBotsSection
                    entityType="appearance-preset"
                    entityId={Number(id)}
                />
            )}

            {/* Bottom Save Button */}
            <div className="flex justify-end pb-8">
                <button
                    onClick={handleSave}
                    disabled={isSaving || !formData.name}
                    className={`flex items-center gap-2 px-6 py-3 rounded-lg transition-all disabled:opacity-50 disabled:cursor-not-allowed ${
                        showSavedAnimation 
                            ? 'bg-green-500 hover:bg-green-600' 
                            : (hasUnsavedChanges && !saveCooldownRef.current)
                                ? 'bg-amber-500 hover:bg-amber-600 animate-pulse'
                                : 'bg-primary-600 hover:bg-primary-700'
                    } text-white shadow-lg hover:shadow-xl`}
                >
                    {showSavedAnimation ? (
                        <Bot className="w-5 h-5 animate-wiggle" />
                    ) : (
                        <Save className="w-5 h-5" />
                    )}
                    {isSaving ? t('Saving...') : showSavedAnimation ? t('Saved! ✓') : (hasUnsavedChanges && !saveCooldownRef.current) ? t('Save Changes') : t('Save')}
                </button>
            </div>
        </div>
        </DefaultPresetProvider>
    )
}
