/**
 * Bot Detail/Edit Page
 * @since 1.1.0
 */

import { useState, useEffect, useMemo, useRef } from 'react'
import { useParams, useNavigate, useSearchParams } from 'react-router-dom'
import { t, sprintf } from '@/lib/i18n'
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'
import { ArrowRight, Save, Bot, Palette, MessageSquare, Settings, Target, AlertTriangle, Info, Puzzle, Sparkles, Users, Pencil, Link2, Link2Off, Zap, Plus, X, Loader2, AlertCircle, ShoppingCart } from 'lucide-react'
import { Link } from 'react-router-dom'
import { useBot, useBotStats, useCreateBot, useUpdateBot } from '@/hooks/useBots'
import { useUnsavedChanges } from '@/hooks/useUnsavedChanges'
import { PageHeader } from '@/components/layout/PageHeader'
import { Card, CardHeader, CardTitle, CardContent } from '@/components/common/Card'
import { ToggleSwitch } from '@/components/common/ToggleSwitch'
import { DisplayConditionsEditor } from '@/components/bots/DisplayConditionsEditor'
import { WidgetAssignment } from '@/components/bots/WidgetAssignment'
import { BotAppearanceTab } from '@/components/bots/BotAppearanceTab'
import { UnsavedChangesModal } from '@/components/common/UnsavedChangesModal'
import { apiClient } from '@/api/client'
import { useLanguage } from '@/contexts/LanguageContext'
import { widgetsApi } from '@/api/widgets'
import type { BotFormData, DisplayCondition, AppearanceOverrides, PersonalityOverrides } from '@/types/bot'
import { DEFAULT_APPEARANCE } from '@/types/bot'
import type { ElementSettings, WidgetSettings, PresetGlobalValues } from '@/types/appearance'
import { OpeningScreenConfig } from '@/components/widgets/OpeningScreenConfig'
import { useSettings } from '@/hooks/useSettings'

interface Personality {
    id: number
    name: string
    slug: string
    description: string | null
    system_prompt: string
    tone: string
    proactive_engagement: number
    proactive_delay_seconds: number
    custom_instructions: string | null
    is_default: number
    is_system: number
}

interface Tone {
    id: number
    name: string
    slug: string
    emoji: string
    description: string | null
}

interface ContactList {
    id: number
    name: string
    description: string | null
    is_primary: number
}

interface OpeningScreenAttachedFile {
    id: number
    name: string
    type: string
    url: string
    path: string
}

interface OpeningScreenPreset {
    id: number
    name: string
    slug: string
    description: string | null
    is_default: number
    is_system: number
    mode: 'questions_ai' | 'questions_answers' | 'departments'
    welcome_text: string | null
    show_welcome: number
    questions: Array<{ text: string; icon: string }>
    ai_instructions: string | null
    qa_pairs: Array<{ question: string; answer: string; icon: string }>
    contact_list_id: number | null
    show_departments: number
    show_contact_cards: number
    attached_files: OpeningScreenAttachedFile[]
}

type OpeningScreenSettings = Parameters<typeof OpeningScreenConfig>[0]['settings']

function toBool(v: unknown, fallback = false): boolean {
    if (typeof v === 'boolean') return v
    if (typeof v === 'number') return v === 1
    if (typeof v === 'string') return v === '1' || v.toLowerCase() === 'true'
    return fallback
}

function buildOpeningSettingsFromPreset(preset: OpeningScreenPreset | undefined, fallbackWelcome: string): OpeningScreenSettings {
    const mode = preset?.mode || 'questions_ai'
    const hasPreset = !!preset

    // IMPORTANT:
    // - When a preset is linked, the bot editor must reflect preset values exactly.
    // - Fallback to bot welcome message is only for "no preset" independent editing.
    const welcome_text = hasPreset ? (preset?.welcome_text ?? '') : (fallbackWelcome || '')

    return {
        mode,
        welcome_text,
        show_welcome: hasPreset ? toBool(preset?.show_welcome, true) : true,
        questions: (preset as any)?.questions || [],
        ai_instructions: (preset as any)?.ai_instructions || '',
        qa_pairs: (preset as any)?.qa_pairs || [],
        contact_list_id: (preset as any)?.contact_list_id ?? null,
        show_departments: hasPreset ? toBool((preset as any)?.show_departments, true) : true,
        show_contact_cards: hasPreset ? toBool((preset as any)?.show_contact_cards, true) : true,
        attached_files: (preset as any)?.attached_files || [],
    }
}

function isNonEmptyObject(v: unknown): v is Record<string, unknown> {
    return !!v && typeof v === 'object' && !Array.isArray(v) && Object.keys(v as Record<string, unknown>).length > 0
}

interface AppearancePreset {
    id: number
    name: string
    is_default: number
    is_system: number
    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
}

// Initialize personality overrides - all fields start as false (linked to personality)
const defaultPersonalityOverrides: PersonalityOverrides = {
    system_prompt: false,
    tone: false,
    proactive_engagement: false,
    proactive_delay_seconds: false,
    custom_instructions: false,
    rules: false,
    forbidden_topics: false,
}

// Initialize appearance overrides - all fields start as false (linked to preset)
const defaultAppearanceOverrides: AppearanceOverrides = {
    primary_color: false,
    secondary_color: false,
    background_color: false,
    header_background: false,
    header_text_color: false,
    user_message_bg: false,
    user_message_text: false,
    bot_message_bg: false,
    bot_message_text: false,
    input_bg: false,
    input_text: false,
    input_border: false,
    button_bg: false,
    button_text: false,
    button_hover_bg: false,
    link_color: false,
    font_family: false,
    font_size_base: false,
    font_size_header: false,
    font_weight_normal: false,
    font_weight_bold: false,
    line_height: false,
    letter_spacing: false,
    bubble_size: false,
    bubble_icon: false,
    bubble_animation: false,
    window_width: false,
    window_height: false,
    window_border_radius: false,
    window_shadow: false,
    custom_css: false,
}

const defaultFormData: BotFormData = {
    bot_name: '',
    bot_slug: '',
    description: '',
    is_active: true,
    test_mode: false,
    is_default: false,
    welcome_message: '',
    show_welcome_message: true,
    position: 'bottom-right',
    
    // Appearance preset
    appearance_preset_id: null,
    
    // Opening screen preset
    opening_screen_preset_id: null,
    opening_screen_overrides: null,
    
    // WooCommerce preset
    woocommerce_preset_id: null,
    
    // Colors
    primary_color: DEFAULT_APPEARANCE.primary_color,
    secondary_color: DEFAULT_APPEARANCE.secondary_color,
    background_color: DEFAULT_APPEARANCE.background_color,
    header_background: DEFAULT_APPEARANCE.header_background,
    header_text_color: DEFAULT_APPEARANCE.header_text_color,
    user_message_bg: DEFAULT_APPEARANCE.user_message_bg,
    user_message_text: DEFAULT_APPEARANCE.user_message_text,
    bot_message_bg: DEFAULT_APPEARANCE.bot_message_bg,
    bot_message_text: DEFAULT_APPEARANCE.bot_message_text,
    input_bg: DEFAULT_APPEARANCE.input_bg,
    input_text: DEFAULT_APPEARANCE.input_text,
    input_border: DEFAULT_APPEARANCE.input_border,
    button_bg: DEFAULT_APPEARANCE.button_bg,
    button_text: DEFAULT_APPEARANCE.button_text,
    button_hover_bg: DEFAULT_APPEARANCE.button_hover_bg,
    link_color: DEFAULT_APPEARANCE.link_color,
    
    // Typography
    font_family: DEFAULT_APPEARANCE.font_family,
    font_size_base: DEFAULT_APPEARANCE.font_size_base,
    font_size_header: DEFAULT_APPEARANCE.font_size_header,
    font_weight_normal: DEFAULT_APPEARANCE.font_weight_normal,
    font_weight_bold: DEFAULT_APPEARANCE.font_weight_bold,
    line_height: DEFAULT_APPEARANCE.line_height,
    letter_spacing: DEFAULT_APPEARANCE.letter_spacing,
    
    // Bubble
    bubble_icon: DEFAULT_APPEARANCE.bubble_icon,
    bubble_size: DEFAULT_APPEARANCE.bubble_size,
    bubble_custom_icon: DEFAULT_APPEARANCE.bubble_custom_icon,
    bubble_animation: DEFAULT_APPEARANCE.bubble_animation,
    
    // Window
    window_width: DEFAULT_APPEARANCE.window_width,
    window_height: DEFAULT_APPEARANCE.window_height,
    window_border_radius: DEFAULT_APPEARANCE.window_border_radius,
    window_shadow: DEFAULT_APPEARANCE.window_shadow,
    
    // Custom CSS
    custom_css: DEFAULT_APPEARANCE.custom_css,
    
    // Overrides
    appearance_overrides: defaultAppearanceOverrides,
    
    // Behavior / Personality
    personality_id: null,
    system_prompt: '',
    tone: 'friendly',
    proactive_engagement: false,
    proactive_delay_seconds: 4,
    personality_overrides: defaultPersonalityOverrides,
    custom_instructions: '',
    rules: '',
    forbidden_topics: '',
    contact_list_id: null,

    // Week 28: per-bot output cap (chars) - null means "use global"
    bot_output_char_limit: null,
}

function slugifyAscii(input: string): string {
    const slug = input
        .toLowerCase()
        .replace(/[^a-z0-9\s-]/g, '') // Remove non-ASCII (including Hebrew)
        .replace(/\s+/g, '-')
        .replace(/-+/g, '-')
        .replace(/^-|-$/g, '')

    return slug || `personality-${Date.now()}`
}

