import { useState, useEffect, useRef, useCallback } from 'react'
import { useParams, useNavigate, useSearchParams, Link } from 'react-router-dom'
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query'
import { t, sprintf } from '@/lib/i18n'
import { 
    ArrowRight, 
    Save, 
    Plus, 
    Trash2, 
    GripVertical,
    FileText,
    MessageCircle,
    Calendar,
    ShoppingBag,
    Ticket,
    Image,
    Youtube,
    Upload,
    Bot,
    Users,
    Gift,
    User,
    AlertTriangle,
    Settings,
    ChevronUp,
    ChevronDown,
    CalendarClock,
} from 'lucide-react'
import { IconPicker } from '@/components/common/IconPicker'
import type { MeetingTypeIconName } from '@/types/widget'
import { apiClient } from '@/api/client'
import { useLanguage } from '@/contexts/LanguageContext'
import { AvailabilityScheduleEditor, type MeetingAvailability, parseMeetingAvailabilitySafely } from '@/components/contacts/AvailabilityScheduleEditor'
import { PageHeader } from '@/components/layout/PageHeader'
import { Card, CardContent, CardHeader, CardTitle } from '@/components/common/Card'
import { Button } from '@/components/common/Button'
import { ToggleSwitch } from '@/components/common/ToggleSwitch'
import { LinkedBotsSection as SharedLinkedBotsSection } from '@/components/common/LinkedBotsSection'
import { UnsavedChangesModal } from '@/components/common/UnsavedChangesModal'
import { useUnsavedChanges } from '@/hooks/useUnsavedChanges'
import { widgetsApi } from '@/api/widgets'
import type { 
    WidgetType, 
    FormField, 
    FieldType,
    FormWidgetConfig,
    WhatsAppWidgetConfig,
    CalendarWidgetConfig,
    ValidationRules,
} from '@/types/widget'
import { isWidgetFullyConfigured, WIDGET_CONFIG_HINTS } from '@/types/widget'
import { BundleBuilderSettings } from '@/components/widgets/BundleBuilderSettings'

function getWidgetTypeConfig(): Record<WidgetType, { label: string; icon: typeof FileText; color: string }> {
    return {
        form: { label: t('Dynamic Form'), icon: FileText, color: 'bg-blue-100 text-blue-700' },
        whatsapp: { label: t('WhatsApp'), icon: MessageCircle, color: 'bg-green-100 text-green-700' },
        calendar_meeting: { label: t('Calendar'), icon: Calendar, color: 'bg-teal-100 text-teal-700' },
        product_card: { label: t('Product Card'), icon: ShoppingBag, color: 'bg-orange-100 text-orange-700' },
        coupon: { label: t('Coupon'), icon: Ticket, color: 'bg-yellow-100 text-yellow-700' },
        gallery: { label: t('Gallery'), icon: Image, color: 'bg-pink-100 text-pink-700' },
        youtube: { label: t('YouTube'), icon: Youtube, color: 'bg-red-100 text-red-700' },
        bundle_builder: { label: t('Bundle Builder'), icon: Gift, color: 'bg-purple-100 text-purple-700' },
        contact_card: { label: t('Contact Card'), icon: User, color: 'bg-indigo-100 text-indigo-700' },
    }
}

function getFieldTypeOptions(): Array<{ value: FieldType; label: string }> {
    return [
        { value: 'text', label: t('Text') },
        { value: 'email', label: t('Email') },
        { value: 'phone', label: t('Phone') },
        { value: 'textarea', label: t('Textarea') },
        { value: 'select', label: t('Select') },
        { value: 'date', label: t('Date') },
        { value: 'number', label: t('Number') },
        { value: 'checkbox', label: t('Checkbox') },
    ]
}

function getDefaultBotDescriptions(): Record<string, string> {
    return {
        form: t('When the customer wants to leave contact details or request a callback'),
        calendar_meeting: t('When the customer wants to schedule or arrange a meeting or call'),
        gallery: t('When the customer wants to see an image gallery'),
        whatsapp: t('When the customer wants to contact via WhatsApp'),
        youtube: t('When the customer wants to watch a video'),
        contact_card: t('When the customer wants to see contact details or speak with a representative'),
    }
}

interface FormData {
    name: string
    type: WidgetType
    description: string  // Bot description - when to use
    is_active: boolean
    config: Record<string, unknown>
    fields: FormField[]
}

const getDefaultFormData = (type: WidgetType): FormData => ({
    name: '',
    type,
    description: getDefaultBotDescriptions()[type] || '',
    is_active: false, // Start disabled — widget must be fully configured before activation
    config: type === 'form' 
        ? { submit_text: t('Submit'), success_message: t('Thank you! We will get back to you soon'), show_labels: true }
        : type === 'whatsapp'
        ? { contacts: [], message_template: t('Hi, I reached out through the bot on the website'), show_all_contacts: false }
        : type === 'calendar_meeting'
        ? { title: t('Book a meeting'), duration_options: [30], require_name: true, require_phone: true, min_notice_hours: 1, show_meeting_type_selection: true, meeting_types: [
            { id: 'frontal', label: t('In-person meeting'), icon: 'user', require_name: true, require_phone: true, require_email: false, min_notice_hours: 1 },
            { id: 'phone', label: t('Phone meeting'), icon: 'phone', require_name: true, require_phone: true, require_email: false, min_notice_hours: 1 },
            { id: 'video', label: t('Virtual meeting'), icon: 'video', require_name: true, require_phone: true, require_email: true, min_notice_hours: 1 },
        ] }
        : type === 'product_card'
        ? { products: [] }
        : type === 'coupon'
        ? { coupons: [], title: t('Coupons for you') }
        : type === 'bundle_builder'
        ? { 
            categories: [],
            exclude_categories: [],
            min_products: 2,
            max_products: 5,
            bundle_discount_percent: 10,
            show_savings: true,
            allow_customization: true,
            intro_message: t('Let me build the perfect bundle for you!'),
            success_message: t('I found a great bundle for you!'),
        }
        : type === 'contact_card'
        ? { 
            contact_list_ids: [],
            display_mode: 'first',
        }
        : {},
    fields: [],
})

