/**
 * Bot Appearance Tab Component
 *
 * Read-only preview of the bot's linked appearance preset.
 * Users choose a preset from the dropdown; all style controls
 * are locked and point to the preset editor for editing.
 *
 * @since 1.5.0
 */

import React, { useMemo } from 'react';
import { Sparkles, Code, AlertCircle, Pencil } from 'lucide-react';
import { t } from '@/lib/i18n';
import { useLanguage } from '@/contexts/LanguageContext';
import { useAppearanceFontCss } from '../../hooks/useAppearanceFontCss';
import { Card, CardHeader, CardTitle, CardContent } from '@/components/common/Card';
import { 
    GeneralChatViewSection,
    CalendarWidgetSection,
    ProductCardSection,
    CartSection,
    ContactCardSection,
    LeadFormSection,
    SurveySection,
    WhatsAppSection,
    GallerySection,
    YouTubeSection,
    CouponSection,
    BundleBuilderSection,
} from '@/components/appearance/WidgetSections';
import { 
    PresetGlobalValues, 
    ElementSettings, 
    WidgetSettings,
    DEFAULT_GLOBAL_VALUES,
} from '@/types/appearance';
import type { BotFormData } from '@/types/bot';
import { mergeWidgetSettings } from '@/utils/appearanceMerge';

interface AvailablePreset {
    id: number;
    name: string;
    is_default?: number;
}

interface BotAppearanceTabProps {
    formData: BotFormData;
    /** Bot ID for return navigation */
    botId?: string | number;
    /** Full preset data - when provided, use its global_values and element_settings */
    selectedPreset?: {
        language?: string;
        global_values?: PresetGlobalValues;
        element_settings?: ElementSettings;
        widget_settings?: WidgetSettings;
        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;
        link_color?: string;
    } | null;
    /** System-wide global values for font fallback */
    systemGlobalValues?: PresetGlobalValues | null;
    /** Custom font CSS (e.g., Elementor @font-face) for preview rendering */
    customFontCss?: string | null;
    /** List of available presets for dropdown selection */
    availablePresets?: AvailablePreset[];
    onFieldChange: (field: keyof BotFormData, value: unknown) => void;
    onElementSettingsChange: (settings: ElementSettings) => void;
    onWidgetSettingsChange: <K extends keyof WidgetSettings>(key: K, settings: WidgetSettings[K]) => void;
}