function LockedPersonalityCard({
    title,
    isLocked,
    onUnlockClick,
    children,
}: {
    title: string
    isLocked: boolean
    onUnlockClick: () => void
    children: React.ReactNode
}) {
    const [isHovered, setIsHovered] = useState(false)

    return (
        <div
            onMouseEnter={() => setIsHovered(true)}
            onMouseLeave={() => setIsHovered(false)}
            className="relative"
        >
            {isLocked && (
                <div
                    style={{
                        position: 'absolute',
                        inset: 0,
                        zIndex: 20,
                        opacity: isHovered ? 1 : 0,
                        pointerEvents: isHovered ? 'auto' : 'none',
                        transition: 'opacity 150ms ease',
                        background: 'rgba(255,255,255,0.55)',
                        backdropFilter: 'blur(1px)',
                        display: 'flex',
                        alignItems: 'center',
                        justifyContent: 'center',
                        padding: '24px',
                        borderRadius: 12,
                    }}
                >
                    <div style={{ textAlign: 'center', maxWidth: 360 }}>
                        <div style={{ fontSize: 13, color: '#374151', marginBottom: 12 }}>
                            {t('To edit here, unlink the setting for independent editing')}
                        </div>
                        <button
                            type="button"
                            onClick={(e) => {
                                e.stopPropagation()
                                onUnlockClick()
                            }}
                            style={{
                                display: 'inline-flex',
                                alignItems: 'center',
                                justifyContent: 'center',
                                gap: 8,
                                padding: '10px 14px',
                                borderRadius: 10,
                                border: 'none',
                                background: '#F59E0B', // amber-500
                                color: '#FFFFFF',
                                fontSize: 14,
                                fontWeight: 600,
                                cursor: 'pointer',
                                boxShadow: '0 6px 18px rgba(0,0,0,0.12)',
                            }}
                        >
                            {t('Unlink all for independent editing')}
                        </button>
                    </div>
                </div>
            )}

            <Card>
                <CardHeader>
                    <CardTitle>{title}</CardTitle>
                </CardHeader>
                <CardContent className={isLocked ? 'opacity-70 pointer-events-none' : ''}>
                    {children}
                </CardContent>
            </Card>
        </div>
    )
}

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

    // Redirect to archive when language changes while editing an existing entity
    const prevLangRef = useRef(currentLanguage)
    useEffect(() => {
        if (prevLangRef.current !== currentLanguage && !isNew) {
            navigate('/bots')
        }
        prevLangRef.current = currentLanguage
    }, [currentLanguage, isNew, navigate])

    const { data: botData, isLoading } = useBot(Number(id), { enabled: !isNew })
    const { data: botStatsData } = useBotStats({ enabled: isNew })
    const { data: settingsData } = useSettings(currentLanguage)
    const createBot = useCreateBot()
    const updateBot = useUpdateBot()
    const queryClient = useQueryClient()

    // Global default welcome text — per-language via settings endpoint
    const globalDefaultWelcomeText = settingsData?.data?.global_default_welcome_text || t('Hello! 👋 How can I help you today?')

    // Fetch personalities (full data for loading values)
    const { data: personalitiesData } = useQuery({
        queryKey: ['personalities', currentLanguage],
        queryFn: () => apiClient.get<{ data: { personalities: Personality[] } }>('personalities', { language: currentLanguage }),
    })

    // Fetch tones
    const { data: tonesData } = useQuery({
        queryKey: ['tones', currentLanguage],
        queryFn: () => apiClient.get<{ data: { tones: Tone[] } }>('tones', { language: currentLanguage }),
    })

    // Fetch contact lists for dropdown
    const { data: contactListsData } = useQuery({
        queryKey: ['contact-lists-dropdown'],
        queryFn: () => apiClient.get<{ data: { lists: ContactList[] } }>('contact-lists/dropdown'),
    })

    // Fetch appearance presets (full data for loading values)
    const { data: appearancePresetsData } = useQuery({
        queryKey: ['appearance-presets', currentLanguage],
        queryFn: () => apiClient.get<{ data: { presets: AppearancePreset[] } }>('appearance-presets', { language: currentLanguage }),
    })

    // Fetch system global values (for font fallback and custom font CSS)
    const { data: systemGlobalValuesData } = useQuery({
        queryKey: ['appearance-presets', 'global-values'],
        queryFn: () => apiClient.get<{ data: { global_values: PresetGlobalValues; custom_font_css?: string } }>('appearance-presets/global-values'),
    })

    // Fetch opening screen presets
    const { data: openingScreenPresetsData } = useQuery({
        queryKey: ['opening-screen-presets', currentLanguage],
        queryFn: () => apiClient.get<{ data: { presets: OpeningScreenPreset[] } }>('opening-screen-presets', { language: currentLanguage }),
    })

    // Fetch WooCommerce presets (only when WooCommerce is active)
    const wooCommerceActive = !!(window as any).boostbotAdmin?.woocommerce_active
    const { data: wooPresetsData } = useQuery({
        queryKey: ['woocommerce-presets', currentLanguage],
        queryFn: () => apiClient.get<{ data: { presets: { id: number; name: string; slug: string; is_default: number }[] } }>('woocommerce/presets', { language: currentLanguage }),
        enabled: wooCommerceActive,
    })

    const personalities = personalitiesData?.data?.personalities || []
    const contactLists = contactListsData?.data?.lists || []
    const appearancePresets = appearancePresetsData?.data?.presets || []
    const openingScreenPresets = openingScreenPresetsData?.data?.presets || []
    const tones = tonesData?.data?.tones || []
    const wooPresets = wooPresetsData?.data?.presets || []
    const systemGlobalValues = systemGlobalValuesData?.data?.global_values || null
    const customFontCss = systemGlobalValuesData?.data?.custom_font_css || null

    const [formData, setFormData] = useState<BotFormData>(defaultFormData)
    const [displayConditions, setDisplayConditions] = useState<DisplayCondition[]>([])
    const [activeTab, setActiveTab] = useState(tabFromUrl || 'basic')
    const [isSaving, setIsSaving] = useState(false)
    const [showSavedAnimation, setShowSavedAnimation] = useState(false)
    const [saveRequestError, setSaveRequestError] = useState<string | null>(null)
    const [isDataLoaded, setIsDataLoaded] = useState(false) // Track when form data is actually populated
    const [needsOriginalResetAfterServerSync, setNeedsOriginalResetAfterServerSync] = useState(false)
    const hasInitializedNewBotDisplayConditions = useRef(false)

    // Fetch selected WooCommerce preset details for the WooCommerce tab preview.
    const selectedWooPresetId = formData.woocommerce_preset_id
    const { data: selectedWooPresetData } = useQuery({
        queryKey: ['woocommerce-preset-detail', selectedWooPresetId],
        queryFn: () => apiClient.get<{ data: { preset: any } }>(`woocommerce/presets/${selectedWooPresetId}`),
        enabled: wooCommerceActive && !!selectedWooPresetId,
    })
    const selectedWooPreset = selectedWooPresetData?.data?.preset || null

    // Hover state for Opening Screen editor (for hover-to-unlock UX)
    const [isOpeningEditorHovered, setIsOpeningEditorHovered] = useState(false)

    // Personality preset (Personalities) - create preset from current bot behavior settings
    const [showCreatePersonalityPresetModal, setShowCreatePersonalityPresetModal] = useState(false)
    const [newPersonalityPresetName, setNewPersonalityPresetName] = useState('')

    const createPersonalityPresetMutation = useMutation({
        mutationFn: (data: {
            name: string
            slug: string
            description?: string
            system_prompt: string
            tone: string
            proactive_engagement: number
            is_default: number
        }) =>
            apiClient.post<{ success: boolean; data: { personality: { id: number; name: string } } }>(
                'personalities',
                { ...data, language: currentLanguage }
            ),
        onSuccess: (res) => {
            queryClient.invalidateQueries({ queryKey: ['personalities', currentLanguage] })
            const newId = res?.data?.personality?.id
            if (newId) {
                // Link bot to newly created personality preset; keep fields linked (no overrides)
                setFormData((prev) => ({
                    ...prev,
                    personality_id: Number(newId),
                    personality_overrides: defaultPersonalityOverrides,
                }))
            }
            setShowCreatePersonalityPresetModal(false)
            setNewPersonalityPresetName('')
        },
    })

    // Keep a snapshot of the last loaded/saved data so updates can send a minimal patch payload.
    // This avoids intermittent 400s when legacy/invalid fields exist but weren't changed in the current edit.
    const lastSavedFormDataRef = useRef<BotFormData | null>(null)
    const lastSavedDisplayConditionsRef = useRef<DisplayCondition[] | null>(null)

    // Fix: Prevent save-button flicker between "Saved" and "Unsaved" states.
    // justSavedRef: Tells the load effect to skip overwriting formData with server response
    //   right after a save (local data is authoritative during the save animation window).
    // saveCooldownRef: Synchronous guard that prevents hasUnsavedChanges from showing amber
    //   during the 2-second save animation, even across render boundaries.
    const justSavedRef = useRef(false)
    const saveCooldownRef = useRef(false)

    const jsonEqual = (a: unknown, b: unknown) => {
        try {
            return JSON.stringify(a) === JSON.stringify(b)
        } catch {
            return a === b
        }
    }

    const buildBotUpdatePatch = (
        current: BotFormData,
        original: BotFormData | null
    ): Partial<BotFormData> => {
        // For updates, we prefer sending a minimal patch. If the "last saved" snapshot
        // isn't available yet, return an empty patch rather than sending the full object
        // (which can re-send legacy invalid fields and cause backend 400 validation errors).
        if (!original) return {}
        const patch: Partial<BotFormData> = {}
        ;(Object.keys(current) as (keyof BotFormData)[]).forEach((key) => {
            const cur = current[key]
            const prev = original[key]
            const equal =
                typeof cur === 'object' || typeof prev === 'object'
                    ? jsonEqual(cur, prev)
                    : cur === prev
            if (!equal) {
                patch[key] = cur as any
            }
        })
        return patch
    }
    
    // New appearance system state (element_settings and widget_settings)
    // These are managed internally by BotAppearanceTab but we keep state here for future use
    const [, setElementSettings] = useState<ElementSettings | null>(null)
    const [, setWidgetSettings] = useState<WidgetSettings | null>(null)

    // Widget assignment tracking (controlled mode - manual save)
    const [assignedWidgetIds, setAssignedWidgetIds] = useState<number[]>([])
    const [widgetIdsLoaded, setWidgetIdsLoaded] = useState(false)
    const originalWidgetIdsRef = useRef<number[]>([])

    // Fetch assigned widget IDs for this bot
    const numericBotId = id ? Number(id) : NaN
    const hasValidBotId = !isNew && !!id && !isNaN(numericBotId) && numericBotId > 0
    const { data: assignedWidgetsData } = useQuery({
        queryKey: ['widgets', 'for-chatbot', numericBotId],
        queryFn: () => widgetsApi.getWidgetsForChatbot(numericBotId),
        enabled: hasValidBotId,
    })

    // Initialize widget assignment state from API — only on first load.
    // After initial load, local state is the source of truth; handleSave
    // updates originalWidgetIdsRef directly after persisting changes.
    // Running this on every refetch would overwrite the user's pending local
    // changes with stale server data (e.g. on window-focus refetch).
    useEffect(() => {
        if (!widgetIdsLoaded && assignedWidgetsData?.data?.widgets) {
            const ids = assignedWidgetsData.data.widgets.map((w: { id: number }) => w.id)
            setAssignedWidgetIds(ids)
            originalWidgetIdsRef.current = ids
            setWidgetIdsLoaded(true)
        }
    }, [assignedWidgetsData, widgetIdsLoaded])
    
    // Unsaved changes detection
    const {
        hasUnsavedChanges,
        checkNavigationSafe,
        setOriginalData,
        showModal: showUnsavedModal,
        saveError,
        modalActions,
    } = useUnsavedChanges({
        currentData: { formData, displayConditions, assignedWidgetIds },
        onSave: async () => { await handleSave() },
        onDiscard: (original) => {
            setFormData(original.formData)
            setDisplayConditions(original.displayConditions)
            setAssignedWidgetIds(original.assignedWidgetIds)
        },
        isLoaded: isNew || (isDataLoaded && (isNew || widgetIdsLoaded)), // For new bots, data is "loaded" immediately; for existing, wait for formData + widget IDs
    })

    // Set tab from URL if it changes
    useEffect(() => {
        if (tabFromUrl) {
            setActiveTab(tabFromUrl)
        }
    }, [tabFromUrl])

    // New bots: default "Display Conditions" should be empty unless this is the first bot in the system.
    // If there are 0 bots before creation, keep the current default behavior: show on homepage.
    useEffect(() => {
        if (!isNew) return
        if (hasInitializedNewBotDisplayConditions.current) return

        const totalBots = botStatsData?.data?.total
        if (typeof totalBots !== 'number') return

        const isHomepageOnlyDefault =
            displayConditions.length === 1 &&
            displayConditions[0]?.type === 'homepage' &&
            displayConditions[0]?.operator === 'include'

        if (totalBots === 0) {
            // First bot: default to homepage include (only if nothing already chosen).
            if (displayConditions.length === 0) {
                setDisplayConditions([
                    {
                        id: '__boostbot_default_homepage__',
                        type: 'homepage',
                        operator: 'include',
                    },
                ])
            }
        } else {
            // Not the first bot: default should be empty.
            // Also clear the current (wrong) homepage-only default if it exists.
            if (displayConditions.length === 0 || isHomepageOnlyDefault) {
                setDisplayConditions([])
            }
        }

        hasInitializedNewBotDisplayConditions.current = true
    }, [isNew, botStatsData, displayConditions])

    // Get selected preset name for display
    // Get the full selected preset with all data for BotAppearanceTab
    const selectedPreset = useMemo(() => {
        if (!formData.appearance_preset_id) return null
        const presetId = Number(formData.appearance_preset_id)
        const preset = appearancePresets.find(p => Number(p.id) === presetId) as (AppearancePreset & {
            global_values?: PresetGlobalValues
            element_settings?: ElementSettings
            widget_settings?: WidgetSettings
        }) | undefined
        return preset || null
    }, [formData.appearance_preset_id, appearancePresets])

    // Get selected personality object/name for display and linked-field fallback.
    const selectedPersonality = useMemo(() => {
        if (!formData.personality_id) return undefined
        const selectedId = Number(formData.personality_id)
        return personalities.find((p) => Number(p.id) === selectedId)
    }, [formData.personality_id, personalities])

    const selectedPersonalityName = selectedPersonality?.name

    const personalityUnlinkedCount = useMemo(() => {
        const o = formData.personality_overrides || defaultPersonalityOverrides
        const keys: (keyof PersonalityOverrides)[] = [
            'system_prompt',
            'tone',
            'proactive_engagement',
        ]
        return keys.filter((k) => !!o[k]).length
    }, [formData.personality_overrides])

    const isPersonalityLinked = !!formData.personality_id && personalityUnlinkedCount === 0

    // Get selected opening screen preset for display
    const selectedOpeningPreset = useMemo(() => {
        if (!formData.opening_screen_preset_id) return undefined
        return openingScreenPresets.find(p => Number(p.id) === Number(formData.opening_screen_preset_id))
    }, [formData.opening_screen_preset_id, openingScreenPresets])

    // Opening screen link state (linked to preset vs per-bot overrides)
    const hasOpeningPreset = !!formData.opening_screen_preset_id
    const isOpeningUnlinked = hasOpeningPreset && isNonEmptyObject(formData.opening_screen_overrides)
    const isOpeningLinked = hasOpeningPreset && !isOpeningUnlinked

    // Derived effective opening settings for editor
    const effectiveOpeningSettings: OpeningScreenSettings = useMemo(() => {
        if (isNonEmptyObject(formData.opening_screen_overrides)) {
            return formData.opening_screen_overrides as unknown as OpeningScreenSettings
        }
        return buildOpeningSettingsFromPreset(selectedOpeningPreset, formData.welcome_message)
    }, [formData.opening_screen_overrides, selectedOpeningPreset, formData.welcome_message])

    // Create Opening Preset modal state
    const [showCreateOpeningPresetModal, setShowCreateOpeningPresetModal] = useState(false)
    const [newOpeningPresetName, setNewOpeningPresetName] = useState('')

    const createOpeningPresetMutation = useMutation({
        mutationFn: (data: any) => apiClient.post('opening-screen-presets', { ...data, language: currentLanguage }),
        onSuccess: (res: any) => {
            queryClient.invalidateQueries({ queryKey: ['opening-screen-presets', currentLanguage] })
            const newId = res?.data?.preset?.id
            if (newId) {
                // Link bot to newly created preset and relink (clear overrides)
                setFormData((prev) => ({
                    ...prev,
                    opening_screen_preset_id: Number(newId),
                    opening_screen_overrides: null,
                }))
            }
            setShowCreateOpeningPresetModal(false)
            setNewOpeningPresetName('')
        },
    })

    // Load existing bot data
    useEffect(() => {
        if (botData?.data?.bot) {
            const bot = botData.data.bot
            
            // Parse appearance_overrides if it's a string
            let overrides = defaultAppearanceOverrides
            if (bot.appearance_overrides) {
                try {
                    overrides = typeof bot.appearance_overrides === 'string'
                        ? JSON.parse(bot.appearance_overrides)
                        : bot.appearance_overrides
                } catch {
                    overrides = defaultAppearanceOverrides
                }
            }

            // Parse personality_overrides if it's a string
            let personalityOverrides = defaultPersonalityOverrides
            if (bot.personality_overrides) {
                try {
                    personalityOverrides = typeof bot.personality_overrides === 'string'
                        ? JSON.parse(bot.personality_overrides)
                        : bot.personality_overrides
                } catch {
                    personalityOverrides = defaultPersonalityOverrides
                }
            }

            const nextFormData: BotFormData = {
                bot_name: bot.bot_name || '',
                bot_slug: bot.bot_slug || '',
                description: bot.description || '',
                is_active: bot.is_active === true || bot.is_active === 1 || bot.is_active === '1',
                test_mode: bot.test_mode === true || bot.test_mode === 1 || bot.test_mode === '1',
                is_default: bot.is_default === true || bot.is_default === 1 || bot.is_default === '1',
                welcome_message: bot.welcome_message || '',
                show_welcome_message: bot.show_welcome_message === true || bot.show_welcome_message === 1 || (bot.show_welcome_message as any) === '1' || bot.show_welcome_message === null,
                position: bot.position || defaultFormData.position,
                
                // Appearance preset
                appearance_preset_id: bot.appearance_preset_id || null,
                
                // Opening screen preset
                opening_screen_preset_id: bot.opening_screen_preset_id || null,
                opening_screen_overrides: (() => {
                    const raw = (bot as any).opening_screen_overrides
                    if (!raw) return null
                    try {
                        if (typeof raw === 'string') return JSON.parse(raw)
                        if (typeof raw === 'object') return raw as Record<string, unknown>
                        return null
                    } catch {
                        return null
                    }
                })(),
                
                // Colors
                primary_color: bot.primary_color || DEFAULT_APPEARANCE.primary_color,
                secondary_color: bot.secondary_color || DEFAULT_APPEARANCE.secondary_color,
                background_color: bot.background_color || DEFAULT_APPEARANCE.background_color,
                header_background: bot.header_background || DEFAULT_APPEARANCE.header_background,
                header_text_color: bot.header_text_color || DEFAULT_APPEARANCE.header_text_color,
                user_message_bg: bot.user_message_bg || DEFAULT_APPEARANCE.user_message_bg,
                user_message_text: bot.user_message_text || DEFAULT_APPEARANCE.user_message_text,
                bot_message_bg: bot.bot_message_bg || DEFAULT_APPEARANCE.bot_message_bg,
                bot_message_text: bot.bot_message_text || DEFAULT_APPEARANCE.bot_message_text,
                input_bg: bot.input_bg || DEFAULT_APPEARANCE.input_bg,
                input_text: bot.input_text || DEFAULT_APPEARANCE.input_text,
                input_border: bot.input_border || DEFAULT_APPEARANCE.input_border,
                button_bg: bot.button_bg || DEFAULT_APPEARANCE.button_bg,
                button_text: bot.button_text || DEFAULT_APPEARANCE.button_text,
                button_hover_bg: bot.button_hover_bg || DEFAULT_APPEARANCE.button_hover_bg,
                link_color: bot.link_color || DEFAULT_APPEARANCE.link_color,
                
                // Typography
                font_family: bot.font_family || DEFAULT_APPEARANCE.font_family,
                font_size_base: bot.font_size_base || DEFAULT_APPEARANCE.font_size_base,
                font_size_header: bot.font_size_header || DEFAULT_APPEARANCE.font_size_header,
                font_weight_normal: bot.font_weight_normal || DEFAULT_APPEARANCE.font_weight_normal,
                font_weight_bold: bot.font_weight_bold || DEFAULT_APPEARANCE.font_weight_bold,
                line_height: bot.line_height || DEFAULT_APPEARANCE.line_height,
                letter_spacing: bot.letter_spacing || DEFAULT_APPEARANCE.letter_spacing,
                
                // Bubble
                bubble_icon: bot.bubble_icon || DEFAULT_APPEARANCE.bubble_icon,
                bubble_size: bot.bubble_size || DEFAULT_APPEARANCE.bubble_size,
                bubble_custom_icon: bot.bubble_custom_icon || DEFAULT_APPEARANCE.bubble_custom_icon,
                bubble_animation: bot.bubble_animation || DEFAULT_APPEARANCE.bubble_animation,
                
                // Window
                window_width: bot.window_width || DEFAULT_APPEARANCE.window_width,
                window_height: bot.window_height || DEFAULT_APPEARANCE.window_height,
                window_border_radius: bot.window_border_radius || DEFAULT_APPEARANCE.window_border_radius,
                window_shadow: bot.window_shadow || DEFAULT_APPEARANCE.window_shadow,
                
                // Custom CSS
                custom_css: bot.custom_css || DEFAULT_APPEARANCE.custom_css,
                
                // Overrides
                appearance_overrides: overrides,
                
                // WooCommerce preset
                woocommerce_preset_id: bot.woocommerce_preset_id || null,
                
                // Behavior / Personality
                // Note: API may return these as strings "1"/"0", so convert with Number()
                personality_id: bot.personality_id || null,
                system_prompt: bot.system_prompt || '',
                tone: bot.tone || 'friendly',
                proactive_engagement: Number(bot.proactive_engagement) === 1 || bot.proactive_engagement === true,
                proactive_delay_seconds: Number(bot.proactive_delay_seconds) || 4,
                personality_overrides: personalityOverrides,
                custom_instructions: bot.custom_instructions || '',
                rules: bot.rules || '',
                forbidden_topics: bot.forbidden_topics || '',
                contact_list_id: bot.contact_list_id || null,

                // Week 28: per-bot output cap (chars)
                bot_output_char_limit: (bot as any).bot_output_char_limit ?? null,
            }

            // Load display conditions
            let conditions: DisplayCondition[] = []
            if (bot.display_conditions) {
                conditions = Array.isArray(bot.display_conditions)
                    ? bot.display_conditions
                    : []
            }

            // Fix: Skip overwriting formData with server response right after a save.
            // The local form data is authoritative; we only update the refs for future
            // patch calculation and reset the unsaved-changes baseline with server data.
            if (justSavedRef.current) {
                justSavedRef.current = false
                // Update refs used for update patching (so next save computes the right diff)
                lastSavedFormDataRef.current = nextFormData
                lastSavedDisplayConditionsRef.current = conditions
                // Reset baseline so unsaved-changes detection uses server-normalized data
                setNeedsOriginalResetAfterServerSync(true)
                return
            }

            setFormData(nextFormData)
            // NOTE: We no longer normalize conditions on load. The DisplayConditionsEditor
            // handles display normalization for default bots via its effectiveConditions memo.
            // This preserves the actual stored conditions and prevents data loss when:
            // 1. A default bot is loaded (its includes would be stripped)
            // 2. User turns off is_default toggle (their includes are already gone)
            // 3. User saves specific page conditions (they get stripped on refetch)
            setDisplayConditions(conditions)
            // Snapshot used for update patching and discard restore.
            lastSavedFormDataRef.current = nextFormData
            lastSavedDisplayConditionsRef.current = conditions
            // After server data syncs into state, reset the unsaved-changes baseline so
            // the Save button doesn't revert to "unsaved" due to minor normalization differences.
            setNeedsOriginalResetAfterServerSync(true)
            // Mark data as loaded AFTER formData is updated
            setIsDataLoaded(true)
        }
    }, [botData])

    // Reset unsaved-changes baseline after botData refetch/sync updates state.
    useEffect(() => {
        if (!needsOriginalResetAfterServerSync) return
        if (!isDataLoaded) return
        // Wait for widget IDs to be loaded too (for existing bots)
        if (!isNew && !widgetIdsLoaded) return
        // Only reset when not actively saving to avoid fighting user edits.
        if (isSaving) return
        setOriginalData()
        setNeedsOriginalResetAfterServerSync(false)
    }, [needsOriginalResetAfterServerSync, isDataLoaded, widgetIdsLoaded, isNew, isSaving, formData, displayConditions, assignedWidgetIds, setOriginalData])

    const DEFAULT_ALL_ID = '__boostbot_default_all__'
    function normalizeDefaultBotConditions(input: DisplayCondition[]): DisplayCondition[] {
        const excludes = (input || [])
            .filter(c => c && c.id !== DEFAULT_ALL_ID)
            .filter(c => c.operator === 'exclude')
            .map(c => ({ ...c, operator: 'exclude' as const }))

        const defaultAll: DisplayCondition = {
            id: DEFAULT_ALL_ID,
            type: 'all',
            operator: 'include',
        }

        return [defaultAll, ...excludes]
    }

    // State for confirmation dialog when toggling is_default would lose include conditions
    const [showDefaultBotConfirm, setShowDefaultBotConfirm] = useState(false)

    // Check if there are include conditions that would be lost when switching to default bot
    const hasIncludeConditions = (conditions: DisplayCondition[]): boolean => {
        return conditions.some(c => 
            c.operator === 'include' && 
            c.id !== DEFAULT_ALL_ID &&
            c.type !== 'all' // Ignore generic "all" includes
        )
    }

    const handleChange = (field: keyof BotFormData, value: unknown) => {
        // Allow display conditions for default bot: keep an explicit "all/include" row and allow only excludes beyond it.
        if (field === 'is_default') {
            const nextIsDefault = value === true
            if (nextIsDefault && hasIncludeConditions(displayConditions)) {
                // Show confirmation before dropping include conditions
                setShowDefaultBotConfirm(true)
                return // Don't update yet, wait for confirmation
            }
            if (nextIsDefault) {
                setDisplayConditions(prev => normalizeDefaultBotConditions(prev))
            } else {
                // When turning off default, keep whatever conditions user had, but drop the implicit default row if it exists
                setDisplayConditions(prev => prev.filter(c => c.id !== DEFAULT_ALL_ID))
            }
        }

        setFormData((prev) => ({ ...prev, [field]: value }))

        // Auto-generate slug from name for new bots (ASCII only)
        if (field === 'bot_name' && isNew && typeof value === 'string') {
            // Only keep ASCII letters, numbers, spaces and hyphens
            const slug = value
                .toLowerCase()
                .replace(/[^a-z0-9\s-]/g, '') // Remove non-ASCII (including Hebrew)
                .replace(/\s+/g, '-')
                .replace(/-+/g, '-') // Remove multiple hyphens
                .replace(/^-|-$/g, '') // Remove leading/trailing hyphens
            // If slug is empty (Hebrew name), generate timestamp-based slug
            const finalSlug = slug || `bot-${Date.now()}`
            setFormData((prev) => ({ ...prev, bot_slug: finalSlug }))
        }
    }

    // Confirm/Cancel modal no longer used: default bot can have display exclusions.

    // Handle personality change - load all values from personality
    const handlePersonalityChange = (personalityId: number | null) => {
        if (!personalityId) {
            // Clear personality, keep current values but reset overrides
            setFormData(prev => ({
                ...prev,
                personality_id: null,
                personality_overrides: defaultPersonalityOverrides,
            }))
            return
        }

        // Use Number() for comparison since API returns id as string
        const personality = personalities.find(p => Number(p.id) === Number(personalityId))
        if (!personality) return

        // Load all values from personality
        // Note: API returns strings like "1", so use Number() for comparison
        setFormData(prev => ({
            ...prev,
            personality_id: personalityId,
            system_prompt: personality.system_prompt || '',
            tone: personality.tone || 'friendly',
            proactive_engagement: Number(personality.proactive_engagement) === 1,
            proactive_delay_seconds: Number(personality.proactive_delay_seconds) || 4,
            custom_instructions: personality.custom_instructions || '',
            // Reset all overrides when selecting new personality
            personality_overrides: defaultPersonalityOverrides,
        }))
    }

    const handleUnlinkAllPersonality = () => {
        // Keep current values, but if currently linked to a preset, first materialize
        // the preset values so unlinking does not expose blank/stale fields.
        setFormData((prev) => ({
            ...prev,
            system_prompt: selectedPersonality?.system_prompt || prev.system_prompt,
            tone: selectedPersonality?.tone || prev.tone,
            proactive_engagement:
                selectedPersonality?.proactive_engagement !== undefined
                    ? Number(selectedPersonality.proactive_engagement) === 1
                    : prev.proactive_engagement,
            proactive_delay_seconds:
                selectedPersonality?.proactive_delay_seconds !== undefined
                    ? Number(selectedPersonality.proactive_delay_seconds) || prev.proactive_delay_seconds
                    : prev.proactive_delay_seconds,
            custom_instructions: selectedPersonality?.custom_instructions || prev.custom_instructions,
            personality_overrides: {
                ...prev.personality_overrides,
                system_prompt: true,
                tone: true,
                proactive_engagement: true,
                proactive_delay_seconds: true,
                custom_instructions: true,
            },
        }))
    }

    const handleRelinkAllPersonality = () => {
        if (!formData.personality_id) return
        // Reload from preset and reset overrides
        handlePersonalityChange(formData.personality_id)
    }

    const handleCreatePersonalityPresetFromCurrent = () => {
        if (!newPersonalityPresetName.trim()) return
        createPersonalityPresetMutation.mutate({
            name: newPersonalityPresetName.trim(),
            slug: slugifyAscii(newPersonalityPresetName.trim()),
            description: `Created from bot "${formData.bot_name || 'bot'}"`,
            system_prompt: formData.system_prompt || '',
            tone: formData.tone || 'friendly',
            proactive_engagement: formData.proactive_engagement ? 1 : 0,
            is_default: 0,
        })
    }

    // Unlink a single personality field
    const unlinkPersonalityField = (fieldKey: keyof PersonalityOverrides) => {
        setFormData(prev => ({
            ...prev,
            personality_overrides: {
                ...prev.personality_overrides,
                [fieldKey]: true, // Mark as overridden
            }
        }))
    }

    // Handle personality field change
    const handlePersonalityFieldChange = (fieldKey: string, value: string | boolean | number) => {
        // If personality is selected and field is linked, unlink it first
        if (formData.personality_id && !formData.personality_overrides[fieldKey as keyof PersonalityOverrides]) {
            unlinkPersonalityField(fieldKey as keyof PersonalityOverrides)
        }

        setFormData(prev => ({
            ...prev,
            [fieldKey]: value
        }))
    }

    // Check if a personality field is linked
    const isPersonalityFieldLinked = (fieldKey: keyof PersonalityOverrides): boolean => {
        return !!formData.personality_id && !formData.personality_overrides[fieldKey]
    }

    // Opening screen actions
    const handleUnlinkOpening = () => {
        // Copy preset values (or defaults) into per-bot overrides so everything becomes editable.
        const base = buildOpeningSettingsFromPreset(selectedOpeningPreset, formData.welcome_message)
        setFormData((prev) => ({
            ...prev,
            opening_screen_overrides: base as unknown as Record<string, unknown>,
        }))
    }

    const handleRelinkOpening = () => {
        setFormData((prev) => ({
            ...prev,
            opening_screen_overrides: null,
        }))
    }

    const handleOpeningSettingsChange = (settings: OpeningScreenSettings) => {
        // If linked to preset, first unlink (create overrides) then apply change.
        if (hasOpeningPreset && !isNonEmptyObject(formData.opening_screen_overrides)) {
            const base = buildOpeningSettingsFromPreset(selectedOpeningPreset, formData.welcome_message)
            setFormData((prev) => ({
                ...prev,
                opening_screen_overrides: { ...(base as any), ...(settings as any) },
            }))
            return
        }
        setFormData((prev) => ({
            ...prev,
            opening_screen_overrides: settings as unknown as Record<string, unknown>,
        }))
    }

    const handleCreateOpeningPresetFromCurrent = () => {
        if (!newOpeningPresetName.trim()) return
        const s = effectiveOpeningSettings
        createOpeningPresetMutation.mutate({
            name: newOpeningPresetName.trim(),
            description: `Created from bot "${formData.bot_name || 'bot'}"`,
            is_default: 0,
            mode: s.mode,
            welcome_text: s.welcome_text,
            show_welcome: s.show_welcome ? 1 : 0,
            questions: s.questions || [],
            ai_instructions: s.ai_instructions || '',
            qa_pairs: s.qa_pairs || [],
            contact_list_id: s.contact_list_id ?? null,
            show_departments: s.show_departments ? 1 : 0,
            show_contact_cards: s.show_contact_cards ? 1 : 0,
            attached_files: s.attached_files || [],
        })
    }

    // Handler for element settings changes (new appearance system)
    const handleElementSettingsChange = (settings: ElementSettings) => {
        setElementSettings(settings)
    }

    // Handler for widget settings changes (new appearance system)
    const handleWidgetSettingsChange = <K extends keyof WidgetSettings>(key: K, settings: WidgetSettings[K]) => {
        setWidgetSettings(prev => {
            if (prev) {
                return { ...prev, [key]: settings }
            }
            // Create a minimal WidgetSettings object with just this key
            return { [key]: settings } as unknown as WidgetSettings
        })
    }

    const handleSave = async () => {
        setIsSaving(true)
        setSaveRequestError(null)
        try {
            if (isNew) {
            const dataToSave = {
                ...formData,
                bot_name: formData.bot_name.trim(),
                language: currentLanguage,
                display_conditions: displayConditions,
            }
                const result = await createBot.mutateAsync(dataToSave)
                if (result?.data?.bot?.id) {
                    navigate(`/bots/${result.data.bot.id}`)
                }
            } else {
                const patch = buildBotUpdatePatch(formData, lastSavedFormDataRef.current)
                const originalConditions = lastSavedDisplayConditionsRef.current
                const shouldSendConditions =
                    !originalConditions || !jsonEqual(displayConditions, originalConditions)

                if (patch.bot_name) patch.bot_name = patch.bot_name.trim()

                const dataToSave: Partial<BotFormData> & { display_conditions?: DisplayCondition[] } = {
                    ...patch,
                    ...(shouldSendConditions ? { display_conditions: displayConditions } : {}),
                }

                // Check if there are widget assignment changes
                const originalIds = originalWidgetIdsRef.current
                const toAssign = assignedWidgetIds.filter(wid => !originalIds.includes(wid))
                const toUnassign = originalIds.filter(wid => !assignedWidgetIds.includes(wid))
                const hasWidgetChanges = toAssign.length > 0 || toUnassign.length > 0

                // If nothing actually changed (bot data + widget assignments), don't hit the API.
                if (Object.keys(dataToSave).length === 0 && !hasWidgetChanges) {
                    setOriginalData()
                    lastSavedFormDataRef.current = { ...formData }
                    lastSavedDisplayConditionsRef.current = displayConditions
                    return
                }

                // Save bot data (only if there are changes)
                if (Object.keys(dataToSave).length > 0) {
                    await updateBot.mutateAsync({ id: Number(id), data: dataToSave })
                }
                
                // Save widget assignment changes
                for (const wid of toAssign) {
                    await widgetsApi.assignToChatbot(wid, Number(id))
                }
                for (const wid of toUnassign) {
                    await widgetsApi.unassignFromChatbot(wid, Number(id))
                }
                
                // Update the original widget IDs reference
                if (hasWidgetChanges) {
                    originalWidgetIdsRef.current = [...assignedWidgetIds]
                    queryClient.invalidateQueries({ queryKey: ['widgets', 'for-chatbot', numericBotId] })
                }

                // Ensure the bots list cache is fresh before any navigation
                // (invalidateQueries only marks stale; refetchQueries awaits the refetch)
                await queryClient.refetchQueries({ queryKey: ['bots'] })
                
                // Fix: Tell the load effect to skip overwriting formData on the
                // next server refetch (triggered by invalidateQueries in onSuccess).
                justSavedRef.current = true

                // Show cute robot animation on successful save
                // saveCooldownRef provides a synchronous guard: during the 2-second
                // animation window the button will never flicker to amber.
                saveCooldownRef.current = true
                setShowSavedAnimation(true)
                setTimeout(() => {
                    setShowSavedAnimation(false)
                    saveCooldownRef.current = false
                }, 2000)
                
                // Reset original data after successful save
                setOriginalData()
                lastSavedFormDataRef.current = { ...formData }
                lastSavedDisplayConditionsRef.current = displayConditions
            }
        } catch (err: any) {
            // Important: do not let this throw (React onClick won't catch), otherwise we get
            // "Uncaught (in promise) Object" and no user-visible feedback.
            const msg =
                err?.message ||
                err?.data?.message ||
                err?.error?.message ||
                t('Save failed. Please try again.')
            setSaveRequestError(String(msg))
        } finally {
            setIsSaving(false)
        }
    }

    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>
        )
    }

    // Tabs
    const tabs = [
        { id: 'basic', label: t('Basic Details'), icon: Bot },
        { id: 'display', label: t('Display Conditions'), icon: Target },
        { id: 'appearance', label: t('Appearance'), icon: Palette },
        { id: 'opening', label: t('Opening Message'), icon: Sparkles },
        { id: 'behavior', label: t('Personality'), icon: MessageSquare },
        ...(!isNew ? [{ id: 'widgets', label: t('Widgets'), icon: Puzzle }] : []),
        ...(wooCommerceActive ? [{ id: 'woocommerce', label: t('WooCommerce'), icon: ShoppingCart }] : []),
        { id: 'advanced', label: t('Advanced'), icon: Settings },
    ]

    // Handle back navigation with unsaved changes check
    const handleBack = () => {
        checkNavigationSafe(() => {
            navigate('/bots')
        })
    }

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

            {/* Default Bot Confirmation Modal - warns when include conditions would be lost */}
            {showDefaultBotConfirm && (
                <div className="fixed inset-0 bg-black/50 flex items-center justify-center z-50">
                    <div className="bg-white rounded-xl shadow-2xl max-w-md w-full mx-4 p-6 animate-scale-in">
                        <div className="flex items-start gap-3 mb-4">
                            <AlertTriangle className="w-6 h-6 text-amber-500 flex-shrink-0 mt-0.5" />
                            <div>
                                <h3 className="text-lg font-semibold text-gray-900">{t('Warning: Display conditions will be lost')}</h3>
                                <p className="text-sm text-gray-600 mt-2">
                                    {t('Setting the bot as default will remove existing display conditions (include conditions).')}
                                    <br /><br />
                                    {t('A default bot is displayed on')} <strong>{t('the entire site')}</strong> {t('and only allows')} <strong>{t('exclusion')}</strong> {t('conditions.')}
                                </p>
                            </div>
                        </div>
                        <div className="flex gap-3 justify-end">
                            <button
                                onClick={() => setShowDefaultBotConfirm(false)}
                                className="px-4 py-2 border border-gray-300 text-gray-700 rounded-lg hover:bg-gray-50 transition-colors"
                            >
                                {t('Cancel')}
                            </button>
                            <button
                                onClick={() => {
                                    // Proceed with toggling to default
                                    setDisplayConditions(prev => normalizeDefaultBotConditions(prev))
                                    setFormData(prev => ({ ...prev, is_default: true }))
                                    setShowDefaultBotConfirm(false)
                                }}
                                className="px-4 py-2 bg-amber-500 text-white rounded-lg hover:bg-amber-600 transition-colors"
                            >
                                {t('Continue anyway')}
                            </button>
                        </div>
                    </div>
                </div>
            )}

            {/* Unsaved changes indicator — suppressed during save animation cooldown
                to prevent cosmetic flicker from server sync */}
            {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>
            )}

            {/* Default bot can now use display exclusions - no warning modal needed */}

            <PageHeader
                title={isNew ? t('New Bot') : sprintf(t('Edit %s'), formData.bot_name)}
                subtitle={isNew ? t('Create a new bot with custom settings') : t('Edit bot 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.bot_name?.trim()}
                        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>

            {saveRequestError && (
                <div className="border border-red-200 bg-red-50 text-red-800 px-4 py-3 rounded-lg">
                    {saveRequestError}
                </div>
            )}

            {/* Tabs */}
            <div className="border-b border-gray-200">
                <nav className="flex gap-2">
                    {tabs.map((tab) => {
                        const Icon = tab.icon
                        return (
                            <button
                                key={tab.id}
                                onClick={() => {
                                    if (activeTab === tab.id) return
                                    checkNavigationSafe(() => setActiveTab(tab.id))
                                }}
                                className={`flex items-center gap-2 px-2 py-3 border-b-2 font-medium text-sm transition-colors ${
                                    activeTab === tab.id
                                        ? 'border-primary-600 text-primary-600'
                                        : 'border-transparent text-gray-500 hover:text-gray-700'
                                }`}
                            >
                                <Icon className="w-4 h-4" />
                                {tab.label}
                            </button>
                        )
                    })}
                </nav>
            </div>

            {/* Basic Info Tab */}
            {activeTab === 'basic' && (
                <Card data-wizard-id="bot-tab-content">
                    <CardHeader>
                        <CardTitle>{t('Basic Details')}</CardTitle>
                    </CardHeader>
                    <CardContent className="space-y-4">
                        {/* Bot Name */}
                        <div>
                            <label className="block text-sm font-medium text-gray-700 mb-1">
                                {t('Bot Name')} *
                            </label>
                            <input
                                type="text"
                                value={formData.bot_name}
                                onChange={(e) => handleChange('bot_name', e.target.value)}
                                placeholder={t('e.g.: Products Bot')}
                                className="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-primary-500 focus:border-transparent"
                            />
                        </div>

                        {/* Bot Slug */}
                        <div>
                            <label className="block text-sm font-medium text-gray-700 mb-1">
                                {t('Slug')}
                            </label>
                            <input
                                type="text"
                                value={formData.bot_slug}
                                onChange={(e) => handleChange('bot_slug', e.target.value)}
                                placeholder="bot-products"
                                className="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-primary-500 focus:border-transparent font-mono text-sm"
                                dir="ltr"
                            />
                            <p className="text-xs text-gray-500 mt-1">
                                {t('Used to identify the bot in the system. Auto-generated from the bot name.')}
                            </p>
                        </div>

                        {/* Description */}
                        <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 bot and its purpose')}
                                rows={3}
                                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>

                        {/* Active Toggle */}
                        <div className="flex items-center justify-between py-3 border-t">
                            <div>
                                <p className="font-medium text-gray-900">{t('Bot Active')}</p>
                                <p className="text-sm text-gray-500">{t('The bot will be displayed to visitors on the site')}</p>
                            </div>
                            <ToggleSwitch
                                checked={!!formData.is_active}
                                onChange={(v) => handleChange('is_active', v)}
                                ariaLabel={t('Bot Active')}
                            />
                        </div>

                        {/* Default Bot Toggle */}
                        <div className="flex items-center justify-between py-3 border-t">
                            <div>
                                <p className="font-medium text-gray-900">{t('Default Bot')}</p>
                                <p className="text-sm text-gray-500">{t('Displayed on every page that has no specific bot')}</p>
                            </div>
                            <ToggleSwitch
                                checked={!!formData.is_default}
                                onChange={(v) => handleChange('is_default', v)}
                                ariaLabel={t('Default Bot')}
                            />
                        </div>

                        {/* Default Bot Info Message */}
                        {formData.is_default && (
                            <div className="bg-blue-50 border border-blue-200 rounded-lg p-4 mt-4">
                                <div className="flex gap-3">
                                    <Info className="w-5 h-5 text-blue-600 flex-shrink-0 mt-0.5" />
                                    <div>
                                        <p className="font-medium text-blue-800">{t('Default Bot')}</p>
                                        <p className="text-sm text-blue-700 mt-1">
                                            {t('This bot will be displayed on all site pages, except pages where a specific bot with display conditions is defined.')}
                                            <br />
                                            <span className="text-blue-600">{t('You can exclude pages/content types for the default bot in the "Display Conditions" tab.')}</span>
                                        </p>
                                    </div>
                                </div>
                            </div>
                        )}
                    </CardContent>
                </Card>
            )}

            {/* Display Conditions Tab */}
            {activeTab === 'display' && (
                <Card data-wizard-id="bot-tab-content">
                    <CardHeader>
                        <CardTitle>{t('Display Conditions')}</CardTitle>
                    </CardHeader>
                    <CardContent className="space-y-4">
                        {/* Warning for default bot */}
                        {formData.is_default && (
                            <div className="bg-amber-50 border border-amber-200 rounded-lg p-4">
                                <div className="flex gap-3">
                                    <AlertTriangle className="w-5 h-5 text-amber-600 flex-shrink-0 mt-0.5" />
                                    <div>
                                        <p className="font-medium text-amber-800">{t('Default Bot')}</p>
                                        <p className="text-sm text-amber-700 mt-1">
                                            {t('This bot is set as default and is therefore displayed on')} <strong>{t('the entire site')}</strong> {t('automatically.')}
                                            <br />
                                            {t('You can only')} <strong>{t('exclude')}</strong> {t('specific pages or content types from display.')}
                                        </p>
                                    </div>
                                </div>
                            </div>
                        )}
                        <DisplayConditionsEditor
                            conditions={displayConditions}
                            onChange={setDisplayConditions}
                            botId={!isNew ? Number(id) : undefined}
                            isDefaultBot={!!formData.is_default}
                        />
                    </CardContent>
                </Card>
            )}

            {/* Appearance Tab - Using new BotAppearanceTab component */}
            {activeTab === 'appearance' && (
                <div data-wizard-id="bot-tab-content"><BotAppearanceTab
                    formData={formData}
                    botId={id}
                    selectedPreset={selectedPreset}
                    systemGlobalValues={systemGlobalValues}
                    customFontCss={customFontCss}
                    availablePresets={appearancePresets.map(p => ({ id: p.id, name: p.name, is_default: p.is_default }))}
                    onFieldChange={(field, value) => handleChange(field, value)}
                    onElementSettingsChange={handleElementSettingsChange}
                    onWidgetSettingsChange={handleWidgetSettingsChange}
                /></div>
            )}

            {/* Opening Screen Tab */}
            {activeTab === 'opening' && (
                <div className="space-y-6" data-wizard-id="bot-tab-content">
                    {/* Preset Selection */}
                    <Card>
                        <CardHeader>
                            <CardTitle className="flex items-center gap-2">
                                <Sparkles className="w-5 h-5 text-amber-500" />
                                {t('Opening Message')}
                            </CardTitle>
                        </CardHeader>
                        <CardContent className="space-y-4">
                            <div>
                                <label className="block text-sm font-medium text-gray-700 mb-2">
                                    {t('Select opening message preset')}
                                </label>
                                <p className="text-xs text-gray-500 mb-3">
                                    {t('Choose a preset template for the bot opening message, or leave empty for the default message')}
                                </p>
                                <div className="flex gap-3 items-center">
                                    <select
                                        value={formData.opening_screen_preset_id || ''}
                                        onChange={(e) => {
                                            const nextId = e.target.value ? Number(e.target.value) : null
                                            setFormData((prev) => ({
                                                ...prev,
                                                opening_screen_preset_id: nextId,
                                                // When switching to a preset, drop previous per-bot overrides to prevent mixing configs.
                                                // When clearing preset, keep overrides if user was editing independently.
                                                ...(nextId ? { opening_screen_overrides: null } : {}),
                                            }))
                                        }}
                                        className="flex-1 px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-primary-500 focus:border-transparent bg-white"
                                    >
                                        <option value="">{t('No preset (default message)')}</option>
                                        {openingScreenPresets.map((preset) => (
                                            <option key={preset.id} value={preset.id}>
                                                {preset.name}
                                                {preset.is_default === 1 && ' ⭐'}
                                            </option>
                                        ))}
                                    </select>

                                    {formData.opening_screen_preset_id && (
                                        <Link
                                            to={`/opening-screen-presets/${formData.opening_screen_preset_id}?returnTo=${encodeURIComponent(`/bots/${id}?tab=opening`)}`}
                                            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 opening message preset')}
                                        >
                                            <Pencil className="w-4 h-4" />
                                            <span className="text-sm font-medium">{t('Edit Preset')}</span>
                                        </Link>
                                    )}
                                </div>
                            </div>
                        </CardContent>
                    </Card>

                    {/* Link status banner (mirrors Appearance) */}
                    {(hasOpeningPreset || isNonEmptyObject(formData.opening_screen_overrides)) && (
                        <Card className={`border-2 transition-all duration-300 ${
                            isOpeningUnlinked ? 'border-amber-300 bg-amber-50' : 'border-blue-300 bg-blue-50'
                        }`}>
                            <CardContent className="py-4">
                                <div className="flex items-center justify-between">
                                    <div className="flex items-center gap-3">
                                        {isOpeningUnlinked ? (
                                            <div className="p-2 bg-amber-200 rounded-full">
                                                <Link2Off className="w-5 h-5 text-amber-700" />
                                            </div>
                                        ) : (
                                            <div className="p-2 bg-blue-200 rounded-full">
                                                <Link2 className="w-5 h-5 text-blue-700" />
                                            </div>
                                        )}
                                        <div>
                                            <h4 className={`font-medium ${isOpeningUnlinked ? 'text-amber-800' : 'text-blue-800'}`}>
                                                {hasOpeningPreset
                                                    ? (isOpeningUnlinked
                                                        ? sprintf(t('Unlinked from Preset "%s"'), selectedOpeningPreset?.name || '')
                                                        : sprintf(t('Linked to Preset "%s"'), selectedOpeningPreset?.name || '')
                                                    )
                                                    : t('Independent editing (no Preset)')
                                                }
                                            </h4>
                                            <p className="text-sm text-gray-600">
                                                {hasOpeningPreset
                                                    ? (isOpeningUnlinked
                                                        ? t('Custom values (independent editing)')
                                                        : t('All fields inherit from the Preset. Click "Unlink" for independent editing')
                                                    )
                                                    : t('Settings are saved on the bot itself. You can create a new Preset from the current state.')
                                                }
                                            </p>
                                        </div>
                                    </div>

                                    <div className="flex items-center gap-2">
                                        {hasOpeningPreset && isOpeningLinked && (
                                            <button
                                                type="button"
                                                onClick={handleUnlinkOpening}
                                                className="flex items-center gap-2 px-4 py-2 bg-amber-500 text-white rounded-lg hover:bg-amber-600 transition-colors font-medium"
                                            >
                                                <Link2Off className="w-4 h-4" />
                                                {t('Unlink for independent editing')}
                                            </button>
                                        )}

                                        {(isOpeningUnlinked || (!hasOpeningPreset && isNonEmptyObject(formData.opening_screen_overrides))) && (
                                            <div className="flex items-center gap-3">
                                                <button
                                                    type="button"
                                                    onClick={() => setShowCreateOpeningPresetModal(true)}
                                                    className="flex items-center gap-2 px-4 py-2 bg-green-500 text-white rounded-lg hover:bg-green-600 transition-colors font-medium"
                                                >
                                                    <Plus className="w-4 h-4" />
                                                    {t("Create New Preset")}
                                                </button>
                                                {hasOpeningPreset && (
                                                    <button
                                                        type="button"
                                                        onClick={handleRelinkOpening}
                                                        className="flex items-center gap-2 px-4 py-2 bg-blue-500 text-white rounded-lg hover:bg-blue-600 transition-colors font-medium"
                                                    >
                                                        <Link2 className="w-4 h-4" />
                                                        {t("Relink to Preset")}
                                                    </button>
                                                )}
                                            </div>
                                        )}
                                    </div>
                                </div>
                            </CardContent>
                        </Card>
                    )}

                    {/* Full editor (all elements from Opening Screen editor) */}
                    {(formData.opening_screen_preset_id || isNonEmptyObject(formData.opening_screen_overrides)) && (
                        <Card>
                            <CardHeader>
                                <CardTitle className="flex items-center gap-2">
                                    <Sparkles className="w-5 h-5 text-primary-500" />
                                    {t('Edit Opening Message')}
                                </CardTitle>
                            </CardHeader>
                            <CardContent>
                                {/* Container with hover tracking (like WidgetSectionBase) */}
                                <div
                                    className="relative"
                                    onMouseEnter={() => setIsOpeningEditorHovered(true)}
                                    onMouseLeave={() => setIsOpeningEditorHovered(false)}
                                >
                                    {/* Hover-only locked overlay (exactly like WidgetSectionBase) */}
                                    {isOpeningLinked && (
                                        <div
                                            style={{
                                                position: 'absolute',
                                                inset: 0,
                                                zIndex: 20,
                                                opacity: isOpeningEditorHovered ? 1 : 0,
                                                pointerEvents: isOpeningEditorHovered ? 'auto' : 'none',
                                                transition: 'opacity 150ms ease',
                                                background: 'rgba(255,255,255,0.55)',
                                                backdropFilter: 'blur(1px)',
                                                display: 'flex',
                                                alignItems: 'center',
                                                justifyContent: 'center',
                                                padding: '24px',
                                                borderRadius: '8px',
                                            }}
                                        >
                                            <div style={{ textAlign: 'center', maxWidth: 360 }}>
                                                <div style={{ fontSize: 13, color: '#374151', marginBottom: 12 }}>
                                                    {t('To edit here, unlink the setting for independent editing')}
                                                </div>
                                                <button
                                                    type="button"
                                                    onClick={(e) => {
                                                        e.stopPropagation();
                                                        handleUnlinkOpening();
                                                    }}
                                                    style={{
                                                        display: 'inline-flex',
                                                        alignItems: 'center',
                                                        justifyContent: 'center',
                                                        gap: 8,
                                                        padding: '10px 14px',
                                                        borderRadius: 10,
                                                        border: 'none',
                                                        background: '#F59E0B',
                                                        color: '#FFFFFF',
                                                        fontSize: 14,
                                                        fontWeight: 600,
                                                        cursor: 'pointer',
                                                        boxShadow: '0 6px 18px rgba(0,0,0,0.12)',
                                                    }}
                                                >
                                                    <Link2Off className="w-4 h-4" />
                                                    {t('Unlink all for independent editing')}
                                                </button>
                                            </div>
                                        </div>
                                    )}

                                    {/* Content (locked when linked to preset - pointer-events: none, reduced opacity) */}
                                    <div
                                        style={{
                                            opacity: isOpeningLinked ? 0.65 : 1,
                                            pointerEvents: isOpeningLinked ? 'none' : 'auto',
                                        }}
                                    >
                                        <OpeningScreenConfig
                                            settings={effectiveOpeningSettings}
                                            onChange={handleOpeningSettingsChange}
                                        />
                                    </div>
                                </div>
                            </CardContent>
                        </Card>
                    )}

                    {/* No Preset Selected — Default Welcome Message Controls */}
                    {!formData.opening_screen_preset_id && !isNonEmptyObject(formData.opening_screen_overrides) && (
                        <>
                            <Card>
                                <CardHeader>
                                    <CardTitle className="flex items-center gap-2">
                                        <MessageSquare className="w-5 h-5 text-primary-500" />
                                        {t('Default Welcome Message')}
                                    </CardTitle>
                                </CardHeader>
                                <CardContent className="space-y-4">
                                    <div>
                                        <label className="flex items-center gap-2 mb-2">
                                            <input
                                                type="checkbox"
                                                checked={formData.show_welcome_message}
                                                onChange={(e) => setFormData((prev) => ({
                                                    ...prev,
                                                    show_welcome_message: e.target.checked,
                                                }))}
                                                className="rounded border-gray-300 text-primary-600 focus:ring-primary-500"
                                            />
                                            <span className="text-sm font-medium text-gray-700">{t('Show welcome text')}</span>
                                        </label>
                                        {formData.show_welcome_message && (
                                            <div>
                                                <input
                                                    type="text"
                                                    value={formData.welcome_message}
                                                    onChange={(e) => setFormData((prev) => ({
                                                        ...prev,
                                                        welcome_message: e.target.value,
                                                    }))}
                                                    placeholder={globalDefaultWelcomeText}
                                                    className="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-primary-500 focus:border-primary-500"
                                                />
                                                <p className="text-xs text-gray-500 mt-1">
                                                    {sprintf(t('Leave empty to use the global default: "%s"'), globalDefaultWelcomeText)}
                                                </p>
                                            </div>
                                        )}
                                    </div>
                                </CardContent>
                            </Card>

                            <Card className="border-dashed border-2 border-gray-300 bg-gray-50">
                                <CardContent className="py-6">
                                    <div className="text-center">
                                        <p className="text-sm text-gray-500 mb-4">
                                            {t('Want to add questions or buttons? Select an advanced opening message preset')}
                                        </p>
                                        <Link
                                            to="/opening-screen-presets/new"
                                            className="inline-flex items-center gap-2 px-4 py-2 bg-primary-600 text-white rounded-lg hover:bg-primary-700 transition-colors"
                                        >
                                            <Sparkles className="w-4 h-4" />
                                            {t('Create New Preset')}
                                        </Link>
                                        <button
                                            type="button"
                                            onClick={() => setFormData((prev) => ({
                                                ...prev,
                                                opening_screen_overrides: buildOpeningSettingsFromPreset(undefined, prev.welcome_message || globalDefaultWelcomeText) as unknown as Record<string, unknown>,
                                            }))}
                                            className="inline-flex items-center gap-2 px-4 py-2 ms-2 bg-amber-500 text-white rounded-lg hover:bg-amber-600 transition-colors"
                                        >
                                            <Link2Off className="w-4 h-4" />
                                            {t('Edit independently without Preset')}
                                        </button>
                                    </div>
                                </CardContent>
                            </Card>
                        </>
                    )}

                    {/* Create Opening Preset Modal */}
                    {showCreateOpeningPresetModal && (
                        <div className="fixed inset-0 bg-black/50 flex items-center justify-center z-50 animate-fade-in">
                            <div className="bg-white rounded-xl shadow-2xl w-full max-w-md mx-4 overflow-hidden">
                                <div className="bg-gradient-to-r from-green-500 to-emerald-600 px-6 py-4 flex items-center justify-between">
                                    <h3 className="text-lg font-semibold text-white flex items-center gap-2">
                                        <Plus className="w-5 h-5" />
                                        {t("Create New Preset")}
                                    </h3>
                                    <button
                                        onClick={() => {
                                            setShowCreateOpeningPresetModal(false)
                                            setNewOpeningPresetName('')
                                        }}
                                        className="text-white/80 hover:text-white transition-colors"
                                    >
                                        <X className="w-5 h-5" />
                                    </button>
                                </div>

                                <div className="p-6">
                                    <p className="text-gray-600 mb-4">
                                        {t('Create a new Preset from the current opening message settings.')}
                                    </p>
                                    <div className="mb-4">
                                        <label className="block text-sm font-medium text-gray-700 mb-2">
                                            {t('Preset Name')}
                                        </label>
                                        <input
                                            type="text"
                                            value={newOpeningPresetName}
                                            onChange={(e) => setNewOpeningPresetName(e.target.value)}
                                            placeholder={t('e.g.: Opening - FAQ')}
                                            className="w-full px-4 py-3 border border-gray-300 rounded-lg focus:ring-2 focus:ring-green-500 focus:border-green-500 transition-all"
                                            autoFocus
                                        />
                                    </div>
                                </div>

                                <div className="bg-gray-50 px-6 py-4 flex items-center justify-end gap-3">
                                    <button
                                        type="button"
                                        onClick={() => {
                                            setShowCreateOpeningPresetModal(false)
                                            setNewOpeningPresetName('')
                                        }}
                                        className="px-4 py-2 text-gray-700 hover:bg-gray-200 rounded-lg transition-colors"
                                    >
                                        {t("Cancel")}
                                    </button>
                                    <button
                                        type="button"
                                        onClick={handleCreateOpeningPresetFromCurrent}
                                        disabled={!newOpeningPresetName.trim() || createOpeningPresetMutation.isPending}
                                        className="flex items-center gap-2 px-6 py-2 bg-green-500 text-white rounded-lg hover:bg-green-600 disabled:opacity-50 disabled:cursor-not-allowed transition-all font-medium"
                                    >
                                        {createOpeningPresetMutation.isPending ? (
                                            <>
                                                <Loader2 className="w-4 h-4 animate-spin" />
                                                {t("Creating...")}
                                            </>
                                        ) : (
                                            <>
                                                <Plus className="w-4 h-4" />
                                                {t("Create Preset")}
                                            </>
                                        )}
                                    </button>
                                </div>
                            </div>
                        </div>
                    )}
                </div>
            )}

            {/* Behavior Tab */}
            {activeTab === 'behavior' && (
                <div className="space-y-6" data-wizard-id="bot-tab-content">
                    {/* Personality Selection */}
                    <Card>
                        <CardHeader>
                            <CardTitle>{t('Bot Personality')}</CardTitle>
                        </CardHeader>
                        <CardContent className="space-y-4">
                            <div>
                                <label className="block text-sm font-medium text-gray-700 mb-2">
                                    <Sparkles className="w-4 h-4 inline me-1 text-primary-500" />
                                    {t('Select Personality')}
                                </label>
                                <p className="text-xs text-gray-500 mb-3">
                                    {t('The personality defines communication style, tone, and bot behavior')}
                                </p>
                                <div className="flex gap-3 items-center">
                                    <select
                                        value={formData.personality_id || ''}
                                        onChange={(e) => handlePersonalityChange(e.target.value ? Number(e.target.value) : null)}
                                        className="flex-1 px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-primary-500 focus:border-transparent bg-white"
                                    >
                                        <option value="">{t('No personality (manual setup)')}</option>
                                        {personalities.map((personality) => (
                                            <option key={personality.id} value={personality.id}>
                                                {personality.name}
                                                {personality.is_default === 1 && ' ⭐'}
                                            </option>
                                        ))}
                                    </select>

                                    {formData.personality_id && (
                                        <Link
                                            to={`/personalities/${formData.personality_id}?returnTo=${encodeURIComponent(`/bots/${id}?tab=behavior`)}`}
                                            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 Personality')}
                                        >
                                            <Pencil className="w-4 h-4" />
                                            <span className="text-sm font-medium">{t("Edit Preset")}</span>
                                        </Link>
                                    )}
                                </div>

                                {/* When linked, fields are locked and unlocked via the orange "unlink all" CTA overlay */}
                            </div>
                        </CardContent>
                    </Card>

                    {/* Personality Link Status Banner (Preset management) */}
                    {formData.personality_id && (
                        <Card
                            className={`border-2 transition-all duration-300 ${
                                isPersonalityLinked ? 'border-blue-300 bg-blue-50' : 'border-amber-300 bg-amber-50'
                            }`}
                        >
                            <CardContent className="py-4">
                                <div className="flex items-center justify-between">
                                    <div className="flex items-center gap-3">
                                        {isPersonalityLinked ? (
                                            <div className="p-2 bg-blue-200 rounded-full">
                                                <Link2 className="w-5 h-5 text-blue-700" />
                                            </div>
                                        ) : (
                                            <div className="p-2 bg-amber-200 rounded-full">
                                                <Link2Off className="w-5 h-5 text-amber-700" />
                                            </div>
                                        )}

                                        <div>
                                            <h4
                                                className={`font-medium ${
                                                    isPersonalityLinked ? 'text-blue-800' : 'text-amber-800'
                                                }`}
                                            >
                                                {isPersonalityLinked
                                                    ? sprintf(t('Linked to Preset "%s"'), selectedPersonalityName ?? '')
                                                    : sprintf(t('Unlinked from Preset "%s"'), selectedPersonalityName ?? '')}
                                            </h4>
                                            <p className="text-sm text-gray-600">
                                                {isPersonalityLinked
                                                    ? t('All fields inherit from the personality. Hover over a field to unlink for independent editing')
                                                    : sprintf(t('%d fields unlinked - custom values'), personalityUnlinkedCount)}
                                            </p>
                                        </div>
                                    </div>

                                    <div className="flex items-center gap-2">
                                        {isPersonalityLinked && (
                                            <button
                                                type="button"
                                                onClick={handleUnlinkAllPersonality}
                                                className="flex items-center gap-2 px-4 py-2 bg-amber-500 text-white rounded-lg hover:bg-amber-600 transition-colors font-medium"
                                            >
                                                <Link2Off className="w-4 h-4" />
                                                {t('Unlink all for independent editing')}
                                            </button>
                                        )}

                                        {!isPersonalityLinked && (
                                            <div className="flex items-center gap-3">
                                                <div className="flex items-center gap-2 text-amber-700">
                                                    <AlertCircle className="w-4 h-4" />
                                                    <span className="text-sm">{t("Custom values")}</span>
                                                </div>
                                                <button
                                                    type="button"
                                                    onClick={() => setShowCreatePersonalityPresetModal(true)}
                                                    className="flex items-center gap-2 px-4 py-2 bg-green-500 text-white rounded-lg hover:bg-green-600 transition-colors font-medium"
                                                >
                                                    <Plus className="w-4 h-4" />
                                                    {t("Create New Preset")}
                                                </button>
                                                <button
                                                    type="button"
                                                    onClick={handleRelinkAllPersonality}
                                                    className="flex items-center gap-2 px-4 py-2 bg-blue-500 text-white rounded-lg hover:bg-blue-600 transition-colors font-medium"
                                                >
                                                    <Link2 className="w-4 h-4" />
                                                    {t("Relink to Preset")}
                                                </button>
                                            </div>
                                        )}
                                    </div>
                                </div>
                            </CardContent>
                        </Card>
                    )}

                    {/* System Prompt */}
                    <LockedPersonalityCard
                        title={t('Personality Definition (System Prompt)')}
                        isLocked={isPersonalityLinked}
                        onUnlockClick={handleUnlinkAllPersonality}
                    >
                            <LinkedPersonalityField
                                label={t('System Instructions')}
                                fieldKey="system_prompt"
                                isLinked={isPersonalityFieldLinked('system_prompt')}
                                linkedName={selectedPersonalityName}
                                onUnlink={() => unlinkPersonalityField('system_prompt')}
                            >
                                <textarea
                                    value={isPersonalityFieldLinked('system_prompt') && selectedPersonality
                                        ? (selectedPersonality.system_prompt || '')
                                        : formData.system_prompt}
                                    onChange={(e) => handlePersonalityFieldChange('system_prompt', e.target.value)}
                                    disabled={isPersonalityFieldLinked('system_prompt')}
                                    placeholder={t('Describe the personality, communication style, and instructions for the bot...')}
                                    rows={8}
                                    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 disabled:bg-gray-50"
                                />
                            </LinkedPersonalityField>
                    </LockedPersonalityCard>

                    {/* Tone Selection */}
                    <LockedPersonalityCard
                        title={t('Conversation Tone')}
                        isLocked={isPersonalityLinked}
                        onUnlockClick={handleUnlinkAllPersonality}
                    >
                            <LinkedPersonalityField
                                label={t('Select Tone')}
                                fieldKey="tone"
                                isLinked={isPersonalityFieldLinked('tone')}
                                linkedName={selectedPersonalityName}
                                onUnlink={() => unlinkPersonalityField('tone')}
                            >
                                <select
                                    value={isPersonalityFieldLinked('tone') && selectedPersonality
                                        ? (selectedPersonality.tone || 'friendly')
                                        : formData.tone}
                                    onChange={(e) => handlePersonalityFieldChange('tone', e.target.value)}
                                    disabled={isPersonalityFieldLinked('tone')}
                                    className="w-full px-4 py-2 border border-gray-300 rounded-lg disabled:bg-gray-50"
                                >
                                    {tones.map((tone) => (
                                        <option key={tone.id} value={tone.slug}>
                                            {tone.emoji} {tone.name}
                                        </option>
                                    ))}
                                    {tones.length === 0 && (
                                        <>
                                            <option value="friendly">😊 {t('Friendly')}</option>
                                            <option value="professional">👔 {t('Professional')}</option>
                                            <option value="casual">🎉 {t('Casual')}</option>
                                        </>
                                    )}
                                </select>
                            </LinkedPersonalityField>
                    </LockedPersonalityCard>

                    {/* Behavior Checkboxes */}
                    <LockedPersonalityCard
                        title={t('Behavior Settings')}
                        isLocked={isPersonalityLinked}
                        onUnlockClick={handleUnlinkAllPersonality}
                    >
                            <p className="text-xs text-gray-500 -mt-2">
                                {t('These settings affect the bot behavior in practice')}
                            </p>

                            {/* Proactive Engagement */}
                            <LinkedCheckboxField
                                label={t('Proactive Engagement')}
                                fieldKey="proactive_engagement"
                                icon={<Zap className="w-4 h-4 text-yellow-600" />}
                                tooltip={t('The bot will proactively initiate conversation with visitors (triggers)')}
                                checked={isPersonalityFieldLinked('proactive_engagement') && selectedPersonality
                                    ? Number(selectedPersonality.proactive_engagement) === 1
                                    : formData.proactive_engagement}
                                isLinked={isPersonalityFieldLinked('proactive_engagement')}
                                linkedName={selectedPersonalityName}
                                onUnlink={() => unlinkPersonalityField('proactive_engagement')}
                                onChange={(v) => handlePersonalityFieldChange('proactive_engagement', v)}
                            />

                            {/* Proactive Delay - only show when proactive is enabled */}
                            {formData.proactive_engagement && (
                                <div className="mr-7 mt-2">
                                    <label className="flex items-center gap-3 text-sm text-gray-600">
                                        <span>{t('Delay before engagement:')}</span>
                                        <input
                                            type="number"
                                            min={1}
                                            max={60}
                                            value={isPersonalityFieldLinked('proactive_delay_seconds') && selectedPersonality
                                                ? (Number(selectedPersonality.proactive_delay_seconds) || formData.proactive_delay_seconds)
                                                : formData.proactive_delay_seconds}
                                            onChange={(e) => handlePersonalityFieldChange('proactive_delay_seconds', Math.max(1, Math.min(60, parseInt(e.target.value) || 4)))}
                                            disabled={isPersonalityFieldLinked('proactive_delay_seconds')}
                                            className="w-16 px-2 py-1 border border-gray-300 rounded text-center text-sm disabled:opacity-50"
                                        />
                                        <span>{t('seconds')}</span>
                                    </label>
                                    <p className="text-xs text-gray-400 mt-1">
                                        {t('How long to wait after bot response before sending a proactive message')}
                                    </p>
                                    {isPersonalityFieldLinked('proactive_delay_seconds') && selectedPersonalityName && (
                                        <p className="text-xs text-gray-500 mt-1">{sprintf(t('Linked to personality "%s"'), selectedPersonalityName)}</p>
                                    )}
                                </div>
                            )}
                    </LockedPersonalityCard>

                    {/* Additional Instructions - linked to personality */}
                    <LockedPersonalityCard
                        title={t('Additional Instructions')}
                        isLocked={isPersonalityFieldLinked('custom_instructions')}
                        onUnlockClick={() => unlinkPersonalityField('custom_instructions')}
                    >
                            <textarea
                                value={isPersonalityFieldLinked('custom_instructions') && selectedPersonality
                                    ? (selectedPersonality.custom_instructions || '')
                                    : formData.custom_instructions}
                                onChange={(e) => handlePersonalityFieldChange('custom_instructions', e.target.value)}
                                placeholder={t("Additional instructions to append to the selected personality...")}
                                rows={3}
                                disabled={isPersonalityFieldLinked('custom_instructions')}
                                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 disabled:opacity-50 disabled:bg-gray-50"
                            />
                            {isPersonalityFieldLinked('custom_instructions') && selectedPersonalityName && (
                                <p className="text-xs text-gray-500 mt-1">{sprintf(t('This value comes from personality "%s".'), selectedPersonalityName)}</p>
                            )}
                    </LockedPersonalityCard>

                    {/* Week 28: Output length cap */}
                    <Card>
                        <CardHeader>
                            <CardTitle>{t('Response Length Limit (characters)')}</CardTitle>
                        </CardHeader>
                        <CardContent className="space-y-3">
                            <p className="text-xs text-gray-500 -mt-2">
                                {t('You can set a lower word limit for this bot than the global one (the global limit is set in plugin settings).')}
                            </p>
                            <div>
                                <label className="block text-sm font-medium text-gray-700 mb-1">
                                    {t('Word limit for this bot (empty = global)')}
                                </label>
                                <input
                                    type="number"
                                    min={1}
                                    max={5000}
                                    value={formData.bot_output_char_limit ?? ''}
                                    onChange={(e) =>
                                        handleChange(
                                            'bot_output_char_limit' as any,
                                            e.target.value === '' ? null : Number(e.target.value)
                                        )
                                    }
                                    className="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-primary-500 focus:border-transparent"
                                />
                                <p className="text-xs text-gray-500 mt-1">
                                    {t('The value will be automatically capped if it exceeds the global limit. The value is in words.')}
                                </p>
                                <p className="text-xs text-gray-500 mt-1">
                                    {t('Widgets (forms, galleries, product cards, etc.) are not counted toward the word limit. The bot will always show relevant widgets even if the text response is short.')}
                                </p>
                            </div>
                        </CardContent>
                    </Card>
                </div>
            )}

            {/* Widgets Tab */}
            {activeTab === 'widgets' && !isNew && (
                <Card data-wizard-id="bot-tab-content">
                    <CardHeader>
                        <CardTitle className="flex items-center gap-2">
                            <Puzzle className="w-5 h-5 text-primary-500" />
                            {t("Widgets")}
                        </CardTitle>
                        <p className="text-sm text-gray-500 mt-1">
                            {t('Assign widgets to the bot - including opening message, forms and more')}
                        </p>
                    </CardHeader>
                    <CardContent>
                        <WidgetAssignment
                            botId={Number(id)}
                            controlledAssignedIds={assignedWidgetIds}
                            onControlledChange={setAssignedWidgetIds}
                        />
                    </CardContent>
                </Card>
            )}

            {/* WooCommerce Tab */}
            {activeTab === 'woocommerce' && wooCommerceActive && (
                <Card className="group">
                    <CardHeader>
                        <CardTitle className="flex items-center gap-2">
                            <ShoppingCart className="w-5 h-5 text-primary-500" />
                            {t('WooCommerce')}
                        </CardTitle>
                    </CardHeader>
                    <CardContent className="space-y-6">
                        {/* Preset Selector */}
                        <div>
                            <label className="block text-sm font-medium text-gray-700 mb-2">
                                {t('WooCommerce Preset')}
                            </label>
                            <p className="text-xs text-gray-500 mb-3">
                                {t('Select a WooCommerce preset to control which products and coupons the bot can recommend.')}
                            </p>
                            <select
                                value={formData.woocommerce_preset_id || ''}
                                onChange={(e) => handleChange('woocommerce_preset_id', e.target.value ? Number(e.target.value) : null)}
                                className="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-primary-500 focus:border-transparent bg-white"
                            >
                                <option value="">{t('None')}</option>
                                {wooPresets.map((preset) => (
                                    <option key={preset.id} value={preset.id}>
                                        {preset.name}
                                        {preset.is_default === 1 ? ' ⭐' : ''}
                                    </option>
                                ))}
                            </select>
                            {wooPresets.length === 0 && (
                                <p className="text-xs text-gray-400 mt-2">
                                    {t('No WooCommerce presets available. Create one on the WooCommerce Settings page.')}
                                </p>
                            )}
                        </div>

                        {/* Preset Actions */}
                        <div className="flex items-center gap-3">
                            <Link
                                to={`/woocommerce-presets/new?returnTo=${encodeURIComponent(`/bots/${id}?tab=woocommerce`)}`}
                                className="inline-flex items-center gap-1.5 text-sm text-primary-600 hover:text-primary-800 transition-colors"
                            >
                                <Plus className="w-4 h-4" />
                                {t('Create New Preset')}
                            </Link>
                            {formData.woocommerce_preset_id && (
                                <Link
                                    to={`/woocommerce-presets/${formData.woocommerce_preset_id}?returnTo=${encodeURIComponent(`/bots/${id}?tab=woocommerce`)}`}
                                    className="inline-flex items-center gap-1.5 text-sm text-primary-600 hover:text-primary-800 transition-colors"
                                >
                                    <Pencil className="w-4 h-4" />
                                    {t('Edit Preset')}
                                </Link>
                            )}
                        </div>

                        {/* Preset Preview Card */}
                        {selectedWooPreset && (
                            <div className="mt-4 bg-gray-50 rounded-xl border border-gray-200 p-5 space-y-4">
                                <h4 className="text-sm font-semibold text-gray-800">{selectedWooPreset.name}</h4>

                                <div className="grid grid-cols-1 sm:grid-cols-2 gap-3">
                                    {/* Product Access */}
                                    <div className="bg-white rounded-lg p-3 border border-gray-100">
                                        <p className="text-xs font-medium text-gray-500 mb-1">{t('Product Access')}</p>
                                        <p className="text-sm text-gray-900">
                                            {selectedWooPreset.product_mode === 'all'
                                                ? t('All products')
                                                : selectedWooPreset.product_mode === 'categories'
                                                    ? (() => {
                                                        const cats = typeof selectedWooPreset.allowed_categories === 'string'
                                                            ? JSON.parse(selectedWooPreset.allowed_categories || '[]')
                                                            : (selectedWooPreset.allowed_categories || [])
                                                        return cats.length + ' ' + t('categories selected')
                                                    })()
                                                    : (() => {
                                                        const prods = typeof selectedWooPreset.specific_product_ids === 'string'
                                                            ? JSON.parse(selectedWooPreset.specific_product_ids || '[]')
                                                            : (selectedWooPreset.specific_product_ids || [])
                                                        return prods.length + ' ' + t('specific products')
                                                    })()
                                            }
                                        </p>
                                    </div>

                                    {/* Product Cards */}
                                    <div className="bg-white rounded-lg p-3 border border-gray-100">
                                        <p className="text-xs font-medium text-gray-500 mb-1">{t('Product Cards')}</p>
                                        {Number(selectedWooPreset.product_card_enabled) === 1 ? (
                                            <span className="inline-flex items-center px-2 py-0.5 rounded-full text-xs font-medium bg-green-100 text-green-800">
                                                {t('Enabled')}
                                            </span>
                                        ) : (
                                            <span className="inline-flex items-center px-2 py-0.5 rounded-full text-xs font-medium bg-gray-100 text-gray-600">
                                                {t('Disabled')}
                                            </span>
                                        )}
                                    </div>

                                    {/* Coupons */}
                                    <div className="bg-white rounded-lg p-3 border border-gray-100">
                                        <p className="text-xs font-medium text-gray-500 mb-1">{t('Coupons')}</p>
                                        {Number(selectedWooPreset.coupon_enabled) === 1 ? (
                                            <span className="inline-flex items-center px-2 py-0.5 rounded-full text-xs font-medium bg-green-100 text-green-800">
                                                {t('Enabled')}
                                            </span>
                                        ) : (
                                            <span className="inline-flex items-center px-2 py-0.5 rounded-full text-xs font-medium bg-gray-100 text-gray-600">
                                                {t('Disabled')}
                                            </span>
                                        )}
                                    </div>

                                    {/* Bundle Builder */}
                                    <div className="bg-white rounded-lg p-3 border border-gray-100">
                                        <p className="text-xs font-medium text-gray-500 mb-1">{t('Bundle Builder')}</p>
                                        {Number(selectedWooPreset.bundle_enabled) === 1 ? (
                                            <div>
                                                <span className="inline-flex items-center px-2 py-0.5 rounded-full text-xs font-medium bg-green-100 text-green-800">
                                                    {t('Enabled')}
                                                </span>
                                                {(selectedWooPreset.bundle_discount_value || selectedWooPreset.bundle_min_products) && (
                                                    <p className="text-xs text-gray-500 mt-1">
                                                        {selectedWooPreset.bundle_discount_value && `${selectedWooPreset.bundle_discount_value}% `}
                                                        {selectedWooPreset.bundle_min_products && selectedWooPreset.bundle_max_products &&
                                                            `${selectedWooPreset.bundle_min_products}-${selectedWooPreset.bundle_max_products} ${t('products')}`
                                                        }
                                                    </p>
                                                )}
                                            </div>
                                        ) : (
                                            <span className="inline-flex items-center px-2 py-0.5 rounded-full text-xs font-medium bg-gray-100 text-gray-600">
                                                {t('Disabled')}
                                            </span>
                                        )}
                                    </div>

                                </div>

                                <div className="pt-2 border-t border-gray-200">
                                    <Link
                                        to={`/woocommerce-presets/${selectedWooPreset.id}?returnTo=${encodeURIComponent(`/bots/${id}?tab=woocommerce`)}`}
                                        className="inline-flex items-center gap-1.5 text-sm text-primary-600 hover:text-primary-800 transition-colors"
                                    >
                                        <Pencil className="w-3.5 h-3.5" />
                                        {t('Edit Preset')}
                                        <ArrowRight className="w-3.5 h-3.5" />
                                    </Link>
                                </div>
                            </div>
                        )}
                    </CardContent>
                </Card>
            )}

            {/* Advanced Tab */}
            {activeTab === 'advanced' && (
                <Card className="group">
                    <CardHeader>
                        <CardTitle>{t('Advanced Settings')}</CardTitle>
                    </CardHeader>
                    <CardContent className="space-y-6">
                        {/* Contact List Selection */}
                        <div>
                            <label className="block text-sm font-medium text-gray-700 mb-2">
                                <Users className="w-4 h-4 inline me-1 text-primary-500" />
                                {t('Contact List')}
                            </label>
                            <p className="text-xs text-gray-500 mb-3">
                                {t('Select a contact list where leads collected by the bot will be saved')}
                            </p>
                            <div className="flex gap-3 items-center">
                                <select
                                    value={formData.contact_list_id || ''}
                                    onChange={(e) => handleChange('contact_list_id', e.target.value ? Number(e.target.value) : null)}
                                    className="flex-1 px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-primary-500 focus:border-transparent bg-white"
                                >
                                    <option value="">{t('Primary list (default)')}</option>
                                    {contactLists.map((list) => (
                                        <option key={list.id} value={list.id}>
                                            {list.name}
                                            {list.is_primary === 1 && ' ⭐'}
                                        </option>
                                    ))}
                                </select>
                                {formData.contact_list_id && (
                                    <Link
                                        to={`/contact-lists?expand=${formData.contact_list_id}&returnTo=${encodeURIComponent(`/bots/${id}?tab=advanced`)}`}
                                        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 contact list")}
                                    >
                                        <Pencil className="w-4 h-4" />
                                        <span className="text-sm font-medium">{t("Edit Preset")}</span>
                                    </Link>
                                )}
                            </div>
                            {contactLists.length === 0 && (
                                <p className="text-xs text-gray-400 mt-2">
                                    {t('No contact lists. Create a new list on the Contact Lists page.')}
                                </p>
                            )}
                        </div>

                        <hr className="border-gray-200" />

                        {/* Knowledge Files Info */}
                        <div className="bg-blue-50 rounded-lg p-4 border border-blue-100">
                            <div className="flex items-start gap-3">
                                <Info className="w-5 h-5 text-blue-600 flex-shrink-0 mt-0.5" />
                                <div>
                                    <p className="text-sm font-medium text-blue-800">{t('Knowledge Files')}</p>
                                    <p className="text-sm text-blue-700 mt-1">
                                        {t('You can upload knowledge files from the Knowledge Base page and assign them to the bot.')}
                                        <br />
                                        {t('Knowledge files allow the bot to answer questions from documents, guides, and content you uploaded.')}
                                    </p>
                                </div>
                            </div>
                        </div>
                    </CardContent>
                </Card>
            )}

            {/* Create Personality Preset Modal */}
            {showCreatePersonalityPresetModal && (
                <div className="fixed inset-0 bg-black/50 flex items-center justify-center z-50 animate-fade-in">
                    <div className="bg-white rounded-xl shadow-2xl w-full max-w-md mx-4 overflow-hidden">
                        {/* Header */}
                        <div className="bg-gradient-to-r from-green-500 to-emerald-600 px-6 py-4 flex items-center justify-between">
                            <h3 className="text-lg font-semibold text-white flex items-center gap-2">
                                <Plus className="w-5 h-5" />
                                {t('Create New Preset (Personality)')}
                            </h3>
                            <button
                                onClick={() => {
                                    setShowCreatePersonalityPresetModal(false)
                                    setNewPersonalityPresetName('')
                                }}
                                className="text-white/80 hover:text-white transition-colors"
                            >
                                <X className="w-5 h-5" />
                            </button>
                        </div>

                        {/* Content */}
                        <div className="p-6">
                            <p className="text-gray-600 mb-4">
                                {t('Create a new Personality (Preset) from the current bot behavior tab settings.')}
                                {t('The new personality will include the tone, prompt, and behavior settings.')}
                            </p>

                            <div className="mb-4">
                                <label className="block text-sm font-medium text-gray-700 mb-2">
                                    {t('Preset Name')}
                                </label>
                                <input
                                    type="text"
                                    value={newPersonalityPresetName}
                                    onChange={(e) => setNewPersonalityPresetName(e.target.value)}
                                    placeholder={t('e.g.: Custom Personality')}
                                    className="w-full px-4 py-3 border border-gray-300 rounded-lg focus:ring-2 focus:ring-green-500 focus:border-green-500 transition-all"
                                    autoFocus
                                />
                            </div>

                            {createPersonalityPresetMutation.error && (
                                <div className="mb-4 p-3 bg-red-50 border border-red-200 rounded-lg text-red-700 text-sm">
                                    {t('An error occurred creating the Preset. Please try again.')}
                                </div>
                            )}
                        </div>

                        {/* Footer */}
                        <div className="bg-gray-50 px-6 py-4 flex items-center justify-end gap-3">
                            <button
                                type="button"
                                onClick={() => {
                                    setShowCreatePersonalityPresetModal(false)
                                    setNewPersonalityPresetName('')
                                }}
                                className="px-4 py-2 text-gray-700 hover:bg-gray-200 rounded-lg transition-colors"
                                disabled={createPersonalityPresetMutation.isPending}
                            >
                                {t("Cancel")}
                            </button>
                            <button
                                type="button"
                                onClick={handleCreatePersonalityPresetFromCurrent}
                                disabled={
                                    !newPersonalityPresetName.trim() ||
                                    createPersonalityPresetMutation.isPending
                                }
                                className="flex items-center gap-2 px-6 py-2 bg-green-500 text-white rounded-lg hover:bg-green-600 disabled:opacity-50 disabled:cursor-not-allowed transition-all font-medium"
                            >
                                {createPersonalityPresetMutation.isPending ? (
                                    <>
                                        <Loader2 className="w-4 h-4 animate-spin" />
                                        {t("Creating...")}
                                    </>
                                ) : (
                                    <>
                                        <Plus className="w-4 h-4" />
                                        {t("Create Preset")}
                                    </>
                                )}
                            </button>
                        </div>
                    </div>
                </div>
            )}
        </div>
    )
}