export function WidgetDetail() {
    const { id } = useParams()
    const [searchParams] = useSearchParams()
    const navigate = useNavigate()
    const queryClient = useQueryClient()
    const { currentLanguage } = useLanguage()
    const isNew = !id || id === 'new'
    const typeFromUrl = searchParams.get('type') as WidgetType | null
    const returnTo = searchParams.get('returnTo')

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

    const [formData, setFormData] = useState<FormData>(
        getDefaultFormData(typeFromUrl || 'form')
    )
    const [isSaving, setIsSaving] = useState(false)
    const [showSavedAnimation, setShowSavedAnimation] = useState(false)
    const [isDataLoaded, setIsDataLoaded] = useState(false)
    const [saveErrorMessage, setSaveErrorMessage] = useState<string | null>(null)

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

    // Fetch widget if editing
    const { data: widgetData, isLoading } = useQuery({
        queryKey: ['widget', id, currentLanguage],
        queryFn: () => widgetsApi.getWidget(Number(id)),
        enabled: !isNew && !!id,
    })

    // Create mutation
    const createWidget = useMutation({
        mutationFn: (data: typeof formData) => widgetsApi.createWidget({
            name: data.name,
            type: data.type,
            description: data.description || undefined,
            is_active: data.is_active,
            config: data.config,
            fields: data.type === 'form' ? data.fields : undefined,
            language: currentLanguage,
        } as any),
        onSuccess: (response) => {
            queryClient.invalidateQueries({ queryKey: ['widgets'] })
            const newId = response?.data?.widget?.id
            if (newId) {
                navigate(`/widgets/${newId}`)
            } else {
                navigate('/widgets')
            }
        },
    })

    // Update mutation
    const updateWidget = useMutation({
        mutationFn: (data: typeof formData) => widgetsApi.updateWidget(Number(id), {
            name: data.name,
            description: data.description || undefined,
            is_active: data.is_active,
            config: data.config,
            fields: data.type === 'form' ? data.fields : undefined,
        }),
        onSuccess: () => {
            queryClient.invalidateQueries({ queryKey: ['widgets'] })
            queryClient.invalidateQueries({ queryKey: ['widget', id] })
        },
    })

    // Load widget data
    useEffect(() => {
        if (widgetData?.data?.widget) {
            // Fix: Skip overwriting formData with server response right after a save.
            if (justSavedRef.current) {
                justSavedRef.current = false
                return
            }
            const w = widgetData.data.widget
            setFormData({
                name: w.name || '',
                type: w.type as WidgetType,
                description: w.description || '',
                is_active: !!w.is_active,
                config: (w.config as Record<string, unknown>) || {},
                fields: w.fields || [],
            })
            setIsDataLoaded(true)
        }
    }, [widgetData])

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

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

    const handleConfigChange = (key: string, value: unknown) => {
        setFormData((prev) => ({
            ...prev,
            config: { ...prev.config, [key]: value },
        }))
    }

    const handleSave = async () => {
        if (!formData.name) {
            alert(t('Please enter a widget name'))
            return
        }

        setSaveErrorMessage(null)

        // If trying to save as active, validate config completeness client-side
        // and auto-disable if not fully configured.
        let dataToSave = formData
        const tempWidget = {
            ...formData,
            field_count: formData.fields?.length ?? 0,
        }
        if (formData.is_active && !isWidgetFullyConfigured(tempWidget as any)) {
            dataToSave = { ...formData, is_active: false }
            setFormData(dataToSave)
        }
        
        setIsSaving(true)
        try {
            if (isNew) {
                await createWidget.mutateAsync(dataToSave)
            } else {
                await updateWidget.mutateAsync(dataToSave)
                // Fix: Tell the load effect to skip overwriting formData on the next refetch
                justSavedRef.current = true
                // Show cute robot animation on successful save
                saveCooldownRef.current = true
                setShowSavedAnimation(true)
                setTimeout(() => {
                    setShowSavedAnimation(false)
                    saveCooldownRef.current = false
                }, 2000)
                // Reset original data after successful save
                setOriginalData()
            }
        } catch (error: any) {
            console.error('Save error:', error)
            // Extract error message from API response
            const msg = error?.response?.data?.message
                || error?.data?.message
                || error?.message
                || t('Error saving')
            setSaveErrorMessage(msg)
        } finally {
            setIsSaving(false)
        }
    }

    const widgetType = formData.type
    const typeConfig = getWidgetTypeConfig()[widgetType]
    const Icon = typeConfig?.icon || FileText

    // Fetch WooCommerce data for bundle_builder widget
    const isWooActive = !!(window as any).boostbotAdmin?.woocommerce_active
    const shouldFetchWooData = widgetType === 'bundle_builder' && isWooActive

    const [bbCategories, setBbCategories] = useState<Array<{ id: number; slug: string; name: string; count: number }>>([])
    const [bbCoupons, setBbCoupons] = useState<Array<{ id: number; code: string; discount_type: string; amount: number }>>([])

    useEffect(() => {
        if (!shouldFetchWooData) return
        let cancelled = false

        const fetchWooData = async () => {
            try {
                const [catResp, couponResp] = await Promise.all([
                    apiClient.get<{ data: { categories: any[] } }>('woocommerce/categories', { language: currentLanguage }),
                    apiClient.get<{ data: { coupons: any[] } }>('woocommerce/available-coupons'),
                ])
                if (!cancelled) {
                    setBbCategories(catResp?.data?.categories || [])
                    setBbCoupons(
                        (couponResp?.data?.coupons || []).map((c: any) => ({
                            id: c.id,
                            code: c.code,
                            discount_type: c.discount_type,
                            amount: c.discount_amount ?? c.amount ?? 0,
                        }))
                    )
                }
            } catch (err) {
                console.error('[BoostBot] Failed to fetch WooCommerce data for bundle builder:', err)
            }
        }

        fetchWooData()
        return () => { cancelled = true }
    }, [shouldFetchWooData, currentLanguage])

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

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

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

            <PageHeader
                title={isNew ? sprintf(t('New %s'), typeConfig?.label || t('Widget')) : sprintf(t('Edit %s'), formData.name)}
                subtitle={typeConfig?.label}
            >
                <div className="flex items-center gap-3">
                    <Button variant="outline" onClick={handleBack}>
                        <ArrowRight className="w-4 h-4 me-2" />
                        {t('Back')}
                    </Button>
                    
                    {/* Active toggle */}
                    {!isNew && (() => {
                        const tempWidget = { ...formData, field_count: formData.fields?.length ?? 0 }
                        const canActivate = isWidgetFullyConfigured(tempWidget as any)
                        return (
                            <div className="relative flex items-center gap-2 px-3 py-2 bg-gray-50 rounded-lg border group">
                                <span className="text-sm text-gray-600">
                                    {formData.is_active ? t('Active') : t('Off')}
                                </span>
                                <ToggleSwitch
                                    checked={Boolean(formData.is_active)}
                                    onChange={(checked) => {
                                        if (checked && !canActivate) return
                                        setFormData(prev => ({ ...prev, is_active: checked }))
                                    }}
                                    disabled={!canActivate && !formData.is_active}
                                    size="sm"
                                    ariaLabel={!canActivate ? t('Cannot activate - configuration missing') : formData.is_active ? t('Deactivate widget') : t('Activate widget')}
                                />
                                {!canActivate && !formData.is_active && (
                                    <div className="absolute end-0 top-full mt-1 z-30 w-52 bg-gray-800 text-white text-xs rounded-lg px-3 py-2 shadow-lg opacity-0 group-hover:opacity-100 transition-opacity pointer-events-none">
                                        {t(WIDGET_CONFIG_HINTS[formData.type] || 'Widget configuration must be completed')}
                                    </div>
                                )}
                            </div>
                        )
                    })()}
                    
                    <button
                        onClick={handleSave}
                        disabled={isSaving || !formData.name}
                        className={`flex items-center gap-2 px-4 py-2 rounded-lg transition-all disabled:opacity-50 disabled:cursor-not-allowed ${
                            showSavedAnimation 
                                ? 'bg-green-500 hover:bg-green-600' 
                                : (hasUnsavedChanges && !saveCooldownRef.current)
                                    ? 'bg-amber-500 hover:bg-amber-600 animate-pulse'
                                    : 'bg-primary-600 hover:bg-primary-700'
                        } text-white`}
                    >
                        {showSavedAnimation ? (
                            <Bot className="w-4 h-4 animate-wiggle" />
                        ) : (
                            <Save className="w-4 h-4" />
                        )}
                        {isSaving ? t('Saving...') : showSavedAnimation ? t('Saved!') + ' ✓' : (hasUnsavedChanges && !saveCooldownRef.current) ? t('Save Changes') : t('Save')}
                    </button>
                </div>
            </PageHeader>

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

            {/* Save error banner */}
            {saveErrorMessage && (
                <div className="bg-red-50 border border-red-200 rounded-lg p-3 flex items-center gap-2 text-sm text-red-700">
                    <AlertTriangle className="w-4 h-4 flex-shrink-0" />
                    <span>{saveErrorMessage}</span>
                    <button 
                        onClick={() => setSaveErrorMessage(null)} 
                        className="ms-auto text-red-400 hover:text-red-600"
                    >
                        ✕
                    </button>
                </div>
            )}

            <div className="space-y-6">
                {/* Basic Info */}
                <Card>
                    <CardContent className="space-y-4 pt-6">
                        {/* Widget type badge */}
                        <div className="flex items-center justify-between mb-2">
                            <div className={`inline-flex items-center gap-2 px-3 py-1.5 rounded-full text-sm font-medium ${typeConfig?.color || 'bg-gray-100'}`}>
                                <Icon className="w-4 h-4" />
                                <span>{typeConfig?.label}</span>
                            </div>
                            {!isNew && (
                                <span className="text-xs text-gray-400">{t('Type cannot be changed')}</span>
                            )}
                        </div>

                        <div>
                            <label className="block text-sm font-medium mb-1">
                                {t('Widget Name')} <span className="text-red-500">*</span>
                            </label>
                            <input
                                type="text"
                                value={formData.name}
                                onChange={(e) => handleChange('name', e.target.value)}
                                placeholder={
                                    widgetType === 'contact_card' ? t('e.g.: Contact Card') :
                                    widgetType === 'form' ? t('e.g.: Contact Form') :
                                    widgetType === 'whatsapp' ? t('e.g.: Sales WhatsApp') :
                                    widgetType === 'gallery' ? t('e.g.: Portfolio Gallery') :
                                    widgetType === 'youtube' ? t('e.g.: Tutorial Video') :
                                    widgetType === 'calendar_meeting' ? t('e.g.: Meeting Calendar') :
                                    t('e.g.: Widget Name')
                                }
                                className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-primary-500 focus:border-primary-500"
                            />
                        </div>

                        <div>
                            <label className="block text-sm font-medium mb-1">
                                {t('Bot Description (when to use)')}
                            </label>
                            <textarea
                                value={formData.description}
                                onChange={(e) => handleChange('description', e.target.value)}
                                placeholder={getDefaultBotDescriptions()[widgetType] || t("Describe when the bot should display this widget")}
                                rows={2}
                                className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-primary-500 focus:border-primary-500"
                            />
                            <p className="text-xs text-gray-500 mt-1">
                                {t('The description helps the bot understand when to display this widget in a conversation. If left empty, a default description tailored to the widget type will be used.')}
                            </p>
                        </div>

                    </CardContent>
                </Card>

                {/* Type-specific config */}
                {widgetType === 'form' && (
                    <FormWidgetEditor 
                        config={formData.config as FormWidgetConfig}
                        fields={formData.fields}
                        onConfigChange={handleConfigChange}
                        onFieldsChange={(fields) => handleChange('fields', fields)}
                    />
                )}

                {widgetType === 'whatsapp' && (
                    <WhatsAppWidgetEditor
                        config={formData.config as unknown as WhatsAppWidgetConfig}
                        onConfigChange={handleConfigChange}
                    />
                )}

                {widgetType === 'calendar_meeting' && (
                    <CalendarWidgetEditor
                        config={formData.config as unknown as CalendarWidgetConfig}
                        onConfigChange={handleConfigChange}
                        onGhostCleaned={setOriginalData}
                    />
                )}

                {widgetType === 'youtube' && (
                    <YouTubeWidgetEditor
                        config={formData.config as Record<string, unknown>}
                        onConfigChange={handleConfigChange}
                    />
                )}

                {widgetType === 'gallery' && (
                    <GalleryWidgetEditor
                        config={formData.config as Record<string, unknown>}
                        onConfigChange={handleConfigChange}
                    />
                )}

                {widgetType === 'coupon' && (
                    <CouponWidgetEditor
                        config={formData.config as Record<string, unknown>}
                        onConfigChange={handleConfigChange}
                    />
                )}

                {widgetType === 'bundle_builder' && (
                    <Card>
                        <CardContent className="pt-6">
                            <BundleBuilderSettings
                                config={formData.config as Partial<Record<string, unknown>>}
                                onChange={(newConfig) => {
                                    setFormData((prev) => ({
                                        ...prev,
                                        config: newConfig as Record<string, unknown>,
                                    }))
                                }}
                                categories={bbCategories}
                                coupons={bbCoupons}
                                language={currentLanguage}
                            />
                        </CardContent>
                    </Card>
                )}

                {widgetType === 'contact_card' && (
                    <ContactCardWidgetEditor
                        config={formData.config as Record<string, unknown>}
                        onConfigChange={handleConfigChange}
                    />
                )}

                {/* Linked Bots Section */}
                {!isNew && (
                    <SharedLinkedBotsSection entityType="widget" entityId={Number(id)} />
                )}
            </div>
        </div>
    )
}

// Field Type-Specific Settings Component
interface FieldTypeSettingsProps {
    field: FormField
    onUpdate: (updates: Partial<FormField>) => void
}

function FieldTypeSettings({ field, onUpdate }: FieldTypeSettingsProps) {
    const { field_type } = field
    // Handle null/undefined safely - database may return null
    const options = field.options ?? []
    const validation_rules = field.validation_rules ?? {}

    const updateOptions = (newOptions: string[]) => {
        onUpdate({ options: newOptions })
    }

    const updateValidation = (key: keyof ValidationRules, value: unknown) => {
        onUpdate({ validation_rules: { ...validation_rules, [key]: value } })
    }

    // Select field - needs options list
    // Note: checkbox is a single true/false field (e.g., "I agree to terms"), not multi-option
    if (field_type === 'select') {
        return (
            <div className="bg-blue-50/50 rounded p-2 border border-blue-100">
                <label className="block text-xs text-blue-700 font-medium mb-1">
                    {t('Selection Options')}
                </label>
                <div className="space-y-1">
                    {options.map((opt, idx) => (
                        <div key={idx} className="flex gap-1">
                            <input
                                type="text"
                                value={opt}
                                onChange={(e) => {
                                    const newOpts = [...options]
                                    newOpts[idx] = e.target.value
                                    updateOptions(newOpts)
                                }}
                                placeholder={sprintf(t('Option %d'), idx + 1)}
                                className="flex-1 px-2 py-1 text-xs border border-gray-300 rounded focus:ring-1 focus:ring-blue-500"
                            />
                            <button
                                type="button"
                                onClick={() => updateOptions(options.filter((_, i) => i !== idx))}
                                className="px-1.5 text-red-500 hover:bg-red-50 rounded text-xs"
                            >
                                ✕
                            </button>
                        </div>
                    ))}
                    <button
                        type="button"
                        onClick={() => updateOptions([...options, ''])}
                        className="text-xs text-blue-600 hover:underline"
                    >
                        + {t('Add Option')}
                    </button>
                </div>
            </div>
        )
    }

    // Number field - min, max, step
    if (field_type === 'number') {
        return (
            <div className="bg-green-50/50 rounded p-2 border border-green-100">
                <label className="block text-xs text-green-700 font-medium mb-1">{t('Number Settings')}</label>
                <div className="grid grid-cols-3 gap-2">
                    <div>
                        <label className="block text-xs text-gray-500">{t('Minimum')}</label>
                        <input
                            type="number"
                            value={validation_rules.min ?? ''}
                            onChange={(e) => updateValidation('min', e.target.value ? Number(e.target.value) : undefined)}
                            placeholder={t('None')}
                            className="w-full px-2 py-1 text-xs border border-gray-300 rounded focus:ring-1 focus:ring-green-500"
                        />
                    </div>
                    <div>
                        <label className="block text-xs text-gray-500">{t('Maximum')}</label>
                        <input
                            type="number"
                            value={validation_rules.max ?? ''}
                            onChange={(e) => updateValidation('max', e.target.value ? Number(e.target.value) : undefined)}
                            placeholder={t('None')}
                            className="w-full px-2 py-1 text-xs border border-gray-300 rounded focus:ring-1 focus:ring-green-500"
                        />
                    </div>
                    <div>
                        <label className="block text-xs text-gray-500">{t('Default')}</label>
                        <input
                            type="number"
                            value={field.default_value ?? ''}
                            onChange={(e) => onUpdate({ default_value: e.target.value ? Number(e.target.value) : undefined })}
                            placeholder={t('Empty')}
                            className="w-full px-2 py-1 text-xs border border-gray-300 rounded focus:ring-1 focus:ring-green-500"
                        />
                    </div>
                </div>
            </div>
        )
    }

    // Textarea field - rows, max length
    if (field_type === 'textarea') {
        return (
            <div className="bg-purple-50/50 rounded p-2 border border-purple-100">
                <label className="block text-xs text-purple-700 font-medium mb-1">{t('Textarea Settings')}</label>
                <div className="grid grid-cols-2 gap-2">
                    <div>
                        <label className="block text-xs text-gray-500">{t('Rows')}</label>
                        <input
                            type="number"
                            value={field.rows ?? 3}
                            onChange={(e) => onUpdate({ rows: e.target.value ? Number(e.target.value) : 3 })}
                            min={1}
                            max={10}
                            className="w-full px-2 py-1 text-xs border border-gray-300 rounded focus:ring-1 focus:ring-purple-500"
                        />
                    </div>
                    <div>
                        <label className="block text-xs text-gray-500">{t('Maximum Length (characters)')}</label>
                        <input
                            type="number"
                            value={validation_rules.max_length ?? ''}
                            onChange={(e) => updateValidation('max_length', e.target.value ? Number(e.target.value) : undefined)}
                            placeholder={t('Unlimited')}
                            className="w-full px-2 py-1 text-xs border border-gray-300 rounded focus:ring-1 focus:ring-purple-500"
                        />
                    </div>
                </div>
            </div>
        )
    }

    // Text field - kept simple, no extra settings

    // Date field - min/max date
    if (field_type === 'date') {
        return (
            <div className="bg-yellow-50/50 rounded p-2 border border-yellow-100">
                <div className="flex items-center justify-between mb-1">
                    <label className="block text-xs text-yellow-700 font-medium">{t('Date Settings')}</label>
                    <span className="text-xs text-gray-400">{t('Format: DD/MM/YYYY')}</span>
                </div>
                <div className="grid grid-cols-2 gap-2">
                    <div>
                        <label className="block text-xs text-gray-500">{t('Minimum Date')}</label>
                        <input
                            type="date"
                            value={field.min_date ?? ''}
                            onChange={(e) => onUpdate({ min_date: e.target.value || undefined })}
                            className="w-full px-2 py-1 text-xs border border-gray-300 rounded focus:ring-1 focus:ring-yellow-500"
                        />
                    </div>
                    <div>
                        <label className="block text-xs text-gray-500">{t('Maximum Date')}</label>
                        <input
                            type="date"
                            value={field.max_date ?? ''}
                            onChange={(e) => onUpdate({ max_date: e.target.value || undefined })}
                            className="w-full px-2 py-1 text-xs border border-gray-300 rounded focus:ring-1 focus:ring-yellow-500"
                        />
                    </div>
                </div>
            </div>
        )
    }

    // Phone field - country code default
    if (field_type === 'phone') {
        return (
            <div className="bg-cyan-50/50 rounded p-2 border border-cyan-100">
                <label className="block text-xs text-cyan-700 font-medium mb-1">{t('Phone Settings')}</label>
                <div>
                    <label className="block text-xs text-gray-500">{t('Country Code')}</label>
                    <select
                        value={field.country_code ?? '+972'}
                        onChange={(e) => onUpdate({ country_code: e.target.value })}
                        className="w-full px-2 py-1 text-xs border border-gray-300 rounded focus:ring-1 focus:ring-cyan-500"
                    >
                        <option value="+972">{t('+972 (Israel)')}</option>
                        <option value="+1">{t('+1 (USA)')}</option>
                        <option value="+44">{t('+44 (UK)')}</option>
                        <option value="+49">{t('+49 (Germany)')}</option>
                        <option value="+33">{t('+33 (France)')}</option>
                        <option value="">{t('No prefix')}</option>
                    </select>
                </div>
            </div>
        )
    }

    // Email - no extra settings
    return null
}