export const BotAppearanceTab: React.FC<BotAppearanceTabProps> = ({
    formData,
    botId,
    selectedPreset,
    systemGlobalValues,
    customFontCss,
    availablePresets = [],
    onFieldChange,
    onElementSettingsChange,
    onWidgetSettingsChange,
}) => {
    const { currentLanguage } = useLanguage();
    const fontCssVersion = useAppearanceFontCss(customFontCss);

    const hasPreset = !!selectedPreset;

    const handlePresetChange = (presetId: number | null) => {
        onFieldChange('appearance_preset_id', presetId);
    };

    const navigateToPresetEditor = () => {
        if (formData.appearance_preset_id) {
            window.location.hash = `/appearance-presets/${formData.appearance_preset_id}?returnTo=/bots/${botId || 'new'}?tab=appearance`;
        }
    };

    const globalValues: PresetGlobalValues = useMemo(() => {
        if (selectedPreset) {
            const presetGV = selectedPreset.global_values;
            if (presetGV && Object.keys(presetGV).length > 0) {
                const presetFont = presetGV.typography?.fontFamily;
                const systemFont = systemGlobalValues?.typography?.fontFamily || DEFAULT_GLOBAL_VALUES.typography.fontFamily;
                const resolvedFont = (!presetFont || presetFont === 'inherit') ? systemFont : presetFont;

                const links = (presetGV as any)?._links?.colors || {};
                const linkedColors: Record<string, string> = {};
                for (const [key, ref] of Object.entries(links)) {
                    if (typeof ref !== 'string' || !ref) continue;
                    const parts = (ref as string).split('.');
                    let cur: any = systemGlobalValues ?? DEFAULT_GLOBAL_VALUES;
                    for (const p of parts) {
                        if (!cur || typeof cur !== 'object') { cur = undefined; break; }
                        cur = cur[p];
                    }
                    if (typeof cur === 'string') linkedColors[key] = cur;
                }

                return {
                    ...DEFAULT_GLOBAL_VALUES,
                    ...presetGV,
                    typography: {
                        ...DEFAULT_GLOBAL_VALUES.typography,
                        ...presetGV.typography,
                        custom: presetGV.typography?.custom ?? DEFAULT_GLOBAL_VALUES.typography?.custom ?? [],
                        fontFamily: resolvedFont,
                        heading: {
                            ...DEFAULT_GLOBAL_VALUES.typography?.heading,
                            ...presetGV.typography?.heading,
                            fontFamily: resolvedFont,
                        },
                        body: {
                            ...DEFAULT_GLOBAL_VALUES.typography?.body,
                            ...presetGV.typography?.body,
                            fontFamily: resolvedFont,
                        },
                        button: {
                            ...DEFAULT_GLOBAL_VALUES.typography?.button,
                            ...presetGV.typography?.button,
                            fontFamily: resolvedFont,
                        },
                    },
                    colors: {
                        ...DEFAULT_GLOBAL_VALUES.colors,
                        ...presetGV.colors,
                        ...linkedColors,
                    },
                    ...((presetGV as any).effects ? { effects: (presetGV as any).effects } : {}),
                    ...((presetGV as any).buttons ? { buttons: (presetGV as any).buttons } : {}),
                    ...((presetGV as any).formFields ? { formFields: (presetGV as any).formFields } : {}),
                    ...((presetGV as any).sizes ? { sizes: (presetGV as any).sizes } : {}),
                    ...((presetGV as any).spacing ? { spacing: (presetGV as any).spacing } : {}),
                    _links: (presetGV as any)?._links,
                } as PresetGlobalValues;
            }
            return {
                ...DEFAULT_GLOBAL_VALUES,
                colors: {
                    ...DEFAULT_GLOBAL_VALUES.colors,
                    primary: selectedPreset.primary_color || '#3BC2D0',
                    secondary: selectedPreset.secondary_color || '#E32774',
                    accent: selectedPreset.primary_color || '#3BC2D0',
                    background: selectedPreset.background_color || '#FFFFFF',
                    text: selectedPreset.bot_message_text || '#1F2937',
                    border: selectedPreset.input_border || '#E5E7EB',
                },
                typography: {
                    ...DEFAULT_GLOBAL_VALUES.typography,
                    fontFamily: systemGlobalValues?.typography?.fontFamily || DEFAULT_GLOBAL_VALUES.typography.fontFamily,
                },
            };
        }

        return {
            ...DEFAULT_GLOBAL_VALUES,
            colors: {
                ...DEFAULT_GLOBAL_VALUES.colors,
                primary: formData.primary_color || '#3BC2D0',
                secondary: formData.secondary_color || '#E32774',
                accent: formData.primary_color || '#3BC2D0',
                text: formData.bot_message_text || '#1F2937',
                background: formData.background_color || '#FFFFFF',
                border: formData.input_border || '#E5E7EB',
            },
            typography: {
                ...DEFAULT_GLOBAL_VALUES.typography,
                heading: {
                    fontFamily: formData.font_family || 'inherit',
                    fontSize: formData.font_size_header || '18px',
                    fontWeight: formData.font_weight_bold || '600',
                    lineHeight: formData.line_height || '1.5',
                },
                body: {
                    fontFamily: formData.font_family || 'inherit',
                    fontSize: formData.font_size_base || '14px',
                    fontWeight: formData.font_weight_normal || '400',
                    lineHeight: formData.line_height || '1.5',
                    letterSpacing: formData.letter_spacing || 'normal',
                },
            },
            buttons: {
                ...(DEFAULT_GLOBAL_VALUES.buttons ?? {}),
                primary: {
                    ...(DEFAULT_GLOBAL_VALUES.buttons?.primary ?? { background: '#3BC2D0', text: '#FFFFFF', hoverBackground: '#2BA8B5', borderRadius: '20px', padding: '8px 16px' }),
                    background: formData.button_bg || formData.primary_color || '#3BC2D0',
                    text: formData.button_text || '#FFFFFF',
                },
            },
            formFields: {
                ...(DEFAULT_GLOBAL_VALUES.formFields ?? {}),
                background: formData.input_bg || '#FFFFFF',
                text: formData.input_text || '#1F2937',
                border: formData.input_border || '#E5E7EB',
            },
        } as PresetGlobalValues;
    }, [formData, selectedPreset, systemGlobalValues]);

    const elementSettings: ElementSettings = useMemo(() => {
        const presetSettings = selectedPreset?.element_settings;

        if (presetSettings) {
            return {
                ...presetSettings,
                header: {
                    ...presetSettings.header,
                    title: formData.bot_name || presetSettings.header?.title || 'BoostBot',
                    subtitle: presetSettings.header?.subtitle || t('Online'),
                },
            };
        }

        if (selectedPreset) {
            const presetPrimary = selectedPreset.primary_color || '#3BC2D0';
            const presetBg = selectedPreset.background_color || '#FFFFFF';
            const presetHeaderBg = selectedPreset.header_background || presetPrimary;
            const presetHeaderText = selectedPreset.header_text_color || '#FFFFFF';

            return {
                chatBubble: {
                    size: { type: 'custom', value: '60px' },
                    background: { type: 'custom', value: presetPrimary },
                    margin: { type: 'custom', value: '20px' },
                    icon: 'robot' as const,
                    animation: 'pulse' as const,
                    position: 'bottom-right' as const,
                    iconColor: { type: 'custom', value: '#FFFFFF' },
                    iconSize: { type: 'custom', value: '24px' },
                    shadow: { type: 'custom', value: '0 4px 20px rgba(0,0,0,0.2)' },
                    borderType: 'none' as const,
                    borderWidth: { top: '0px', right: '0px', bottom: '0px', left: '0px' },
                    borderColor: { type: 'custom', value: 'transparent' },
                    borderRadius: { type: 'custom', value: '9999px' },
                },
                header: {
                    background: { type: 'custom', value: presetHeaderBg },
                    text: { type: 'custom', value: presetHeaderText },
                    height: { type: 'custom', value: '60px' },
                    padding: { type: 'custom', value: '16px' },
                    showCloseButton: true,
                    showMinimizeButton: true,
                    title: formData.bot_name || 'BoostBot',
                    subtitle: t('Online'),
                },
                chatWindow: {
                    width: { type: 'custom', value: '400px' },
                    height: { type: 'custom', value: '600px' },
                    background: { type: 'custom', value: presetBg },
                    borderRadius: { type: 'custom', value: '16px' },
                    shadow: { type: 'custom', value: '0 10px 40px rgba(0,0,0,0.15)' },
                    padding: { type: 'custom', value: '16px' },
                },
                userMessage: {
                    background: { type: 'custom', value: selectedPreset.user_message_bg || presetPrimary },
                    text: { type: 'custom', value: selectedPreset.user_message_text || '#FFFFFF' },
                    borderRadius: { type: 'custom', value: '12px' },
                    padding: { type: 'custom', value: '8px 12px' },
                    maxWidth: { type: 'custom', value: '80%' },
                    fontSize: { type: 'custom', value: '14px' },
                },
                botMessage: {
                    background: { type: 'custom', value: selectedPreset.bot_message_bg || '#F3F4F6' },
                    text: { type: 'custom', value: selectedPreset.bot_message_text || '#1F2937' },
                    borderRadius: { type: 'custom', value: '12px' },
                    padding: { type: 'custom', value: '8px 12px' },
                    maxWidth: { type: 'custom', value: '80%' },
                    fontSize: { type: 'custom', value: '14px' },
                    showAvatar: true,
                },
                inputArea: {
                    background: { type: 'custom', value: selectedPreset.input_bg || '#FFFFFF' },
                    text: { type: 'custom', value: selectedPreset.input_text || '#1F2937' },
                    border: { type: 'custom', value: selectedPreset.input_border || '#E5E7EB' },
                    borderRadius: { type: 'custom', value: '8px' },
                    padding: { type: 'custom', value: '8px 12px' },
                    placeholderColor: { type: 'custom', value: '#9CA3AF' },
                    placeholder: t('Write a message...'),
                    sendButtonBackground: { type: 'custom', value: selectedPreset.button_bg || presetPrimary },
                    sendButtonIcon: { type: 'custom', value: 'send' },
                    sendButtonHoverBackground: { type: 'custom', value: '#E32774' },
                    sendButtonHoverShadow: { type: 'custom', value: '0 1px 2px rgba(0,0,0,0.05)' },
                },
                typingIndicator: {
                    background: { type: 'custom', value: '#F3F4F6' },
                    dotColor: { type: 'custom', value: '#9CA3AF' },
                    dotSize: { type: 'custom', value: '8px' },
                    animationSpeed: { type: 'custom', value: '1.4s' },
                },
            };
        }

        return {
            chatBubble: {
                size: { type: 'custom', value: formData.bubble_size || '60px' },
                background: { type: 'custom', value: formData.primary_color || '#3BC2D0' },
                margin: { type: 'custom', value: '20px' },
                icon: (formData.bubble_icon || 'robot') as 'robot' | 'chat' | 'message' | 'sparkles' | 'headphones' | 'custom',
                customIconUrl: formData.bubble_custom_icon,
                animation: (formData.bubble_animation || 'none') as 'none' | 'pulse' | 'bounce' | 'shake' | 'glow' | 'wiggle' | 'float',
                position: (formData.position || 'bottom-right') as 'bottom-right' | 'bottom-left' | 'top-right' | 'top-left',
            },
            header: {
                background: { type: 'custom', value: formData.header_background || formData.primary_color || '#3BC2D0' },
                text: { type: 'custom', value: formData.header_text_color || '#FFFFFF' },
                height: { type: 'custom', value: '60px' },
                padding: { type: 'custom', value: '16px' },
                showCloseButton: true,
                showMinimizeButton: true,
                title: formData.bot_name || 'BoostBot',
                subtitle: t('Online'),
                typography: {
                    fontFamily: { type: 'custom', value: formData.font_family || 'inherit' },
                    fontSize: { type: 'custom', value: formData.font_size_header || '18px' },
                    fontWeight: { type: 'custom', value: formData.font_weight_bold || '600' },
                },
            },
            chatWindow: {
                width: { type: 'custom', value: formData.window_width || '400px' },
                height: { type: 'custom', value: formData.window_height || '600px' },
                background: { type: 'custom', value: formData.background_color || '#FFFFFF' },
                borderRadius: { type: 'custom', value: formData.window_border_radius || '16px' },
                shadow: { type: 'custom', value: formData.window_shadow || '0 10px 40px rgba(0,0,0,0.15)' },
                padding: { type: 'custom', value: '16px' },
            },
            userMessage: {
                background: { type: 'custom', value: formData.user_message_bg || '#3BC2D0' },
                text: { type: 'custom', value: formData.user_message_text || '#FFFFFF' },
                borderRadius: { type: 'custom', value: '12px' },
                padding: { type: 'custom', value: '8px 12px' },
                maxWidth: { type: 'custom', value: '80%' },
                fontSize: { type: 'custom', value: formData.font_size_base || '14px' },
                typography: {
                    fontFamily: { type: 'custom', value: formData.font_family || 'inherit' },
                    fontSize: { type: 'custom', value: formData.font_size_base || '14px' },
                    fontWeight: { type: 'custom', value: formData.font_weight_normal || '400' },
                    lineHeight: { type: 'custom', value: formData.line_height || '1.5' },
                },
            },
            botMessage: {
                background: { type: 'custom', value: formData.bot_message_bg || '#F3F4F6' },
                text: { type: 'custom', value: formData.bot_message_text || '#1F2937' },
                borderRadius: { type: 'custom', value: '12px' },
                padding: { type: 'custom', value: '8px 12px' },
                maxWidth: { type: 'custom', value: '80%' },
                fontSize: { type: 'custom', value: formData.font_size_base || '14px' },
                showAvatar: true,
                typography: {
                    fontFamily: { type: 'custom', value: formData.font_family || 'inherit' },
                    fontSize: { type: 'custom', value: formData.font_size_base || '14px' },
                    fontWeight: { type: 'custom', value: formData.font_weight_normal || '400' },
                    lineHeight: { type: 'custom', value: formData.line_height || '1.5' },
                },
            },
            inputArea: {
                background: { type: 'custom', value: formData.input_bg || '#FFFFFF' },
                text: { type: 'custom', value: formData.input_text || '#1F2937' },
                border: { type: 'custom', value: formData.input_border || '#E5E7EB' },
                borderRadius: { type: 'custom', value: '8px' },
                padding: { type: 'custom', value: '8px 12px' },
                placeholderColor: { type: 'custom', value: '#9CA3AF' },
                placeholder: t('Write a message...'),
                sendButtonBackground: { type: 'custom', value: formData.button_bg || formData.primary_color || '#3BC2D0' },
                sendButtonIcon: { type: 'custom', value: 'send' },
                sendButtonHoverBackground: { type: 'custom', value: formData.button_hover_bg || '#E32774' },
                sendButtonHoverShadow: { type: 'custom', value: '0 1px 2px rgba(0,0,0,0.05)' },
                typography: {
                    fontFamily: { type: 'custom', value: formData.font_family || 'inherit' },
                    fontSize: { type: 'custom', value: formData.font_size_base || '14px' },
                },
            },
            typingIndicator: {
                dotColor: { type: 'custom', value: formData.primary_color || '#3BC2D0' },
                background: { type: 'custom', value: formData.bot_message_bg || '#F3F4F6' },
                dotSize: { type: 'custom', value: '8px' },
                animationSpeed: { type: 'custom', value: '1.4s' },
            },
        };
    }, [formData, selectedPreset]);

    const widgetSettings: WidgetSettings = useMemo(() => {
        if (selectedPreset?.widget_settings) {
            return mergeWidgetSettings(selectedPreset.widget_settings);
        }
        return mergeWidgetSettings(formData.widget_settings);
    }, [formData.widget_settings, selectedPreset]);

    const [showCustomCss, setShowCustomCss] = React.useState(false);
    
    return (
        <div className="space-y-6 animate-fade-in w-full">
            {/* Preset Selection Card */}
            <Card className="border-2 border-gray-200 bg-white">
                <CardHeader>
                    <CardTitle className="flex items-center gap-2 text-lg">
                        <Sparkles className="w-5 h-5 text-primary" />
                        {t('Appearance Preset Selection')}
                    </CardTitle>
                </CardHeader>
                <CardContent>
                    <div className="flex items-center gap-4">
                        <div className="flex-1">
                            <label className="block text-sm font-medium text-gray-700 mb-2">
                                {t('Appearance Preset')}
                            </label>
                            <div className="flex items-center gap-3">
                                <select
                                    value={formData.appearance_preset_id || ''}
                                    onChange={(e) => handlePresetChange(e.target.value ? Number(e.target.value) : null)}
                                    className="flex-1 min-w-0 px-4 py-3 border border-gray-300 rounded-lg focus:ring-2 focus:ring-primary focus:border-primary text-base"
                                >
                                    <option value="">{t('-- Select appearance preset --')}</option>
                                    {availablePresets.map((preset) => (
                                        <option key={preset.id} value={preset.id}>
                                            {preset.name} {preset.is_default ? t('(default)') : ''}
                                        </option>
                                    ))}
                                </select>

                                {formData.appearance_preset_id && (
                                    <a
                                        href={`#/appearance-presets/${formData.appearance_preset_id}?returnTo=/bots/${botId || 'new'}?tab=appearance`}
                                        className="inline-flex items-center gap-2 px-3 py-2 rounded-lg bg-sky-100 text-sky-700 hover:bg-sky-200 hover:text-sky-800 transition-colors flex-shrink-0"
                                        title={t('Edit this appearance preset')}
                                    >
                                        <Pencil className="w-4 h-4" />
                                        <span className="text-sm font-medium">{t('Edit Preset')}</span>
                                    </a>
                                )}
                            </div>
                        </div>
                        <div className="flex flex-col gap-2 pt-6">
                            <a
                                href="#/appearance-presets"
                                className="text-sm text-primary hover:underline flex items-center gap-1"
                            >
                                <Sparkles className="w-4 h-4" />
                                {t('Manage Appearance Presets')}
                            </a>
                        </div>
                    </div>
                    {!formData.appearance_preset_id && (
                        <p className="mt-3 text-sm text-amber-600 flex items-center gap-2">
                            <AlertCircle className="w-4 h-4" />
                            {t('No appearance preset selected. The bot will use default values.')}
                        </p>
                    )}
                </CardContent>
            </Card>

            {/* General Chat View Section */}
            <GeneralChatViewSection
                key={`chat-view-${fontCssVersion}`}
                settings={elementSettings}
                globalValues={globalValues}
                onChange={onElementSettingsChange}
                disableSettingsPointerEvents={hasPreset}
                onLockedHoverActionClick={navigateToPresetEditor}
                presetLanguage={selectedPreset?.language || currentLanguage}
            />

            {/* Widget Sections */}
            <div className="space-y-4">
                <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 flex items-center gap-2">
                        <Sparkles className="w-5 h-5 text-yellow-500" />
                        {t('Widget Design')}
                    </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('Design each widget the bot displays in conversation - calendars, product cards, forms and more')}
                </p>

                <CalendarWidgetSection
                    settings={widgetSettings.calendar ?? null}
                    globalValues={globalValues}
                    disableSettingsPointerEvents={hasPreset}
                    onLockedHoverActionClick={navigateToPresetEditor}
                    onChange={(settings) => onWidgetSettingsChange('calendar', settings)}
                />

                <ProductCardSection
                    settings={widgetSettings.productCard ?? null}
                    globalValues={globalValues}
                    disableSettingsPointerEvents={hasPreset}
                    onLockedHoverActionClick={navigateToPresetEditor}
                    onChange={(settings) => onWidgetSettingsChange('productCard', settings)}
                />

                <ContactCardSection
                    settings={widgetSettings.contactCard ?? null}
                    globalValues={globalValues}
                    disableSettingsPointerEvents={hasPreset}
                    onLockedHoverActionClick={navigateToPresetEditor}
                    onChange={(settings) => onWidgetSettingsChange('contactCard', settings)}
                />

                <LeadFormSection
                    settings={widgetSettings.leadForm ?? null}
                    globalValues={globalValues}
                    disableSettingsPointerEvents={hasPreset}
                    onLockedHoverActionClick={navigateToPresetEditor}
                    onChange={(settings) => onWidgetSettingsChange('leadForm', settings)}
                />

                <SurveySection
                    settings={widgetSettings.survey ?? null}
                    globalValues={globalValues}
                    disableSettingsPointerEvents={hasPreset}
                    onLockedHoverActionClick={navigateToPresetEditor}
                    onChange={(settings) => onWidgetSettingsChange('survey', settings)}
                />

                <WhatsAppSection
                    settings={widgetSettings.whatsapp ?? null}
                    globalValues={globalValues}
                    disableSettingsPointerEvents={hasPreset}
                    onLockedHoverActionClick={navigateToPresetEditor}
                    onChange={(settings) => onWidgetSettingsChange('whatsapp', settings)}
                />

                <GallerySection
                    settings={widgetSettings.gallery ?? null}
                    globalValues={globalValues}
                    disableSettingsPointerEvents={hasPreset}
                    onLockedHoverActionClick={navigateToPresetEditor}
                    onChange={(settings) => onWidgetSettingsChange('gallery', settings)}
                />

                <YouTubeSection
                    settings={widgetSettings.youtube ?? null}
                    globalValues={globalValues}
                    disableSettingsPointerEvents={hasPreset}
                    onLockedHoverActionClick={navigateToPresetEditor}
                    onChange={(settings) => onWidgetSettingsChange('youtube', settings)}
                />

                {(window as any).boostbotAdmin?.woocommerce_active && (
                    <>
                        <CartSection
                            settings={widgetSettings.cart ?? null}
                            globalValues={globalValues}
                            disableSettingsPointerEvents={hasPreset}
                            onLockedHoverActionClick={navigateToPresetEditor}
                            onChange={(settings) => onWidgetSettingsChange('cart', settings)}
                        />

                        <CouponSection
                            settings={widgetSettings.coupon ?? null}
                            globalValues={globalValues}
                            disableSettingsPointerEvents={hasPreset}
                            onLockedHoverActionClick={navigateToPresetEditor}
                            onChange={(settings) => onWidgetSettingsChange('coupon', settings)}
                        />

                        <BundleBuilderSection
                            settings={widgetSettings.bundleBuilder ?? null}
                            globalValues={globalValues}
                            disableSettingsPointerEvents={hasPreset}
                            onLockedHoverActionClick={navigateToPresetEditor}
                            onChange={(settings) => onWidgetSettingsChange('bundleBuilder', settings)}
                        />
                    </>
                )}
            </div>

            {/* 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) => onFieldChange('custom_css', e.target.value)}
                            placeholder={`/* ${t('Custom CSS')} */
.boostbot-widget {
  /* ${t('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. Warning: invalid CSS may cause display issues.')}
                        </p>
                    </CardContent>
                )}
            </Card>
        </div>
    );
};

export default BotAppearanceTab;