// Linked Personality Field Component
interface LinkedPersonalityFieldProps {
    label: string
    fieldKey: string
    isLinked: boolean
    linkedName?: string
    onUnlink: () => void
    children: React.ReactNode
}

function LinkedPersonalityField({
    label,
    fieldKey: _fieldKey,
    isLinked,
    linkedName,
    onUnlink,
    children,
}: LinkedPersonalityFieldProps) {
    void _fieldKey
    void onUnlink
    return (
        <div className="relative">
            <div className="flex items-center justify-between mb-2">
                <label className="block text-sm font-medium text-gray-700">
                    {label}
                </label>
            </div>

            {children}

            {isLinked && linkedName && (
                <p className="text-xs text-gray-500 mt-1">{sprintf(t('This value comes from personality "%s".'), linkedName)}</p>
            )}
        </div>
    )
}

// Linked Checkbox Field Component
interface LinkedCheckboxFieldProps {
    label: string
    fieldKey: string
    icon: React.ReactNode
    tooltip: string
    checked: boolean
    isLinked: boolean
    linkedName?: string
    onUnlink: () => void
    onChange: (value: boolean) => void
}

function LinkedCheckboxField({
    label,
    fieldKey: _fieldKey,
    icon,
    tooltip,
    checked,
    isLinked,
    linkedName,
    onUnlink,
    onChange,
}: LinkedCheckboxFieldProps) {
    void _fieldKey
    void onUnlink
    return (
        <div className="group relative p-3 rounded-lg transition-colors hover:bg-gray-50">
            <div className="flex items-center justify-between">
                <label className="flex items-center gap-3 cursor-pointer flex-1">
                    <input
                        type="checkbox"
                        checked={checked}
                        onChange={(e) => onChange(e.target.checked)}
                        disabled={isLinked}
                        className="w-4 h-4 text-primary-600 rounded focus:ring-primary-500 disabled:opacity-50"
                    />
                    <div className="flex items-center gap-2">
                        {icon}
                        <span className="text-sm">{label}</span>
                    </div>
                </label>
            </div>

            {/* Tooltip */}
            <div className="absolute hidden group-hover:block bg-gray-900 text-white text-xs rounded-lg px-3 py-2 -top-12 start-0 w-64 z-20 shadow-lg">
                {tooltip}
                <div className="absolute w-2 h-2 bg-gray-900 rotate-45 -bottom-1 start-4"></div>
            </div>

            {isLinked && linkedName && <p className="text-xs text-gray-500 mt-1 ms-7">{sprintf(t('Linked to personality "%s"'), linkedName)}</p>}
        </div>
    )
}