// Form Widget Editor Component
interface FormWidgetEditorProps {
    config: FormWidgetConfig
    fields: FormField[]
    onConfigChange: (key: string, value: unknown) => void
    onFieldsChange: (fields: FormField[]) => void
}

function FormWidgetEditor({ config, fields, onConfigChange, onFieldsChange }: FormWidgetEditorProps) {
    const notificationEmailsText = (config.notification_emails || []).join('\n')

    const addField = () => {
        const newField: FormField = {
            field_type: 'text',
            label: '',
            name: `field_${fields.length + 1}`,
            is_required: false,
            placeholder: '',
            sort_order: fields.length,
        }
        onFieldsChange([...fields, newField])
    }

    const updateField = (index: number, updates: Partial<FormField>) => {
        const updated = [...fields]
        updated[index] = { ...updated[index], ...updates }
        // Auto-generate name from label
        if (updates.label && !updated[index].id) {
            const base = updates.label
                .toLowerCase()
                .replace(/[^a-z0-9\s]/g, '')
                .replace(/\s+/g, '_')
                || `field_${index + 1}`
            // Ensure uniqueness against the other fields' names so duplicate/empty labels don't collide
            const taken = new Set(updated.filter((_, i) => i !== index).map((f) => f.name))
            let name = base
            let suffix = 2
            while (taken.has(name)) {
                name = `${base}_${suffix++}`
            }
            updated[index].name = name
        }
        onFieldsChange(updated)
    }

    const removeField = (index: number) => {
        const updated = fields.filter((_, i) => i !== index)
        onFieldsChange(updated)
    }

    const moveField = (fromIndex: number, direction: 'up' | 'down') => {
        const toIndex = direction === 'up' ? fromIndex - 1 : fromIndex + 1
        if (toIndex < 0 || toIndex >= fields.length) return
        
        const updated = [...fields]
        const [removed] = updated.splice(fromIndex, 1)
        updated.splice(toIndex, 0, removed)
        onFieldsChange(updated)
    }

    return (
        <>
            {/* Form Config */}
            <Card>
                <CardHeader>
                    <CardTitle>{t('Form Settings')}</CardTitle>
                </CardHeader>
                <CardContent className="space-y-4">
                    <div className="grid grid-cols-2 gap-4">
                        <div>
                            <label className="block text-sm font-medium mb-1">{t('Submit Button Text')}</label>
                            <input
                                type="text"
                                value={config.submit_text || ''}
                                onChange={(e) => onConfigChange('submit_text', e.target.value)}
                                placeholder={t('Submit')}
                                className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-primary-500 focus:border-primary-500"
                            />
                        </div>
                        <div>
                            <label className="block text-sm font-medium mb-1">{t('Success Message')}</label>
                            <input
                                type="text"
                                value={config.success_message || ''}
                                onChange={(e) => onConfigChange('success_message', e.target.value)}
                                placeholder={t('Thank you! We will get back to you soon')}
                                className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-primary-500 focus:border-primary-500"
                            />
                        </div>
                    </div>
                </CardContent>
            </Card>

            {/* Form Fields */}
            <Card>
                <CardHeader>
                    <CardTitle className="flex items-center justify-between">
                        <span>{t('Form Fields')}</span>
                        <Button size="sm" onClick={addField}>
                            <Plus className="w-4 h-4 me-1" />
                            {t('Add Field')}
                        </Button>
                    </CardTitle>
                </CardHeader>
                <CardContent>
                    {fields.length === 0 ? (
                        <div className="text-center py-8 text-gray-500">
                            <FileText className="w-10 h-10 mx-auto mb-2 opacity-30" />
                            <p className="mb-3">{t('No fields defined yet')}</p>
                            <Button variant="outline" size="sm" onClick={addField}>
                                <Plus className="w-4 h-4 me-1" />
                                {t('Add First Field')}
                            </Button>
                        </div>
                    ) : (
                        <div className="space-y-3">
                            {fields.map((field, index) => (
                                <div 
                                    key={field.id || index}
                                    className="flex items-start gap-3 p-3 bg-gray-50 rounded-lg"
                                >
                                    <div className="flex flex-col gap-1 pt-2">
                                        <button
                                            type="button"
                                            onClick={() => moveField(index, 'up')}
                                            disabled={index === 0}
                                            className="text-gray-400 hover:text-gray-600 disabled:opacity-30"
                                        >
                                            ▲
                                        </button>
                                        <GripVertical className="w-4 h-4 text-gray-300" />
                                        <button
                                            type="button"
                                            onClick={() => moveField(index, 'down')}
                                            disabled={index === fields.length - 1}
                                            className="text-gray-400 hover:text-gray-600 disabled:opacity-30"
                                        >
                                            ▼
                                        </button>
                                    </div>
                                    
                                    <div className="flex-1 space-y-3">
                                        <div className="grid grid-cols-2 md:grid-cols-4 gap-3">
                                            <div>
                                                <label className="block text-xs text-gray-500 mb-1">{t('Label')}</label>
                                                <input
                                                    type="text"
                                                    value={field.label}
                                                    onChange={(e) => updateField(index, { label: e.target.value })}
                                                    placeholder={t('Field name')}
                                                    className="w-full px-2 py-1.5 text-sm border border-gray-300 rounded focus:ring-1 focus:ring-primary-500"
                                                />
                                            </div>
                                            <div>
                                                <label className="block text-xs text-gray-500 mb-1">{t('Type')}</label>
                                                <select
                                                    value={field.field_type}
                                                    onChange={(e) => updateField(index, { field_type: e.target.value as FieldType })}
                                                    className="w-full px-2 py-1.5 text-sm border border-gray-300 rounded focus:ring-1 focus:ring-primary-500"
                                                >
                                                    {getFieldTypeOptions().map((opt) => (
                                                        <option key={opt.value} value={opt.value}>{opt.label}</option>
                                                    ))}
                                                </select>
                                            </div>
                                            <div>
                                                <label className="block text-xs text-gray-500 mb-1">{t('Placeholder Text')}</label>
                                                <input
                                                    type="text"
                                                    value={field.placeholder || ''}
                                                    onChange={(e) => updateField(index, { placeholder: e.target.value })}
                                                    placeholder={t('Placeholder Text')}
                                                    className="w-full px-2 py-1.5 text-sm border border-gray-300 rounded focus:ring-1 focus:ring-primary-500"
                                                />
                                            </div>
                                            <div className="flex items-end gap-3">
                                                <label className="flex items-center gap-1.5 cursor-pointer">
                                                    <input
                                                        type="checkbox"
                                                        checked={field.is_required}
                                                        onChange={(e) => updateField(index, { is_required: e.target.checked })}
                                                        className="w-3.5 h-3.5 text-primary-600 rounded focus:ring-primary-500"
                                                    />
                                                    <span className="text-xs">{t('Required')}</span>
                                                </label>
                                            </div>
                                        </div>
                                        {/* Type-specific settings */}
                                        <FieldTypeSettings
                                            field={field}
                                            onUpdate={(updates) => updateField(index, updates)}
                                        />
                                    </div>

                                    <button
                                        type="button"
                                        onClick={() => removeField(index)}
                                        className="p-1.5 text-gray-400 hover:text-red-500 mt-5"
                                    >
                                        <Trash2 className="w-4 h-4" />
                                    </button>
                                </div>
                            ))}
                        </div>
                    )}
                </CardContent>
            </Card>

            {/* Integrations */}
            <Card>
                <CardHeader>
                    <CardTitle className="flex items-center gap-2">
                        <Settings className="w-4 h-4" />
                        {t('Integrations')}
                    </CardTitle>
                </CardHeader>
                <CardContent className="space-y-4">
                    {/* GA4 Measurement ID */}
                    <div>
                        <label className="block text-sm font-medium mb-1">{t('GA4 Measurement ID')}</label>
                        <input
                            type="text"
                            value={config.ga4_measurement_id || ''}
                            onChange={(e) => {
                                const val = e.target.value.trim()
                                onConfigChange('ga4_measurement_id', val || undefined)
                            }}
                            placeholder="G-XXXXXXXXXX"
                            className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-primary-500 focus:border-primary-500 font-mono text-sm"
                            dir="ltr"
                        />
                        <p className="text-xs text-gray-500 mt-1">
                            {t('When the form is submitted, a')} <code className="bg-gray-100 px-1 rounded">Lead_from_chatbot</code> {t('event will be sent to Google Analytics 4')}
                        </p>
                        {config.ga4_measurement_id && !/^G-[A-Z0-9]+$/i.test(config.ga4_measurement_id) && (
                            <p className="text-xs text-red-500 mt-1 flex items-center gap-1">
                                <AlertTriangle className="w-3 h-3" />
                                {t('Invalid format. Correct format: G-XXXXXXXXXX')}
                            </p>
                        )}
                    </div>

                    {/* Webhook URL */}
                    <div>
                        <label className="block text-sm font-medium mb-1">Webhook URL</label>
                        <input
                            type="url"
                            value={config.webhook_url || ''}
                            onChange={(e) => {
                                const val = e.target.value.trim()
                                onConfigChange('webhook_url', val || undefined)
                            }}
                            placeholder="https://hooks.zapier.com/... or https://hook.eu1.make.com/..."
                            className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-primary-500 focus:border-primary-500 font-mono text-sm"
                            dir="ltr"
                        />
                        <p className="text-xs text-gray-500 mt-1">
                            {t('Send form data to Zapier, Make, n8n or any other webhook service.')}
                            {' '}
                            <Link to="/integrations" className="text-primary-600 hover:underline">
                                {t('You can also set up a global webhook on the Integrations page')}
                            </Link>
                        </p>
                    </div>

                    {/* Notification recipient emails */}
                    <div>
                        <label className="block text-sm font-medium mb-1">{t('Lead Notification Emails')}</label>
                        <textarea
                            value={notificationEmailsText}
                            onChange={(e) => {
                                const raw = e.target.value
                                const emails = raw
                                    .split(/[\n,;]+/)
                                    .map((email) => email.trim())
                                    .filter(Boolean)
                                onConfigChange('notification_emails', emails.length ? emails : undefined)
                            }}
                            placeholder={`sales@example.com\nmanager@example.com`}
                            rows={3}
                            className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-primary-500 focus:border-primary-500 font-mono text-sm"
                            dir="ltr"
                        />
                        <p className="text-xs text-gray-500 mt-1">
                            {t('Each address on a separate line (or comma-separated). When a form is submitted, an email will be sent to all addresses in addition to Webhook and GA4.')}
                        </p>
                    </div>
                </CardContent>
            </Card>
        </>
    )
}

// WhatsApp Widget Editor Component
interface WhatsAppWidgetEditorProps {
    config: WhatsAppWidgetConfig
    onConfigChange: (key: string, value: unknown) => void
}

function WhatsAppWidgetEditor({ config, onConfigChange }: WhatsAppWidgetEditorProps) {
    const contacts = config.contacts || []
    const { currentLanguage } = useLanguage()
    
    const { data: brandCardData } = useQuery({
        queryKey: ['brand-card-global', currentLanguage],
        queryFn: () => apiClient.get<{ data: { brand_card: { whatsapp_number?: string } } }>(
            `brand-card${currentLanguage ? `?language=${currentLanguage}` : ''}`
        ),
    })
    const brandCardWhatsApp = (brandCardData as any)?.data?.brand_card?.whatsapp_number || ''

    const addContact = () => {
        onConfigChange('contacts', [...contacts, { name: '', phone: '', title: '' }])
    }

    const updateContact = (index: number, updates: Partial<typeof contacts[0]>) => {
        const updated = [...contacts]
        updated[index] = { ...updated[index], ...updates }
        onConfigChange('contacts', updated)
    }

    const removeContact = (index: number) => {
        onConfigChange('contacts', contacts.filter((_, i) => i !== index))
    }

    return (
        <Card>
            <CardHeader>
                <CardTitle className="flex items-center justify-between">
                    <span>{t('WhatsApp Contacts')}</span>
                    <Button size="sm" onClick={addContact}>
                        <Plus className="w-4 h-4 me-1" />
                        {t('Add Contact')}
                    </Button>
                </CardTitle>
            </CardHeader>
            <CardContent className="space-y-4">
                <div>
                    <label className="block text-sm font-medium mb-1">{t('Message Template')}</label>
                    <textarea
                        value={config.message_template || ''}
                        onChange={(e) => onConfigChange('message_template', e.target.value)}
                        placeholder={t('Hi, I reached out through the bot on the website...')}
                        rows={2}
                        className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-primary-500 focus:border-primary-500"
                    />
                </div>

                <div className="flex items-center gap-3">
                    <input
                        type="checkbox"
                        id="show_all_contacts"
                        checked={config.show_all_contacts || false}
                        onChange={(e) => onConfigChange('show_all_contacts', e.target.checked)}
                        className="w-4 h-4 text-primary-600 rounded focus:ring-primary-500"
                    />
                    <label htmlFor="show_all_contacts" className="text-sm">
                        {t('Show all contacts (if more than one)')}
                    </label>
                </div>

                {contacts.length === 0 ? (
                    <div className="text-center py-6 text-gray-500 bg-gray-50 rounded-lg">
                        <MessageCircle className="w-8 h-8 mx-auto mb-2 opacity-30" />
                        <p className="mb-2">{t('No contacts defined')}</p>
                        <Button variant="outline" size="sm" onClick={addContact}>
                            <Plus className="w-4 h-4 me-1" />
                            {t('Add Contact')}
                        </Button>
                    </div>
                ) : (
                    <div className="space-y-3">
                        {contacts.map((contact, index) => {
                            const phoneIsEmpty = !contact.phone || contact.phone.trim() === ''
                            const showBrandCardFallback = phoneIsEmpty && brandCardWhatsApp
                            
                            return (
                                <div key={index} className="flex items-start gap-3 p-3 bg-gray-50 rounded-lg">
                                    <div className="flex-1 grid grid-cols-3 gap-3">
                                        <div>
                                            <label className="block text-xs text-gray-500 mb-1">{t('Name')}</label>
                                            <input
                                                type="text"
                                                value={contact.name}
                                                onChange={(e) => updateContact(index, { name: e.target.value })}
                                                placeholder={t('Representative name')}
                                                className="w-full px-2 py-1.5 text-sm border border-gray-300 rounded focus:ring-1 focus:ring-primary-500"
                                            />
                                        </div>
                                        <div>
                                            <label className="block text-xs text-gray-500 mb-1">{t('Phone')}</label>
                                            <input
                                                type="tel"
                                                value={contact.phone}
                                                onChange={(e) => updateContact(index, { phone: e.target.value })}
                                                placeholder={showBrandCardFallback ? brandCardWhatsApp : "972501234567"}
                                                className={`w-full px-2 py-1.5 text-sm border border-gray-300 rounded focus:ring-1 focus:ring-primary-500 ${
                                                    showBrandCardFallback ? 'placeholder:text-gray-600' : ''
                                                }`}
                                            />
                                            {showBrandCardFallback && (
                                                <div className="mt-1 flex items-center gap-1 text-xs text-gray-500">
                                                    <span>{t('Number pulled from Business Card')}</span>
                                                    <Link 
                                                        to="/brand-card" 
                                                        className="text-primary-600 hover:text-primary-700 underline"
                                                    >
                                                        {t('Business Card')}
                                                    </Link>
                                                </div>
                                            )}
                                        </div>
                                        <div>
                                            <label className="block text-xs text-gray-500 mb-1">{t('Role')}</label>
                                            <input
                                                type="text"
                                                value={contact.title || ''}
                                                onChange={(e) => updateContact(index, { title: e.target.value })}
                                                placeholder={t('Sales representative')}
                                                className="w-full px-2 py-1.5 text-sm border border-gray-300 rounded focus:ring-1 focus:ring-primary-500"
                                            />
                                        </div>
                                    </div>
                                    <button
                                        type="button"
                                        onClick={() => removeContact(index)}
                                        className="p-1.5 text-gray-400 hover:text-red-500 mt-5"
                                    >
                                        <Trash2 className="w-4 h-4" />
                                    </button>
                                </div>
                            )
                        })}
                    </div>
                )}
            </CardContent>
        </Card>
    )
}

// Calendar Widget Editor Component
interface CalendarWidgetEditorProps {
    config: CalendarWidgetConfig
    onConfigChange: (key: string, value: unknown) => void
    // Re-baseline the unsaved-changes snapshot after a silent auto-clean so it
    // isn't counted as a user edit (see ghost-contact cleanup below).
    onGhostCleaned?: () => void
}

interface Contact {
    id: number
    list_id: number
    name: string
    email: string | null
    phone: string | null
    title: string | null
    meeting_availability?: {
        meeting_duration?: number
        days?: Record<string, Array<{ start: string; end: string }>>
    } | null
}

interface ContactList {
    id: number
    name: string
    contacts?: Contact[]
}

function CalendarWidgetEditor({ config, onConfigChange, onGhostCleaned }: CalendarWidgetEditorProps) {
    const meetingTypes = config.meeting_types || [
        { id: 'frontal', label: t('In-person meeting'), icon: 'user' as MeetingTypeIconName, require_name: true, require_phone: true, require_email: false, min_notice_hours: 1 },
        { id: 'phone', label: t('Phone meeting'), icon: 'phone' as MeetingTypeIconName, require_name: true, require_phone: true, require_email: false, min_notice_hours: 1 },
        { id: 'video', label: t('Virtual meeting'), icon: 'video' as MeetingTypeIconName, require_name: true, require_phone: true, require_email: true, min_notice_hours: 1 },
    ]
    const associatedContacts = (config.associated_contacts as number[]) || []
    // Track which meeting type is expanded for editing required fields
    const [expandedType, setExpandedType] = useState<string | null>(null)
    // Drag state for priority reordering
    const [dragIndex, setDragIndex] = useState<number | null>(null)
    // Availability editor state
    const [availContactId, setAvailContactId] = useState<number | null>(null)
    const [isSavingAvail, setIsSavingAvail] = useState(false)
    const queryClient = useQueryClient()

    // Fetch contact lists with contacts
    const { data: contactListsData } = useQuery({
        queryKey: ['contact-lists-with-contacts'],
        queryFn: () => apiClient.get<{ success: boolean; data: { lists: ContactList[] } }>('contact-lists?include_contacts=1'),
    })

    const contactLists = contactListsData?.data?.lists || []
    const allContacts = contactLists.flatMap(list => list.contacts || [])

    // Fix #4 — Auto-clean ghost contacts: if a contact was deleted but its ID
    // remains in associated_contacts, silently remove it when data loads.
    const ghostCleanedRef = useRef(false)
    useEffect(() => {
        if (allContacts.length === 0 || associatedContacts.length === 0) return
        const validIds = associatedContacts.filter(id =>
            allContacts.some(c => Number(c.id) === id)
        )
        if (validIds.length !== associatedContacts.length) {
            ghostCleanedRef.current = true
            onConfigChange('associated_contacts', validIds)
        }
    }, [allContacts.length]) // Only re-run when contact list loads / changes

    // After the silent auto-clean is applied to config, re-baseline the
    // unsaved-changes snapshot so the removal isn't flagged as a user edit.
    // Runs on the next render (once config reflects validIds, associatedContacts
    // shrinks) with the freshly-captured onGhostCleaned/setOriginalData closure.
    useEffect(() => {
        if (ghostCleanedRef.current) {
            ghostCleanedRef.current = false
            onGhostCleaned?.()
        }
    }, [associatedContacts.length]) // eslint-disable-line react-hooks/exhaustive-deps

    const handleSaveAvailability = async (data: MeetingAvailability) => {
        if (!availContactId) return
        const contact = allContacts.find(c => Number(c.id) === availContactId)
        if (!contact) return
        setIsSavingAvail(true)
        try {
            await apiClient.put(
                `contact-lists/${contact.list_id}/contacts/${availContactId}`,
                { meeting_availability: data }
            )
            await queryClient.invalidateQueries({ queryKey: ['contact-lists-with-contacts'] })
            // Don't close here — the editor calls onClose() after onSave resolves
        } catch (err) {
            console.error('Failed to save availability:', err)
            throw err // Re-throw so the editor knows the save failed
        } finally {
            setIsSavingAvail(false)
        }
    }

    const moveContact = (fromIndex: number, toIndex: number) => {
        const newOrder = [...associatedContacts]
        const [moved] = newOrder.splice(fromIndex, 1)
        newOrder.splice(toIndex, 0, moved)
        onConfigChange('associated_contacts', newOrder)
    }
    
    const updateMeetingType = (index: number, field: string, value: string | boolean | number | MeetingTypeIconName) => {
        const updated = [...meetingTypes]
        updated[index] = { ...updated[index], [field]: value }
        onConfigChange('meeting_types', updated)
    }
    
    const addMeetingType = () => {
        onConfigChange('meeting_types', [...meetingTypes, { 
            id: `type_${Date.now()}`, 
            label: '', 
            icon: 'user' as MeetingTypeIconName,
            require_name: true,
            require_phone: true,
            require_email: false,
            min_notice_hours: 1,
        }])
    }
    
    const removeMeetingType = (index: number) => {
        onConfigChange('meeting_types', meetingTypes.filter((_, i) => i !== index))
    }

    const toggleContact = (contactId: number) => {
        if (associatedContacts.includes(contactId)) {
            onConfigChange('associated_contacts', associatedContacts.filter(id => id !== contactId))
        } else {
            onConfigChange('associated_contacts', [...associatedContacts, contactId])
        }
    }

    return (
        <div className="space-y-6">
            <Card>
                <CardHeader>
                    <CardTitle>
                        {t('Calendar Settings')}
                    </CardTitle>
                </CardHeader>
                <CardContent className="space-y-4">
                    <div>
                        <label className="block text-sm font-medium mb-1">{t('Title')}</label>
                        <input
                            type="text"
                            value={config.title || ''}
                            onChange={(e) => onConfigChange('title', e.target.value)}
                            placeholder={t('Book a meeting')}
                            className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-primary-500 focus:border-primary-500"
                        />
                    </div>

                    <div>
                        <label className="block text-sm font-medium mb-1">{t('Description (optional)')}</label>
                        <textarea
                            value={config.description || ''}
                            onChange={(e) => onConfigChange('description', e.target.value)}
                            placeholder={t('Short description...')}
                            rows={2}
                            className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-primary-500 focus:border-primary-500"
                        />
                    </div>
                    
                    {/* Meeting Types Section */}
                    <div>
                        <div className="flex items-center justify-between mb-2">
                            <label className="block text-sm font-medium">{t('Meeting Types')}</label>
                            <label className="flex items-center gap-2 text-sm">
                                <input
                                    type="checkbox"
                                    checked={config.show_meeting_type_selection !== false}
                                    onChange={(e) => onConfigChange('show_meeting_type_selection', e.target.checked)}
                                    className="w-4 h-4 text-primary-600 rounded focus:ring-primary-500"
                                />
                                {t('Show type selection')}
                            </label>
                        </div>
                        <div className="space-y-2">
                            {meetingTypes.map((mt, index) => (
                                <div key={mt.id} className="border rounded-lg overflow-hidden">
                                    {/* Meeting type row */}
                                    <div className="flex items-center gap-2 p-2">
                                        <IconPicker
                                            value={(mt.icon as MeetingTypeIconName) || 'user'}
                                            onChange={(icon) => updateMeetingType(index, 'icon', icon)}
                                        />
                                        <input
                                            type="text"
                                            value={mt.label}
                                            onChange={(e) => updateMeetingType(index, 'label', e.target.value)}
                                            placeholder={t('Meeting type name')}
                                            className="flex-1 px-3 py-2 border border-gray-300 rounded-lg"
                                        />
                                        <button
                                            type="button"
                                            onClick={() => setExpandedType(expandedType === mt.id ? null : mt.id)}
                                            className={`p-2 rounded-lg transition-colors ${expandedType === mt.id ? 'bg-primary-50 text-primary-600' : 'text-gray-400 hover:bg-gray-100'}`}
                                            title={t('Required Fields')}
                                        >
                                            <Settings className="w-4 h-4" />
                                        </button>
                                        <button
                                            type="button"
                                            onClick={() => removeMeetingType(index)}
                                            className="p-2 text-red-500 hover:bg-red-50 rounded-lg"
                                        >
                                            <Trash2 className="w-4 h-4" />
                                        </button>
                                    </div>
                                    {/* Expanded: per-type required fields + extra info */}
                                    {expandedType === mt.id && (
                                        <div className="px-3 pb-3 pt-1 bg-gray-50 border-t space-y-3">
                                            <div>
                                                <p className="text-xs text-gray-500 mb-2">{t('Required fields for this meeting type:')}</p>
                                                <div className="flex gap-4">
                                                    <label className="flex items-center gap-2 cursor-pointer">
                                                        <input
                                                            type="checkbox"
                                                            checked={mt.require_name !== false}
                                                            onChange={(e) => updateMeetingType(index, 'require_name', e.target.checked)}
                                                            className="w-4 h-4 text-primary-600 rounded focus:ring-primary-500"
                                                        />
                                                        <span className="text-sm">{t('Name')}</span>
                                                    </label>
                                                    <label className="flex items-center gap-2 cursor-pointer">
                                                        <input
                                                            type="checkbox"
                                                            checked={mt.require_phone !== false}
                                                            onChange={(e) => updateMeetingType(index, 'require_phone', e.target.checked)}
                                                            className="w-4 h-4 text-primary-600 rounded focus:ring-primary-500"
                                                        />
                                                        <span className="text-sm">{t('Phone')}</span>
                                                    </label>
                                                    <label className="flex items-center gap-2 cursor-pointer">
                                                        <input
                                                            type="checkbox"
                                                            checked={mt.require_email === true}
                                                            onChange={(e) => updateMeetingType(index, 'require_email', e.target.checked)}
                                                            className="w-4 h-4 text-primary-600 rounded focus:ring-primary-500"
                                                        />
                                                        <span className="text-sm">{t('Email')}</span>
                                                    </label>
                                                </div>
                                            </div>
                                            {/* Extra info toggle (address/location/description) */}
                                            <div>
                                                <label className="flex items-center gap-2 cursor-pointer mb-2">
                                                    <input
                                                        type="checkbox"
                                                        checked={!!(mt as any).has_extra_info}
                                                        onChange={(e) => {
                                                            const checked = e.target.checked
                                                            const updated = [...meetingTypes]
                                                            updated[index] = { ...updated[index], has_extra_info: checked, ...(!checked ? { extra_info: '' } : {}) }
                                                            onConfigChange('meeting_types', updated)
                                                        }}
                                                        className="w-4 h-4 text-primary-600 rounded focus:ring-primary-500"
                                                    />
                                                    <span className="text-sm">{t('Show extra info (address / location / description)')}</span>
                                                </label>
                                                {!!(mt as any).has_extra_info && (
                                                    <textarea
                                                        value={(mt as any).extra_info || ''}
                                                        onChange={(e) => updateMeetingType(index, 'extra_info', e.target.value)}
                                                        placeholder={t('e.g.: 5 Herzl St., Tel Aviv')}
                                                        rows={2}
                                                        className="w-full px-3 py-2 border border-gray-300 rounded-lg text-sm focus:ring-2 focus:ring-primary-500 focus:border-primary-500"
                                                    />
                                                )}
                                            </div>
                                            {/* Min notice hours */}
                                            <div>
                                                <label className="block text-xs text-gray-500 mb-1">{t('Minimum advance notice (hours)')}</label>
                                                <input
                                                    type="number"
                                                    min={0}
                                                    step={0.5}
                                                    value={mt.min_notice_hours ?? 1}
                                                    onChange={(e) => updateMeetingType(index, 'min_notice_hours', Math.max(0, Number(e.target.value)))}
                                                    className="w-24 px-3 py-1.5 border border-gray-300 rounded-lg text-sm focus:ring-2 focus:ring-primary-500 focus:border-primary-500"
                                                />
                                                <p className="text-xs text-gray-400 mt-1">{t('Customer cannot book a meeting if less than these hours remain')}</p>
                                            </div>
                                        </div>
                                    )}
                                </div>
                            ))}
                            <button
                                type="button"
                                onClick={addMeetingType}
                                className="flex items-center gap-1 px-3 py-1.5 text-sm text-primary-600 hover:bg-primary-50 rounded-lg"
                            >
                                <Plus className="w-4 h-4" /> {t('Add meeting type')}
                            </button>
                        </div>
                    </div>

                    {/* Global required fields (fallback when meeting type selection is disabled) */}
                    {config.show_meeting_type_selection === false && (
                        <div className="space-y-4">
                            <div>
                                <label className="block text-sm font-medium mb-2">{t('Required Fields')}</label>
                                <div className="flex gap-6">
                                    <label className="flex items-center gap-2 cursor-pointer">
                                        <input
                                            type="checkbox"
                                            checked={config.require_name !== false}
                                            onChange={(e) => onConfigChange('require_name', e.target.checked)}
                                            className="w-4 h-4 text-primary-600 rounded focus:ring-primary-500"
                                        />
                                        <span className="text-sm">{t('Require Name')}</span>
                                    </label>
                                    <label className="flex items-center gap-2 cursor-pointer">
                                        <input
                                            type="checkbox"
                                            checked={config.require_phone !== false}
                                            onChange={(e) => onConfigChange('require_phone', e.target.checked)}
                                            className="w-4 h-4 text-primary-600 rounded focus:ring-primary-500"
                                        />
                                        <span className="text-sm">{t('Require Phone')}</span>
                                    </label>
                                    <label className="flex items-center gap-2 cursor-pointer">
                                        <input
                                            type="checkbox"
                                            checked={config.require_email === true}
                                            onChange={(e) => onConfigChange('require_email', e.target.checked)}
                                            className="w-4 h-4 text-primary-600 rounded focus:ring-primary-500"
                                        />
                                        <span className="text-sm">{t('Require Email')}</span>
                                    </label>
                                </div>
                            </div>
                            <div>
                                <label className="block text-sm font-medium mb-1">{t('Minimum advance notice (hours)')}</label>
                                <input
                                    type="number"
                                    min={0}
                                    step={0.5}
                                    value={config.min_notice_hours ?? 1}
                                    onChange={(e) => onConfigChange('min_notice_hours', Math.max(0, Number(e.target.value)))}
                                    className="w-24 px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-primary-500 focus:border-primary-500"
                                />
                                <p className="text-xs text-gray-400 mt-1">{t('Customer cannot book a meeting if less than these hours remain')}</p>
                            </div>
                        </div>
                    )}
                </CardContent>
            </Card>

            {/* Associated Contacts with Priority */}
            <Card>
                <CardHeader>
                    <CardTitle className="flex items-center gap-2">
                        <Users className="w-5 h-5" />
                        {t('Associated Contacts and Priority')}
                    </CardTitle>
                </CardHeader>
                <CardContent>
                    <p className="text-sm text-gray-600 mb-4">
                        {t('Select contacts and set priority order. The first contact in the list will receive meetings first. Drag to reorder.')}
                    </p>
                    
                    {/* Dropdown to add contacts */}
                    <div className="mb-4">
                        <label className="block text-sm font-medium mb-2">{t('Add Contact')}</label>
                        <select
                            className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-primary-500 focus:border-primary-500"
                            value=""
                            onChange={(e) => {
                                const value = e.target.value
                                if (value.startsWith('list_')) {
                                    const listId = value.replace('list_', '')
                                    const list = contactLists.find(l => String(l.id) === listId)
                                    if (list?.contacts) {
                                        const newContacts = list.contacts
                                            .map(c => Number(c.id))
                                            .filter(id => !associatedContacts.includes(id))
                                        if (newContacts.length > 0) {
                                            onConfigChange('associated_contacts', [...associatedContacts, ...newContacts])
                                        }
                                    }
                                } else if (value.startsWith('contact_')) {
                                    const contactId = parseInt(value.replace('contact_', ''))
                                    if (!associatedContacts.includes(contactId)) {
                                        onConfigChange('associated_contacts', [...associatedContacts, contactId])
                                    }
                                }
                            }}
                        >
                            <option value="">{t('-- Select a list or contact --')}</option>
                            {contactLists.length > 0 && (
                                <>
                                    <optgroup label={t('Lists (add entire list)')}>
                                        {contactLists.map((list) => (
                                            <option key={`list_${list.id}`} value={`list_${list.id}`}>
                                                {list.name} ({sprintf(t('%d contacts'), (list.contacts || []).length)})
                                            </option>
                                        ))}
                                    </optgroup>
                                    <optgroup label={t('Individual Contacts')}>
                                        {allContacts.map((contact) => (
                                            <option 
                                                key={`contact_${contact.id}`} 
                                                value={`contact_${contact.id}`}
                                                disabled={associatedContacts.includes(Number(contact.id))}
                                            >
                                                {contact.name}{contact.email ? ` (${contact.email})` : ''}{associatedContacts.includes(Number(contact.id)) ? ' ✓' : ''}
                                            </option>
                                        ))}
                                    </optgroup>
                                </>
                            )}
                        </select>
                        {allContacts.length === 0 && (
                            <p className="text-xs text-gray-500 mt-2">
                                {t('No contacts in the system.')} <a href="#/contact-lists" className="text-primary-600 hover:underline">{t('Add contacts')}</a>
                            </p>
                        )}
                    </div>

                    {/* Priority-ordered contacts list (drag to reorder) */}
                    {associatedContacts.length > 0 && (
                        <div className="space-y-2">
                            <label className="block text-sm font-medium text-gray-700">
                                {sprintf(t('Priority Order (%d contacts)'), associatedContacts.length)}
                            </label>
                            <div className="space-y-1 max-h-64 overflow-y-auto border rounded-lg p-2 bg-gray-50">
                                {associatedContacts.map((contactId, index) => {
                                    const contact = allContacts.find(c => Number(c.id) === contactId)
                                    if (!contact) return null
                                    const meetingAvail = parseMeetingAvailabilitySafely(contact.meeting_availability)
                                    const duration = meetingAvail?.meeting_duration
                                    return (
                                        <div 
                                            key={contactId}
                                            draggable
                                            onDragStart={() => setDragIndex(index)}
                                            onDragOver={(e) => {
                                                e.preventDefault()
                                                e.currentTarget.classList.add('border-primary-400', 'bg-primary-50')
                                            }}
                                            onDragLeave={(e) => {
                                                e.currentTarget.classList.remove('border-primary-400', 'bg-primary-50')
                                            }}
                                            onDrop={(e) => {
                                                e.preventDefault()
                                                e.currentTarget.classList.remove('border-primary-400', 'bg-primary-50')
                                                if (dragIndex !== null && dragIndex !== index) {
                                                    moveContact(dragIndex, index)
                                                }
                                                setDragIndex(null)
                                            }}
                                            onDragEnd={() => setDragIndex(null)}
                                            className={`flex items-center gap-3 p-3 bg-white rounded-lg border cursor-grab active:cursor-grabbing transition-colors ${
                                                dragIndex === index ? 'opacity-50' : ''
                                            }`}
                                        >
                                            {/* Priority number */}
                                            <div className={`w-7 h-7 rounded-full flex items-center justify-center text-xs font-bold shrink-0 ${
                                                index === 0 ? 'bg-primary-500 text-white' : 'bg-gray-200 text-gray-600'
                                            }`}>
                                                {index + 1}
                                            </div>
                                            {/* Drag handle */}
                                            <div className="text-gray-300 shrink-0 select-none" title={t('Drag to reorder')}>
                                                &#x2630;
                                            </div>
                                            {/* Contact info */}
                                            <div className="flex-1 min-w-0">
                                                <div className="font-medium text-sm">{contact.name}</div>
                                                <div className="flex items-center gap-3 text-xs text-gray-500">
                                                    {contact.title && <span>{contact.title}</span>}
                                                    {contact.email && <span className="text-primary-600">{contact.email}</span>}
                                                    {duration && (
                                                        <span className="bg-gray-100 px-1.5 py-0.5 rounded text-gray-500">
                                                            {sprintf(t('%d min'), duration)}
                                                        </span>
                                                    )}
                                                    {!meetingAvail && (
                                                        <span className="text-orange-500">{t('No availability defined')}</span>
                                                    )}
                                                </div>
                                            </div>
                                            {/* Move up/down buttons */}
                                            <div className="flex flex-col gap-0.5 shrink-0">
                                                <button
                                                    type="button"
                                                    onClick={() => index > 0 && moveContact(index, index - 1)}
                                                    disabled={index === 0}
                                                    className="p-0.5 text-gray-400 hover:text-gray-600 disabled:opacity-30"
                                                    title={t('Increase priority')}
                                                >
                                                    <ChevronUp className="w-3.5 h-3.5" />
                                                </button>
                                                <button
                                                    type="button"
                                                    onClick={() => index < associatedContacts.length - 1 && moveContact(index, index + 1)}
                                                    disabled={index === associatedContacts.length - 1}
                                                    className="p-0.5 text-gray-400 hover:text-gray-600 disabled:opacity-30"
                                                    title={t('Decrease priority')}
                                                >
                                                    <ChevronDown className="w-3.5 h-3.5" />
                                                </button>
                                            </div>
                                            {/* Availability editor */}
                                            <button
                                                type="button"
                                                onClick={() => setAvailContactId(contactId)}
                                                className={`p-1 rounded shrink-0 transition-colors ${
                                                    meetingAvail
                                                        ? 'text-primary-500 hover:text-primary-700 hover:bg-primary-50'
                                                        : 'text-orange-400 hover:text-orange-600 hover:bg-orange-50'
                                                }`}
                                                title={t('Set availability')}
                                            >
                                                <CalendarClock className="w-4 h-4" />
                                            </button>
                                            {/* Remove */}
                                            <button
                                                type="button"
                                                onClick={() => toggleContact(contactId)}
                                                className="p-1 text-red-500 hover:bg-red-50 rounded shrink-0"
                                                title={t('Remove')}
                                            >
                                                <Trash2 className="w-4 h-4" />
                                            </button>
                                        </div>
                                    )
                                })}
                            </div>
                            <div className="p-2 bg-blue-50 rounded-lg text-sm text-blue-700">
                                {t('Meetings will be assigned by priority order. A time slot will only be blocked when all contacts are busy.')}
                            </div>

                            {/* Slot interval selector */}
                            {(() => {
                                // Collect unique meeting durations from associated contacts
                                const durations = new Set<number>()
                                associatedContacts.forEach((contactId) => {
                                    const contact = allContacts.find(c => Number(c.id) === contactId)
                                    if (contact?.meeting_availability) {
                                        const avail = parseMeetingAvailabilitySafely(contact.meeting_availability)
                                        if (avail?.meeting_duration) {
                                            durations.add(Number(avail.meeting_duration))
                                        }
                                    }
                                })
                                const sortedDurations = Array.from(durations).sort((a, b) => a - b)
                                const currentInterval = (config as any).slot_interval || 0

                                if (sortedDurations.length === 0) return null

                                return (
                                    <div className="mt-3">
                                        <label className="block text-sm font-medium text-gray-700 mb-1">
                                            {t('Time Slots in Calendar (minutes)')}
                                        </label>
                                        <p className="text-xs text-gray-500 mb-2">
                                            {t('Choose the time intervals displayed to the customer in the calendar. Options are derived from the meeting duration of associated contacts.')}
                                        </p>
                                        <select
                                            value={currentInterval}
                                            onChange={(e) => onConfigChange('slot_interval', Number(e.target.value))}
                                            className="w-full px-3 py-2 border border-gray-300 rounded-lg bg-white focus:ring-2 focus:ring-primary-500 focus:border-primary-500 text-sm"
                                        >
                                            <option value={0}>{t('Automatic (based on each contact\'s meeting duration)')}</option>
                                            {sortedDurations.map((dur) => (
                                                <option key={dur} value={dur}>
                                                    {sprintf(t('%d minutes'), dur)}
                                                </option>
                                            ))}
                                        </select>
                                    </div>
                                )
                            })()}
                        </div>
                    )}
                </CardContent>
            </Card>

            {/* Availability Schedule Editor Modal */}
            {(() => {
                const editContact = availContactId ? allContacts.find(c => Number(c.id) === availContactId) : null
                return (
                    <AvailabilityScheduleEditor
                        isOpen={!!availContactId}
                        contactName={editContact?.name || ''}
                        initialData={parseMeetingAvailabilitySafely(editContact?.meeting_availability)}
                        onSave={handleSaveAvailability}
                        onClose={() => setAvailContactId(null)}
                        isSaving={isSavingAvail}
                    />
                )
            })()}
        </div>
    )
}

// YouTube Widget Editor Component
interface YouTubeWidgetEditorProps {
    config: Record<string, unknown>
    onConfigChange: (key: string, value: unknown) => void
}

function YouTubeWidgetEditor({ config, onConfigChange }: YouTubeWidgetEditorProps) {
    return (
        <Card>
            <CardHeader>
                <CardTitle className="flex items-center gap-2">
                    <Youtube className="w-5 h-5 text-red-500" />
                    {t('YouTube Video Settings')}
                </CardTitle>
            </CardHeader>
            <CardContent className="space-y-4">
                <div>
                    <label className="block text-sm font-medium mb-1">
                        {t('Video URL')} <span className="text-red-500">*</span>
                    </label>
                    <input
                        type="url"
                        value={(config.video_url as string) || ''}
                        onChange={(e) => onConfigChange('video_url', e.target.value)}
                        placeholder="https://www.youtube.com/watch?v=..."
                        className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-primary-500 focus:border-primary-500"
                        dir="ltr"
                    />
                    <p className="text-xs text-gray-500 mt-1">
                        {t('Supported formats: youtube.com/watch?v=..., youtu.be/..., youtube.com/embed/...')}
                    </p>
                </div>

                <div>
                    <label className="block text-sm font-medium mb-1">{t('Title (optional)')}</label>
                    <input
                        type="text"
                        value={(config.title as string) || ''}
                        onChange={(e) => onConfigChange('title', e.target.value)}
                        placeholder={t('How to use the product')}
                        className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-primary-500 focus:border-primary-500"
                    />
                </div>

                <div>
                    <label className="block text-sm font-medium mb-1">{t('Description (optional)')}</label>
                    <textarea
                        value={(config.description as string) || ''}
                        onChange={(e) => onConfigChange('description', e.target.value)}
                        placeholder={t('Short description of the video...')}
                        rows={2}
                        className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-primary-500 focus:border-primary-500"
                    />
                </div>

                <div className="flex items-center gap-3">
                    <input
                        type="checkbox"
                        id="autoplay"
                        checked={(config.autoplay as boolean) || false}
                        onChange={(e) => onConfigChange('autoplay', e.target.checked)}
                        className="w-4 h-4 text-primary-600 rounded focus:ring-primary-500"
                    />
                    <label htmlFor="autoplay" className="text-sm">
                        {t('Autoplay (not recommended)')}
                    </label>
                </div>

                {/* Preview */}
                {typeof config.video_url === 'string' && config.video_url && extractYouTubeId(config.video_url) && (
                    <div className="mt-4 p-3 bg-gray-50 rounded-lg">
                        <p className="text-xs text-gray-500 mb-2">{t('Preview')}:</p>
                        <div className="aspect-video bg-black rounded-lg overflow-hidden">
                            <iframe
                                src={`https://www.youtube.com/embed/${extractYouTubeId(config.video_url)}`}
                                title={t('Preview')}
                                className="w-full h-full"
                                frameBorder="0"
                                allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture"
                                allowFullScreen
                            />
                        </div>
                    </div>
                )}
            </CardContent>
        </Card>
    )
}

// Helper to extract YouTube ID (supports watch, youtu.be, embed, shorts)
function extractYouTubeId(url: string): string {
    if (!url) return ''
    
    const patterns = [
        /(?:youtube\.com\/watch\?v=)([^&\n?#]+)/,
        /(?:youtu\.be\/)([^&\n?#]+)/,
        /(?:youtube\.com\/embed\/)([^&\n?#]+)/,
        /(?:youtube\.com\/shorts\/)([^&\n?#]+)/,
        /^([a-zA-Z0-9_-]{11})$/
    ]
    for (const pattern of patterns) {
        const match = url.match(pattern)
        if (match) return match[1]
    }
    return ''
}

// Gallery Widget Editor Component
interface GalleryWidgetEditorProps {
    config: Record<string, unknown>
    onConfigChange: (key: string, value: unknown) => void
}

function GalleryWidgetEditor({ config, onConfigChange }: GalleryWidgetEditorProps) {
    const images = (config.images as Array<{ url: string; title?: string; description?: string; link_url?: string; attachment_id?: number }>) || []

    const addImage = () => {
        onConfigChange('images', [...images, { url: '', title: '', description: '', link_url: '' }])
    }

    const updateImage = (index: number, updates: Partial<typeof images[0]>) => {
        const updated = [...images]
        updated[index] = { ...updated[index], ...updates }
        onConfigChange('images', updated)
    }

    const removeImage = (index: number) => {
        onConfigChange('images', images.filter((_, i) => i !== index))
    }

    // Open WordPress media library
    const openMediaLibrary = (index?: number) => {
        // Check if wp.media exists (WordPress media library)
        if (typeof window !== 'undefined' && (window as unknown as { wp?: { media?: unknown } }).wp?.media) {
            const wp = (window as unknown as { wp: { media: (options: unknown) => { on: (event: string, callback: () => void) => void; open: () => void; state: () => { get: (key: string) => { toJSON: () => Array<{ id: number; url: string; title: string; alt: string }> } } } } }).wp
            
            const mediaUploader = wp.media({
                title: t('Select images for gallery'),
                button: { text: index !== undefined ? t('Select image') : t('Add images') },
                multiple: index === undefined, // Multiple only when adding new
                library: { type: 'image' }
            })

            mediaUploader.on('select', () => {
                const selection = mediaUploader.state().get('selection').toJSON()
                
                if (index !== undefined && selection.length > 0) {
                    // Update existing image
                    const img = selection[0]
                    updateImage(index, { 
                        url: img.url, 
                        title: img.title || img.alt || '',
                        attachment_id: img.id
                    })
                } else {
                    // Add new images
                    const newImages = selection.map((img: { id: number; url: string; title: string; alt: string }) => ({
                        url: img.url,
                        title: img.title || img.alt || '',
                        description: '',
                        link_url: '',
                        attachment_id: img.id
                    }))
                    onConfigChange('images', [...images, ...newImages])
                }
            })

            mediaUploader.open()
        } else {
            // Fallback: just add empty image
            if (index === undefined) {
                addImage()
            }
            alert(t('WordPress media library is not available. Please enter a URL manually.'))
        }
    }

    return (
        <Card>
            <CardHeader>
                <CardTitle className="flex items-center gap-2">
                    <Image className="w-5 h-5 text-pink-500" />
                    {t('Gallery Settings')}
                </CardTitle>
            </CardHeader>
            <CardContent className="space-y-4">
                <div className="grid grid-cols-2 gap-4">
                    <div>
                        <label className="block text-sm font-medium mb-1">{t('Gallery Name')}</label>
                        <input
                            type="text"
                            value={(config.name as string) || ''}
                            onChange={(e) => onConfigChange('name', e.target.value)}
                            placeholder={t('Portfolio Gallery')}
                            className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-primary-500 focus:border-primary-500"
                        />
                    </div>
                </div>

                <div>
                    <label className="block text-sm font-medium mb-1">{t('Description (optional)')}</label>
                    <textarea
                        value={(config.description as string) || ''}
                        onChange={(e) => onConfigChange('description', e.target.value)}
                        placeholder={t('Gallery description...')}
                        rows={2}
                        className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-primary-500 focus:border-primary-500"
                    />
                </div>

                <div>
                    <div className="flex items-center justify-between mb-2">
                        <label className="text-sm font-medium">{t('Images')}</label>
                        <div className="flex gap-2">
                            <Button variant="outline" size="sm" onClick={() => openMediaLibrary()}>
                                <Upload className="w-4 h-4 me-1" />
                                {t('Upload Images')}
                            </Button>
                            <Button variant="ghost" size="sm" onClick={addImage}>
                                <Plus className="w-4 h-4 me-1" />
                                {t('Add URL')}
                            </Button>
                        </div>
                    </div>

                    {images.length === 0 ? (
                        <div 
                            className="text-center py-8 text-gray-500 bg-gray-50 rounded-lg border-2 border-dashed cursor-pointer hover:bg-gray-100 transition-colors"
                            onClick={() => openMediaLibrary()}
                        >
                            <Upload className="w-10 h-10 mx-auto mb-2 opacity-30" />
                            <p>{t('Click to upload images')}</p>
                            <p className="text-xs mt-1">{t('Or drag images here')}</p>
                        </div>
                    ) : (
                        <div className="space-y-3">
                            {images.map((image, index) => (
                                <div key={index} className="p-3 bg-gray-50 rounded-lg border">
                                    <div className="flex gap-3">
                                        {/* Preview - clickable to change */}
                                        <div 
                                            className="w-20 h-20 bg-gray-200 rounded-lg overflow-hidden flex-shrink-0 cursor-pointer hover:opacity-80 transition-opacity relative group"
                                            onClick={() => openMediaLibrary(index)}
                                            title={t('Click to change image')}
                                        >
                                            {image.url ? (
                                                <img
                                                    src={image.url}
                                                    alt=""
                                                    className="w-full h-full object-cover"
                                                    onError={(e) => {
                                                        (e.target as HTMLImageElement).style.display = 'none'
                                                    }}
                                                />
                                            ) : (
                                                <div className="w-full h-full flex items-center justify-center">
                                                    <Image className="w-6 h-6 text-gray-400" />
                                                </div>
                                            )}
                                            {/* Upload overlay on hover */}
                                            <div className="absolute inset-0 bg-black/50 opacity-0 group-hover:opacity-100 transition-opacity flex items-center justify-center">
                                                <Upload className="w-5 h-5 text-white" />
                                            </div>
                                        </div>

                                        {/* Fields */}
                                        <div className="flex-1 space-y-2">
                                            <div className="flex gap-2">
                                                <input
                                                    type="url"
                                                    value={image.url}
                                                    onChange={(e) => updateImage(index, { url: e.target.value })}
                                                    placeholder={t('Image URL')}
                                                    className="flex-1 px-2 py-1.5 text-sm border border-gray-300 rounded focus:ring-1 focus:ring-primary-500"
                                                    dir="ltr"
                                                />
                                                <button
                                                    type="button"
                                                    onClick={() => openMediaLibrary(index)}
                                                    className="px-2 py-1.5 text-sm bg-gray-100 hover:bg-gray-200 border border-gray-300 rounded transition-colors"
                                                    title={t('Select from media library')}
                                                >
                                                    <Upload className="w-4 h-4" />
                                                </button>
                                            </div>
                                            <div className="grid grid-cols-2 gap-2">
                                                <input
                                                    type="text"
                                                    value={image.title || ''}
                                                    onChange={(e) => updateImage(index, { title: e.target.value })}
                                                    placeholder={t('Title')}
                                                    className="px-2 py-1.5 text-sm border border-gray-300 rounded focus:ring-1 focus:ring-primary-500"
                                                />
                                                <input
                                                    type="url"
                                                    value={image.link_url || ''}
                                                    onChange={(e) => updateImage(index, { link_url: e.target.value })}
                                                    placeholder={t('Link (optional)')}
                                                    className="px-2 py-1.5 text-sm border border-gray-300 rounded focus:ring-1 focus:ring-primary-500"
                                                    dir="ltr"
                                                />
                                            </div>
                                        </div>

                                        {/* Remove button */}
                                        <button
                                            type="button"
                                            onClick={() => removeImage(index)}
                                            className="p-1.5 text-gray-400 hover:text-red-500"
                                        >
                                            <Trash2 className="w-4 h-4" />
                                        </button>
                                    </div>
                                </div>
                            ))}
                        </div>
                    )}
                </div>
            </CardContent>
        </Card>
    )
}

// Coupon Widget Editor Component
interface CouponWidgetEditorProps {
    config: Record<string, unknown>
    onConfigChange: (key: string, value: unknown) => void
}

interface WcPreset {
    id: number
    name: string
    description?: string
    language?: string
    coupon_count?: number
    bot_count?: number
    is_active?: number
}

interface WcCouponInPreset {
    id: number
    preset_id: number
    wc_coupon_id: number
    display_name: string
    description: string
    keywords: string
    priority: number
    min_cart_total: number | null
    max_cart_total: number | null
    is_active: number
    wc_coupon_code: string
    wc_discount_type: string
    wc_discount_amount: number
    wc_is_valid: boolean
}

interface WcAvailableCoupon {
    id: number
    code: string
    discount_type: string
    discount_amount: number
    description: string
    expiry_date: string | null
    usage_count: number
    usage_limit: number | null
}

function CouponWidgetEditor({ config, onConfigChange }: CouponWidgetEditorProps) {
    const { currentLanguage } = useLanguage()
    const [presets, setPresets] = useState<WcPreset[]>([])
    const [presetCoupons, setPresetCoupons] = useState<WcCouponInPreset[]>([])
    const [availableCoupons, setAvailableCoupons] = useState<WcAvailableCoupon[]>([])
    const [loadingPresets, setLoadingPresets] = useState(true)
    const [loadingCoupons, setLoadingCoupons] = useState(false)
    const [showAddCoupon, setShowAddCoupon] = useState(false)
    const [showCreatePreset, setShowCreatePreset] = useState(false)
    const [newPresetName, setNewPresetName] = useState('')
    const [newPresetDesc, setNewPresetDesc] = useState('')
    const [savingPreset, setSavingPreset] = useState(false)
    const [addingCoupon, setAddingCoupon] = useState(false)

    const selectedPresetId = config?.woocommerce_preset_id as number | undefined

    const fetchPresets = useCallback(async () => {
        setLoadingPresets(true)
        try {
            const res = await apiClient.get<{ success: boolean; data: { presets: WcPreset[] } }>(
                'woocommerce/presets',
                { language: currentLanguage }
            )
            setPresets(res?.data?.presets || [])
        } catch (err) {
            console.error('Failed to fetch presets:', err)
            setPresets([])
        } finally {
            setLoadingPresets(false)
        }
    }, [currentLanguage])

    const fetchPresetCoupons = useCallback(async (presetId: number) => {
        setLoadingCoupons(true)
        try {
            const res = await apiClient.get<{ success: boolean; data: { coupons: WcCouponInPreset[] } }>(
                `woocommerce/presets/${presetId}/coupons`
            )
            setPresetCoupons(res?.data?.coupons || [])
        } catch (err) {
            console.error('Failed to fetch preset coupons:', err)
            setPresetCoupons([])
        } finally {
            setLoadingCoupons(false)
        }
    }, [])

    const fetchAvailableCoupons = useCallback(async () => {
        try {
            const res = await apiClient.get<{ success: boolean; data: { coupons: WcAvailableCoupon[] } }>(
                'woocommerce/available-coupons'
            )
            setAvailableCoupons(res?.data?.coupons || [])
        } catch (err) {
            console.error('Failed to fetch available coupons:', err)
            setAvailableCoupons([])
        }
    }, [])

    useEffect(() => {
        fetchPresets()
    }, [fetchPresets])

    useEffect(() => {
        if (selectedPresetId) {
            fetchPresetCoupons(selectedPresetId)
        } else {
            setPresetCoupons([])
        }
    }, [selectedPresetId, fetchPresetCoupons])

    const handlePresetChange = (presetId: string) => {
        if (presetId === '__new__') {
            setShowCreatePreset(true)
            return
        }
        const id = presetId ? Number(presetId) : undefined
        onConfigChange('woocommerce_preset_id', id)
    }

    const handleCreatePreset = async () => {
        if (!newPresetName.trim()) return
        setSavingPreset(true)
        try {
            const res = await apiClient.post<{ success: boolean; data: { preset: WcPreset } }>(
                'woocommerce/presets',
                { name: newPresetName.trim(), description: newPresetDesc.trim(), language: currentLanguage }
            )
            const created = res?.data?.preset
            if (created) {
                await fetchPresets()
                onConfigChange('woocommerce_preset_id', created.id)
                setShowCreatePreset(false)
                setNewPresetName('')
                setNewPresetDesc('')
            }
        } catch (err) {
            console.error('Failed to create preset:', err)
        } finally {
            setSavingPreset(false)
        }
    }

    const handleAddCoupon = async (wcCouponId: number) => {
        if (!selectedPresetId || addingCoupon) return
        setAddingCoupon(true)
        try {
            await apiClient.post(`woocommerce/presets/${selectedPresetId}/coupons`, {
                wc_coupon_id: wcCouponId,
            })
            await fetchPresetCoupons(selectedPresetId)
            setShowAddCoupon(false)
        } catch (err) {
            console.error('Failed to add coupon:', err)
        } finally {
            setAddingCoupon(false)
        }
    }

    const handleRemoveCoupon = async (couponId: number) => {
        try {
            await apiClient.delete(`woocommerce/coupons/${couponId}`)
            if (selectedPresetId) {
                await fetchPresetCoupons(selectedPresetId)
            }
        } catch (err) {
            console.error('Failed to remove coupon:', err)
        }
    }

    const formatDiscountType = (type: string) => {
        switch (type) {
            case 'percent': return t('Percentage')
            case 'fixed_cart': return t('Fixed Cart')
            case 'fixed_product': return t('Fixed Product')
            default: return type
        }
    }

    const formatDiscountDisplay = (type: string, amount: number) => {
        if (type === 'percent') return `${amount}%`
        const currencySymbol = (window as any).boostbotAdmin?.woocommerce_currency_symbol || '₪'
        return `${currencySymbol}${amount}`
    }

    return (
        <div className="space-y-6">
            {/* Section 1: Preset Selection */}
            <Card>
                <CardHeader>
                    <CardTitle className="flex items-center gap-2">
                        <Ticket className="w-5 h-5 text-yellow-500" />
                        {t('Coupon Preset')}
                    </CardTitle>
                </CardHeader>
                <CardContent className="space-y-4">
                    {loadingPresets ? (
                        <div className="flex items-center justify-center py-6">
                            <div className="animate-spin rounded-full h-8 w-8 border-b-2 border-primary-600" />
                        </div>
                    ) : (
                        <>
                            <div>
                                <label className="block text-sm font-medium mb-2">
                                    {t('Select Preset')}
                                </label>
                                <select
                                    value={selectedPresetId ?? ''}
                                    onChange={(e) => handlePresetChange(e.target.value)}
                                    className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-primary-500 focus:border-primary-500"
                                >
                                    <option value="">{t('Select preset...')}</option>
                                    {presets.map((preset) => (
                                        <option key={preset.id} value={preset.id}>
                                            {preset.name}
                                            {preset.coupon_count != null ? ` (${preset.coupon_count})` : ''}
                                        </option>
                                    ))}
                                    <option value="__new__">+ {t('Create New Preset')}</option>
                                </select>
                            </div>

                            {showCreatePreset && (
                                <div className="border rounded-lg p-4 bg-gray-50 space-y-3">
                                    <h4 className="font-medium text-sm">{t('Create New Preset')}</h4>
                                    <input
                                        type="text"
                                        value={newPresetName}
                                        onChange={(e) => setNewPresetName(e.target.value)}
                                        placeholder={t('Preset name')}
                                        className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-primary-500 focus:border-primary-500"
                                    />
                                    <textarea
                                        value={newPresetDesc}
                                        onChange={(e) => setNewPresetDesc(e.target.value)}
                                        placeholder={t('Description (optional)')}
                                        rows={2}
                                        className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-primary-500 focus:border-primary-500"
                                    />
                                    <div className="flex gap-2">
                                        <Button
                                            onClick={handleCreatePreset}
                                            disabled={!newPresetName.trim() || savingPreset}
                                        >
                                            {savingPreset ? t('Creating...') : t('Create')}
                                        </Button>
                                        <Button
                                            variant="outline"
                                            onClick={() => {
                                                setShowCreatePreset(false)
                                                setNewPresetName('')
                                                setNewPresetDesc('')
                                            }}
                                        >
                                            {t('Cancel')}
                                        </Button>
                                    </div>
                                </div>
                            )}
                        </>
                    )}
                </CardContent>
            </Card>

            {/* Section 2: Coupons in Selected Preset */}
            {selectedPresetId && (
                <Card>
                    <CardHeader>
                        <CardTitle className="flex items-center justify-between">
                            <span className="flex items-center gap-2">
                                <ShoppingBag className="w-5 h-5 text-green-500" />
                                {t('Coupons in Preset')}
                            </span>
                            <Button
                                size="sm"
                                onClick={() => {
                                    fetchAvailableCoupons()
                                    setShowAddCoupon(true)
                                }}
                            >
                                <Plus className="w-4 h-4" />
                                {t('Add Coupon')}
                            </Button>
                        </CardTitle>
                    </CardHeader>
                    <CardContent>
                        {loadingCoupons ? (
                            <div className="flex items-center justify-center py-6">
                                <div className="animate-spin rounded-full h-8 w-8 border-b-2 border-primary-600" />
                            </div>
                        ) : presetCoupons.length === 0 ? (
                            <div className="text-center py-8 bg-gray-50 rounded-lg">
                                <Ticket className="w-10 h-10 mx-auto mb-2 text-gray-400" />
                                <p className="text-gray-500 text-sm">{t('No coupons in this preset')}</p>
                                <p className="text-gray-400 text-xs mt-1">{t('Add coupons from your WooCommerce store')}</p>
                            </div>
                        ) : (
                            <div className="space-y-3">
                                {presetCoupons.map((coupon) => (
                                    <div
                                        key={coupon.id}
                                        className={`flex items-center justify-between p-3 border rounded-lg ${
                                            coupon.wc_is_valid ? 'bg-white' : 'bg-red-50 border-red-200'
                                        }`}
                                    >
                                        <div className="flex-1 min-w-0">
                                            <div className="flex items-center gap-2">
                                                <code className="text-sm font-mono bg-gray-100 px-2 py-0.5 rounded">
                                                    {coupon.wc_coupon_code || t('Unknown')}
                                                </code>
                                                <span className="text-xs px-2 py-0.5 rounded-full bg-blue-100 text-blue-700">
                                                    {formatDiscountType(coupon.wc_discount_type)}
                                                </span>
                                                <span className="text-sm font-semibold text-green-700">
                                                    {formatDiscountDisplay(coupon.wc_discount_type, coupon.wc_discount_amount)}
                                                </span>
                                                {!coupon.wc_is_valid && (
                                                    <span className="text-xs px-2 py-0.5 rounded-full bg-red-100 text-red-700 flex items-center gap-1">
                                                        <AlertTriangle className="w-3 h-3" />
                                                        {t('Expired/Invalid')}
                                                    </span>
                                                )}
                                            </div>
                                            {coupon.display_name && (
                                                <p className="text-xs text-gray-500 mt-1 truncate">{coupon.display_name}</p>
                                            )}
                                        </div>
                                        <button
                                            onClick={() => handleRemoveCoupon(coupon.id)}
                                            className="p-1.5 text-red-400 hover:text-red-600 hover:bg-red-50 rounded transition-colors"
                                            title={t('Remove')}
                                        >
                                            <Trash2 className="w-4 h-4" />
                                        </button>
                                    </div>
                                ))}
                            </div>
                        )}

                        {/* Add Coupon Picker */}
                        {showAddCoupon && (
                            <div className="mt-4 border-t pt-4">
                                <h4 className="font-medium text-sm mb-3">{t('Select WooCommerce Coupon')}</h4>
                                {availableCoupons.length === 0 ? (
                                    <p className="text-gray-500 text-sm py-2">
                                        {t('No coupons available. Create a coupon in WooCommerce to use this feature.')}
                                    </p>
                                ) : (
                                    <div className="space-y-2 max-h-60 overflow-y-auto">
                                        {availableCoupons
                                            .filter((wc) => !presetCoupons.some((pc) => pc.wc_coupon_id === wc.id))
                                            .map((wc) => (
                                                <button
                                                    key={wc.id}
                                                    onClick={() => handleAddCoupon(wc.id)}
                                                    disabled={addingCoupon}
                                                    className="w-full flex items-center justify-between p-3 border rounded-lg hover:bg-primary-50 hover:border-primary-300 transition-colors text-start"
                                                >
                                                    <div>
                                                        <code className="text-sm font-mono">{wc.code}</code>
                                                        <div className="text-xs text-gray-500 mt-0.5">
                                                            {formatDiscountType(wc.discount_type)} — {formatDiscountDisplay(wc.discount_type, wc.discount_amount)}
                                                            {wc.expiry_date && ` · ${t('Expires')}: ${wc.expiry_date}`}
                                                        </div>
                                                    </div>
                                                    <Plus className="w-4 h-4 text-primary-500 flex-shrink-0" />
                                                </button>
                                            ))}
                                    </div>
                                )}
                                <Button
                                    variant="outline"
                                    size="sm"
                                    className="mt-3"
                                    onClick={() => setShowAddCoupon(false)}
                                >
                                    {t('Close')}
                                </Button>
                            </div>
                        )}
                    </CardContent>
                </Card>
            )}

            {/* Section 3: Display Settings */}
            <Card>
                <CardHeader>
                    <CardTitle className="flex items-center gap-2">
                        <Settings className="w-5 h-5 text-gray-500" />
                        {t('Display Settings')}
                    </CardTitle>
                </CardHeader>
                <CardContent className="space-y-4">
                    <div>
                        <label className="block text-sm font-medium mb-2">
                            {t('Widget Title')}
                        </label>
                        <input
                            type="text"
                            value={(config?.title as string) || ''}
                            onChange={(e) => onConfigChange('title', e.target.value)}
                            placeholder={t('Coupons for you')}
                            className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-primary-500 focus:border-primary-500"
                        />
                    </div>

                    <div className="flex items-center justify-between">
                        <div>
                            <p className="text-sm font-medium">{t('Show Expiry Date')}</p>
                            <p className="text-xs text-gray-500">{t('Display coupon expiration date to users')}</p>
                        </div>
                        <ToggleSwitch
                            checked={(config?.show_expiry as boolean) ?? true}
                            onChange={(val) => onConfigChange('show_expiry', val)}
                            ariaLabel={t('Show Expiry Date')}
                        />
                    </div>

                    <div className="flex items-center justify-between">
                        <div>
                            <p className="text-sm font-medium">{t('Show Terms')}</p>
                            <p className="text-xs text-gray-500">{t('Display coupon terms and conditions')}</p>
                        </div>
                        <ToggleSwitch
                            checked={(config?.show_terms as boolean) ?? false}
                            onChange={(val) => onConfigChange('show_terms', val)}
                            ariaLabel={t('Show Terms')}
                        />
                    </div>

                    <div className="flex items-center justify-between">
                        <div>
                            <p className="text-sm font-medium">{t('Show Discount Value')}</p>
                            <p className="text-xs text-gray-500">{t('Display the discount amount on the coupon')}</p>
                        </div>
                        <ToggleSwitch
                            checked={(config?.show_discount_value as boolean) ?? true}
                            onChange={(val) => onConfigChange('show_discount_value', val)}
                            ariaLabel={t('Show Discount Value')}
                        />
                    </div>
                </CardContent>
            </Card>
        </div>
    )
}

// Contact Card Widget Editor Component
interface ContactCardWidgetEditorProps {
    config: Record<string, unknown>
    onConfigChange: (key: string, value: unknown) => void
}

interface ContactListOption {
    id: number
    name: string
    contacts_count?: number
}

function ContactCardWidgetEditor({ config, onConfigChange }: ContactCardWidgetEditorProps) {
    const contactListIds = (config.contact_list_ids as number[]) || []

    // Fetch contact lists
    const { data: contactListsData } = useQuery({
        queryKey: ['contact-lists'],
        queryFn: () => apiClient.get<{ success: boolean; data: { lists: ContactListOption[] } }>('contact-lists'),
    })

    const contactLists = contactListsData?.data?.lists || []

    const toggleContactList = (listId: number) => {
        if (contactListIds.includes(listId)) {
            onConfigChange('contact_list_ids', contactListIds.filter(id => id !== listId))
        } else {
            onConfigChange('contact_list_ids', [...contactListIds, listId])
        }
    }

    return (
        <div className="space-y-6">
            <Card>
                <CardHeader>
                    <CardTitle className="flex items-center gap-2">
                        <User className="w-5 h-5 text-indigo-500" />
                        {t('Contact Card Settings')}
                    </CardTitle>
                </CardHeader>
                <CardContent className="space-y-4">
                    {/* Contact Lists Selection */}
                    <div>
                        <label className="block text-sm font-medium mb-2">
                            {t('Contact Lists')}
                        </label>
                        <p className="text-xs text-gray-500 mb-3">
                            {t('Select the contact lists from which Gemini will choose the most suitable contact based on the conversation context, role, and availability')}
                        </p>
                        
                        {contactLists.length === 0 ? (
                            <div className="text-center py-6 bg-gray-50 rounded-lg">
                                <User className="w-8 h-8 mx-auto mb-2 text-gray-400" />
                                <p className="text-gray-500 text-sm">{t('No contact lists')}</p>
                                <a href="#/contact-lists" className="text-sm text-primary-600 hover:underline">
                                    {t('Create new list')} →
                                </a>
                            </div>
                        ) : (
                            <div className="space-y-2 max-h-48 overflow-y-auto border rounded-lg p-2 bg-gray-50">
                                {contactLists.map((list) => (
                                    <label
                                        key={list.id}
                                        className={`flex items-center gap-3 p-3 bg-white rounded-lg border cursor-pointer transition-colors ${
                                            contactListIds.includes(list.id) 
                                                ? 'border-primary-500 bg-primary-50' 
                                                : 'hover:bg-gray-50'
                                        }`}
                                    >
                                        <input
                                            type="checkbox"
                                            checked={contactListIds.includes(list.id)}
                                            onChange={() => toggleContactList(list.id)}
                                            className="w-4 h-4 text-primary-600 rounded focus:ring-primary-500"
                                        />
                                        <span className="font-medium">{list.name}</span>
                                        {list.contacts_count !== undefined && (
                                            <span className="text-xs text-gray-400">
                                                ({sprintf(t('%d contacts'), list.contacts_count)})
                                            </span>
                                        )}
                                    </label>
                                ))}
                            </div>
                        )}
                    </div>

                    {/* Display Mode - COMMENTED OUT: Gemini decides which contact to show based on context, role, and availability */}
                    {/* <div>
                        <label className="block text-sm font-medium mb-2">
                            {t('Display mode')}
                        </label>
                        <select
                            value={displayMode}
                            onChange={(e) => onConfigChange('display_mode', e.target.value)}
                            className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-primary-500 focus:border-primary-500"
                        >
                            <option value="first">{t('Show the first contact')}</option>
                            <option value="random">{t('Show a random contact')}</option>
                            <option value="all">{t('Show all contacts')}</option>
                        </select>
                    </div> */}

                </CardContent>
            </Card>
        </div>
    )
}

