/**
 * Display Conditions Editor Component
 * @since 1.1.0
 */

import { useMemo, useState, useEffect, useLayoutEffect, useRef } from 'react'
import { createPortal } from 'react-dom'
import { Plus, Trash2, Globe, Home, FileText, Tag, Link2, ChevronDown, ChevronUp, ExternalLink, AlertTriangle } from 'lucide-react'
import { Link } from 'react-router-dom'
import type { DisplayCondition } from '@/types/bot'
import { apiClient } from '@/api/client'
import { useOverridingBots, useOverriddenBots } from '@/hooks/useBots'
import { t, sprintf } from '@/lib/i18n'

interface DisplayConditionsEditorProps {
    conditions: DisplayCondition[]
    onChange: (conditions: DisplayCondition[]) => void
    botId?: number // To exclude current bot from assigned checks
    isDefaultBot?: boolean
}

interface ContentItem {
    id: number
    title: string
    assigned_bot?: {
        bot_id: number
        bot_name: string
    } | null
}

function getConditionTypes() {
    return [
        { value: 'all', label: t('Entire Site'), icon: Globe, needsValue: false },
        { value: 'homepage', label: t('Homepage'), icon: Home, needsValue: false },
        { value: 'post_type', label: t('Content Type'), icon: FileText, needsValue: true },
        { value: 'taxonomy', label: t('Category'), icon: Tag, needsValue: true },
        { value: 'url_contains', label: t('URL Contains'), icon: Link2, needsValue: true },
    ]
}

function getPostTypes() {
    return [
        { value: 'post', label: t('Posts'), endpoint: 'posts' },
        { value: 'page', label: t('Pages'), endpoint: 'pages' },
        { value: 'product', label: t('Products (WooCommerce)'), endpoint: 'products' },
    ]
}

export function DisplayConditionsEditor({ conditions, onChange, botId, isDefaultBot = false }: DisplayConditionsEditorProps) {
    const DEFAULT_ALL_ID = '__boostbot_default_all__'

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

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

        return [defaultAll, ...excludes]
    }

    // NOTE: We use effectiveConditions for DISPLAY only. The underlying `conditions`
    // is what gets saved to the database. This prevents data loss when:
    // - A default bot's include conditions would be stripped
    // - User turns off is_default toggle (their includes are already gone)
    // For default bots, effectiveConditions shows the "show all" + excludes view,
    // but we never destructively modify the actual conditions array.

    const effectiveConditions = useMemo(() => {
        return isDefaultBot ? normalizeDefaultConditions(conditions) : conditions
    }, [conditions, isDefaultBot])

    const addCondition = () => {
        const newCondition: DisplayCondition = {
            id: `cond_${Date.now()}`,
            type: isDefaultBot ? 'post_type' : 'all',
            operator: isDefaultBot ? 'exclude' : 'include',
        }
        // For default bots: add new exclude condition to the actual conditions array
        // For regular bots: add new condition normally
        onChange([...conditions, newCondition])
    }

    const updateCondition = (id: string, updates: Partial<DisplayCondition>) => {
        // Default bot: lock the implicit "all/include" display row (it doesn't exist in real data)
        if (isDefaultBot && id === DEFAULT_ALL_ID) {
            return
        }

        // Update the actual conditions array, not the display-only effectiveConditions
        const next = (conditions || []).map(c => {
            if (c.id !== id) return c
            // For default bots, force operator to 'exclude' for any user-added conditions
            const forcedUpdates = isDefaultBot
                ? { ...updates, operator: 'exclude' as const }
                : updates
            return { ...c, ...forcedUpdates }
        })
        onChange(next)
    }

    const removeCondition = (id: string) => {
        // Default bot: the "all/include" display row can't be removed (it's virtual)
        if (isDefaultBot && id === DEFAULT_ALL_ID) {
            return
        }
        // Remove from actual conditions, not the display-only effectiveConditions
        const next = conditions.filter(c => c.id !== id)
        onChange(next)
    }

    return (
        <div className="space-y-4">
            {/* Header */}
            <div className="flex items-center justify-between">
                <div>
                    <h4 className="font-medium text-gray-900">{t('Display Conditions')}</h4>
                    <p className="text-sm text-gray-500">
                        {t('Define where the bot will be displayed on the site')}
                    </p>
                </div>
                <button
                    type="button"
                    onClick={addCondition}
                    className="flex items-center gap-1 px-3 py-1.5 text-sm border border-gray-300 rounded-lg hover:bg-gray-50 transition-colors"
                >
                    <Plus className="w-4 h-4" />
                    {t('Add Condition')}
                </button>
            </div>

            {/* Conditions List */}
            {effectiveConditions.length === 0 ? (
                <div className="text-center py-8 bg-gray-50 rounded-lg border-2 border-dashed border-gray-200">
                    <Globe className="w-8 h-8 mx-auto text-gray-400 mb-2" />
                    <p className="text-gray-500 text-sm">
                        {isDefaultBot
                            ? t('Default bot will be displayed across the entire site, unless excluded')
                            : t('No conditions - the bot will not be displayed until you add a condition')}
                    </p>
                    <button
                        type="button"
                        onClick={addCondition}
                        className="mt-3 text-primary-600 text-sm hover:underline"
                    >
                        {t('Add first condition')}
                    </button>
                </div>
            ) : (
                <div className="space-y-3">
                    {effectiveConditions.map((condition) => (
                        <ConditionRow
                            key={condition.id}
                            condition={condition}
                            onUpdate={(updates) => updateCondition(condition.id, updates)}
                            onRemove={() => removeCondition(condition.id)}
                            botId={botId}
                            isDefaultBot={isDefaultBot}
                            isLocked={isDefaultBot && condition.id === DEFAULT_ALL_ID}
                        />
                    ))}
                </div>
            )}

            {/* Help Text */}
            {effectiveConditions.length > 0 && (
                <div className="bg-blue-50 rounded-lg p-3 text-sm text-blue-700">
                    <strong>{t('Tip:')}</strong>{' '}
                    {isDefaultBot
                        ? t('For a default bot you can only exclude (not display).')
                        : t('"Do not display" conditions override "Display" conditions. For example: display on all product pages, except a specific category.')}
                </div>
            )}

            {/* Overriding Bots Section - Only show for saved bots */}
            {botId && botId > 0 && (
                <OverridingBotsSection botId={botId} />
            )}
        </div>
    )
}

/**
 * Sub-component: Bot Relationships Section
 * Shows which bots override this one AND which bots this one overrides
 */
function OverridingBotsSection({ botId }: { botId: number }) {
    const [isExpanded, setIsExpanded] = useState(false)
    const { data: overridingData, isLoading: isLoadingOverriding } = useOverridingBots(botId, { enabled: isExpanded })
    const { data: overriddenData, isLoading: isLoadingOverridden } = useOverriddenBots(botId, { enabled: isExpanded })

    const overridingBots = overridingData?.data?.overriding_bots || []
    const overriddenBots = overriddenData?.data?.overridden_bots || []
    const currentScope = overridingData?.data?.current_bot?.scope || overriddenData?.data?.current_bot?.scope || ''
    const isLoading = isLoadingOverriding || isLoadingOverridden

    if (!isExpanded) {
        return (
            <div className="border-t border-gray-200 pt-4 mt-4">
                <button
                    type="button"
                    onClick={() => setIsExpanded(true)}
                    className="flex items-center gap-2 text-sm text-gray-600 hover:text-gray-900 transition-colors"
                >
                    <ChevronDown className="w-4 h-4" />
                    <span>{t('Show overlaps with other bots')}</span>
                </button>
            </div>
        )
    }

    return (
        <div className="border-t border-gray-200 pt-4 mt-4 w-full">
            <button
                type="button"
                onClick={() => setIsExpanded(false)}
                className="flex items-center gap-2 text-sm text-gray-600 hover:text-gray-900 transition-colors mb-3"
            >
                <ChevronUp className="w-4 h-4" />
                    <span>{t('Hide overlaps with other bots')}</span>
            </button>

            {isLoading ? (
                <div className="flex items-center justify-center py-6 text-gray-500">
                    <div className="animate-spin rounded-full h-5 w-5 border-b-2 border-primary-600 mr-2" />
                    <span className="text-sm">{t('Loading...')}</span>
                </div>
            ) : (
                <div className="space-y-6 w-full">
                    {/* Bots that THIS bot overrides (shown for specific bots) */}
                    {overriddenBots.length > 0 && (
                        <div className="space-y-3 w-full">
                            <div className="bg-green-50 rounded-lg p-3 flex items-start gap-2">
                                <div className="w-5 h-5 flex items-center justify-center text-green-600 flex-shrink-0 mt-0.5">✓</div>
                                <div className="text-sm">
                                    <strong className="text-green-800">{t('Bots that this bot overrides')}</strong>
                                    <p className="text-green-700 mt-1">
                                        {t('This bot will be displayed instead of the following bots in overlapping areas, because its display conditions are more specific:')}
                                    </p>
                                    {currentScope && (
                                        <p className="text-green-600 mt-1 text-xs">
                                            {t('Current bot scope:')} <strong>{currentScope}</strong>
                                        </p>
                                    )}
                                </div>
                            </div>

                            <div className="overflow-hidden rounded-lg border border-gray-200 w-full">
                                <table className="w-full divide-y divide-gray-200">
                                    <thead className="bg-gray-50">
                                        <tr>
                                            <th scope="col" className="px-4 py-3 text-right text-xs font-medium text-gray-500 uppercase tracking-wider">
                                                {t('Bot Name')}
                                            </th>
                                            <th scope="col" className="px-4 py-3 text-right text-xs font-medium text-gray-500 uppercase tracking-wider">
                                                {t('Its Scope')}
                                            </th>
                                            <th scope="col" className="px-4 py-3 text-right text-xs font-medium text-gray-500 uppercase tracking-wider">
                                                {t('Actions')}
                                            </th>
                                        </tr>
                                    </thead>
                                    <tbody className="bg-white divide-y divide-gray-200">
                                        {overriddenBots.map((bot) => (
                                            <tr key={bot.id} className="hover:bg-gray-50">
                                                <td className="px-4 py-3 whitespace-nowrap">
                                                    <div className="flex items-center gap-2">
                                                        <span className="text-sm font-medium text-gray-900">
                                                            {bot.bot_name}
                                                        </span>
                                                        {bot.is_default && (
                                                            <span className="px-2 py-0.5 text-xs bg-primary-100 text-primary-700 rounded-full">
                                                                {t('Default')}
                                                            </span>
                                                        )}
                                                    </div>
                                                </td>
                                                <td className="px-4 py-3">
                                                    <div className="text-sm text-gray-600">
                                                        {bot.their_scope || '—'}
                                                    </div>
                                                </td>
                                                <td className="px-4 py-3 whitespace-nowrap">
                                                    <Link
                                                        to={`/bots/${bot.id}?tab=display`}
                                                        className="inline-flex items-center gap-1 px-3 py-1.5 text-xs font-medium text-primary-600 hover:text-primary-700 hover:bg-primary-50 rounded-lg transition-colors"
                                                    >
                                                        <ExternalLink className="w-3.5 h-3.5" />
                                                        {t('Edit display conditions')}
                                                    </Link>
                                                </td>
                                            </tr>
                                        ))}
                                    </tbody>
                                </table>
                            </div>
                        </div>
                    )}

                    {/* Bots that override THIS bot (shown for broad scope bots) */}
                    {overridingBots.length > 0 && (
                        <div className="space-y-3 w-full">
                            <div className="bg-amber-50 rounded-lg p-3 flex items-start gap-2">
                                <AlertTriangle className="w-5 h-5 text-amber-500 flex-shrink-0 mt-0.5" />
                                <div className="text-sm">
                                    <strong className="text-amber-800">{t('Bots that override this bot')}</strong>
                                    <p className="text-amber-700 mt-1">
                                        {t('The following bots will be displayed instead of this bot in overlapping areas, because their display conditions are more specific:')}
                                    </p>
                                    {currentScope && (
                                        <p className="text-amber-600 mt-1 text-xs">
                                            {t('Current bot scope:')} <strong>{currentScope}</strong>
                                        </p>
                                    )}
                                </div>
                            </div>

                            <div className="overflow-hidden rounded-lg border border-gray-200 w-full">
                                <table className="w-full divide-y divide-gray-200">
                                    <thead className="bg-gray-50">
                                        <tr>
                                            <th scope="col" className="px-4 py-3 text-right text-xs font-medium text-gray-500 uppercase tracking-wider">
                                                {t('Bot Name')}
                                            </th>
                                            <th scope="col" className="px-4 py-3 text-right text-xs font-medium text-gray-500 uppercase tracking-wider">
                                                {t('Overlapping Conditions')}
                                            </th>
                                            <th scope="col" className="px-4 py-3 text-right text-xs font-medium text-gray-500 uppercase tracking-wider">
                                                {t('Actions')}
                                            </th>
                                        </tr>
                                    </thead>
                                    <tbody className="bg-white divide-y divide-gray-200">
                                        {overridingBots.map((bot) => (
                                            <tr key={bot.id} className="hover:bg-gray-50">
                                                <td className="px-4 py-3 whitespace-nowrap">
                                                    <div className="flex items-center gap-2">
                                                        <span className="text-sm font-medium text-gray-900">
                                                            {bot.bot_name}
                                                        </span>
                                                        {bot.is_default && (
                                                            <span className="px-2 py-0.5 text-xs bg-primary-100 text-primary-700 rounded-full">
                                                                {t('Default')}
                                                            </span>
                                                        )}
                                                    </div>
                                                </td>
                                                <td className="px-4 py-3">
                                                    <div className="text-sm text-gray-600">
                                                        {bot.overlapping_scopes.length > 0 ? (
                                                            <ul className="list-disc list-inside space-y-0.5">
                                                                {bot.overlapping_scopes.map((scope, idx) => (
                                                                    <li key={idx} className="text-gray-700">{scope}</li>
                                                                ))}
                                                            </ul>
                                                        ) : (
                                                            <span className="text-gray-400">—</span>
                                                        )}
                                                    </div>
                                                </td>
                                                <td className="px-4 py-3 whitespace-nowrap">
                                                    <Link
                                                        to={`/bots/${bot.id}?tab=display`}
                                                        className="inline-flex items-center gap-1 px-3 py-1.5 text-xs font-medium text-primary-600 hover:text-primary-700 hover:bg-primary-50 rounded-lg transition-colors"
                                                    >
                                                        <ExternalLink className="w-3.5 h-3.5" />
                                                        {t('Edit display conditions')}
                                                    </Link>
                                                </td>
                                            </tr>
                                        ))}
                                    </tbody>
                                </table>
                            </div>
                        </div>
                    )}

                    {/* No overlaps at all */}
                    {overridingBots.length === 0 && overriddenBots.length === 0 && (
                        <div className="bg-gray-50 rounded-lg p-4 text-sm text-gray-600">
                            <strong>{t('No overlaps')}</strong>
                            <p className="mt-1">
                                {t('There are no other bots with overlapping display conditions for this bot.')}
                            </p>
                        </div>
                    )}
                </div>
            )}
        </div>
    )
}

// Sub-component: Condition Row
interface ConditionRowProps {
    condition: DisplayCondition
    onUpdate: (updates: Partial<DisplayCondition>) => void
    onRemove: () => void
    botId?: number
    isDefaultBot?: boolean
    isLocked?: boolean
}

// Threshold for showing search instead of dropdown
const SEARCH_THRESHOLD = 20

function ConditionRow({ condition, onUpdate, onRemove, botId, isDefaultBot = false, isLocked = false }: ConditionRowProps) {
    const [contentItems, setContentItems] = useState<ContentItem[]>([])
    const [totalItems, setTotalItems] = useState(0)
    const [isLoadingItems, setIsLoadingItems] = useState(false)
    const [searchQuery, setSearchQuery] = useState('')
    const [isDropdownOpen, setIsDropdownOpen] = useState(false)
    const [, setSelectedItemTitle] = useState('')
    const [isSearching, setIsSearching] = useState(false)
    const dropdownRef = useRef<HTMLDivElement>(null)
    const menuRef = useRef<HTMLDivElement>(null)
    const searchTimeoutRef = useRef<ReturnType<typeof setTimeout> | null>(null)
    const [menuPos, setMenuPos] = useState<{ top: number; left: number; width: number } | null>(null)

    // Parse value - can be "post_type" or "post_type:id" or "post_type:id1,id2,id3"
    const parseValue = (value: string | number | number[] | undefined): { postType: string; itemIds: number[] } => {
        if (!value || typeof value !== 'string') {
            return { postType: '', itemIds: [] }
        }
        const parts = value.split(':')
        const postType = parts[0] || ''
        const idsStr = parts[1] || ''
        const itemIds = idsStr ? idsStr.split(',').map(id => parseInt(id, 10)).filter(id => !isNaN(id)) : []
        return { postType, itemIds }
    }

    const { postType, itemIds } = parseValue(condition.value)

    // Check if we need search mode (more than 20 items)
    const useSearchMode = totalItems > SEARCH_THRESHOLD

    // Close dropdown when clicking outside
    useEffect(() => {
        const handleClickOutside = (event: MouseEvent) => {
            const target = event.target as Node
            const clickedTrigger = dropdownRef.current && dropdownRef.current.contains(target)
            const clickedMenu = menuRef.current && menuRef.current.contains(target)
            if (!clickedTrigger && !clickedMenu) {
                setIsDropdownOpen(false)
            }
        }
        document.addEventListener('mousedown', handleClickOutside)
        return () => document.removeEventListener('mousedown', handleClickOutside)
    }, [])

    const updateMenuPos = () => {
        const el = dropdownRef.current
        if (!el) return
        const rect = el.getBoundingClientRect()
        setMenuPos({
            top: rect.bottom + 4,
            left: rect.left,
            width: rect.width,
        })
    }

    useLayoutEffect(() => {
        if (!isDropdownOpen) return
        updateMenuPos()

        // Reposition on scroll/resize (capture scroll from nested containers like <main overflow-auto>)
        const onScrollOrResize = () => updateMenuPos()
        window.addEventListener('resize', onScrollOrResize)
        window.addEventListener('scroll', onScrollOrResize, true)
        return () => {
            window.removeEventListener('resize', onScrollOrResize)
            window.removeEventListener('scroll', onScrollOrResize, true)
        }
        // eslint-disable-next-line react-hooks/exhaustive-deps
    }, [isDropdownOpen])

    // Load content items when post type changes
    useEffect(() => {
        if (condition.type === 'post_type' && postType) {
            loadContentItems(postType)
        }
    }, [condition.type, postType])

    // Search with debounce
    useEffect(() => {
        if (!useSearchMode || !postType) return
        
        // Clear previous timeout
        if (searchTimeoutRef.current) {
            clearTimeout(searchTimeoutRef.current)
        }

        // Debounce search
        searchTimeoutRef.current = setTimeout(() => {
            if (searchQuery.trim()) {
                searchContentItems(postType, searchQuery)
            } else {
                loadContentItems(postType)
            }
        }, 300)

        return () => {
            if (searchTimeoutRef.current) {
                clearTimeout(searchTimeoutRef.current)
            }
        }
    }, [searchQuery, postType, useSearchMode])

    // Update selected item title when itemIds change
    useEffect(() => {
        if (itemIds.length > 0 && contentItems.length > 0) {
            const selectedItems = contentItems.filter(i => itemIds.includes(i.id))
            if (selectedItems.length === 1) {
                setSelectedItemTitle(selectedItems[0].title)
            } else if (selectedItems.length > 1) {
                setSelectedItemTitle(sprintf(t('%s items selected'), selectedItems.length))
            }
        } else if (itemIds.length === 0) {
            setSelectedItemTitle('')
        }
    }, [itemIds, contentItems])

    interface ContentItemsResponse {
        success: boolean
        data: {
            items: ContentItem[]
            total: number
        }
    }

    const loadContentItems = async (type: string) => {
        setIsLoadingItems(true)
        try {
            const excludeParam = botId ? `&exclude_bot_id=${botId}` : ''
            const response = await apiClient.get<ContentItemsResponse>(`content-items?post_type=${type}${excludeParam}`)
            if (response?.success && response?.data) {
                setContentItems(response.data.items)
                setTotalItems(response.data.total)
            }
        } catch (error) {
            console.error('Failed to load content items:', error)
            setContentItems([])
            setTotalItems(0)
        } finally {
            setIsLoadingItems(false)
        }
    }

    const searchContentItems = async (type: string, query: string) => {
        setIsSearching(true)
        try {
            const excludeParam = botId ? `&exclude_bot_id=${botId}` : ''
            const response = await apiClient.get<ContentItemsResponse>(
                `content-items?post_type=${type}&search=${encodeURIComponent(query)}${excludeParam}`
            )
            if (response?.success && response?.data) {
                setContentItems(response.data.items)
            }
        } catch (error) {
            console.error('Failed to search content items:', error)
        } finally {
            setIsSearching(false)
        }
    }

    const handlePostTypeChange = (newPostType: string) => {
        // When changing post type, reset to "all items"
        onUpdate({ value: newPostType })
        setContentItems([])
        setSearchQuery('')
        setSelectedItemTitle('')
    }

    const toggleItemSelection = (itemId: number) => {
        let newIds: number[]
        if (itemIds.includes(itemId)) {
            // Remove from selection
            newIds = itemIds.filter(id => id !== itemId)
        } else {
            // Add to selection
            newIds = [...itemIds, itemId]
        }
        
        if (newIds.length === 0) {
            // No items selected - show all
            onUpdate({ value: postType })
            setSelectedItemTitle('')
        } else {
            // Update with new selection
            onUpdate({ value: `${postType}:${newIds.join(',')}` })
        }
    }

    const handleSelectAll = () => {
        // Clear selection - show all
        onUpdate({ value: postType })
        setSelectedItemTitle('')
        setIsDropdownOpen(false)
        setSearchQuery('')
    }

    const allItemsLabel = condition.operator === 'exclude'
        ? sprintf(t('📋 Exclude all (%s items)'), totalItems.toLocaleString())
        : sprintf(t('📋 Show in all (%s items)'), totalItems.toLocaleString())

    return (
        <div className="flex items-start gap-3 p-3 bg-gray-50 rounded-lg border border-gray-200">
            {/* Operator */}
            <div className="w-28 flex-shrink-0">
                <select
                    value={condition.operator}
                    onChange={(e) => onUpdate({ operator: e.target.value as 'include' | 'exclude' })}
                    disabled={isLocked || isDefaultBot}
                    className={`w-full px-2 py-2 text-sm rounded-lg border font-medium ${
                        condition.operator === 'include' 
                            ? 'bg-green-50 border-green-200 text-green-700' 
                            : 'bg-red-50 border-red-200 text-red-700'
                    }`}
                >
                    {/* Default bot: lock the first row to "include", and force all other rows to be "exclude" */}
                    {(isLocked || !isDefaultBot) && <option value="include">{t('✓ Display')}</option>}
                    {/* For non-default bots we allow exclude too; for default bot non-locked rows, exclude is the only option */}
                    {(!isLocked) && <option value="exclude">{t('✗ Do not display')}</option>}
                </select>
            </div>

            {/* Type */}
            <div className="w-40 flex-shrink-0">
                <select
                    value={condition.type}
                    onChange={(e) => onUpdate({ type: e.target.value as DisplayCondition['type'], value: undefined })}
                    disabled={isLocked}
                    className="w-full px-2 py-2 text-sm rounded-lg border border-gray-200 bg-white"
                >
                    {getConditionTypes()
                        .filter(t => !isLocked || t.value === 'all')
                        .map(type => (
                        <option key={type.value} value={type.value}>
                            {type.label}
                        </option>
                    ))}
                </select>
            </div>

            {/* Value (based on type) */}
            <div className="flex-1">
                {condition.type === 'post_type' && (
                    <div className="flex gap-2">
                        {/* Post Type Select */}
                        <select
                            value={postType}
                            onChange={(e) => handlePostTypeChange(e.target.value)}
                            className="w-40 flex-shrink-0 px-2 py-2 text-sm rounded-lg border border-gray-200 bg-white"
                        >
                            <option value="">{t('Select content type')}</option>
                            {getPostTypes().map(type => (
                                <option key={type.value} value={type.value}>
                                    {type.label}
                                </option>
                            ))}
                        </select>

                        {/* Multi-Select for specific items */}
                        {postType && !isLoadingItems && (
                            <div className="flex-1 relative" ref={dropdownRef}>
                                {/* Selected items display / trigger */}
                                <div
                                    onClick={() => setIsDropdownOpen(!isDropdownOpen)}
                                    className="min-h-[38px] px-2 py-1.5 text-sm rounded-lg border border-gray-200 bg-white cursor-pointer flex flex-wrap gap-1 items-center"
                                >
                                    {itemIds.length === 0 ? (
                                        <span className="text-gray-400">{allItemsLabel}</span>
                                    ) : (
                                        <>
                                            {contentItems
                                                .filter(item => itemIds.includes(item.id))
                                                .slice(0, 3)
                                                .map(item => (
                                                    <span
                                                        key={item.id}
                                                        className="inline-flex items-center gap-1 px-2 py-0.5 bg-primary-100 text-primary-700 text-xs rounded-full"
                                                    >
                                                        {item.title.length > 15 ? item.title.slice(0, 15) + '...' : item.title}
                                                        <button
                                                            type="button"
                                                            onClick={(e) => {
                                                                e.stopPropagation()
                                                                toggleItemSelection(item.id)
                                                            }}
                                                            className="hover:text-primary-900"
                                                        >
                                                            ×
                                                        </button>
                                                    </span>
                                                ))}
                                            {itemIds.length > 3 && (
                                                <span className="text-xs text-gray-500">{sprintf(t('+%s more'), itemIds.length - 3)}</span>
                                            )}
                                        </>
                                    )}
                                </div>

                                {/* Dropdown with checkboxes (portal to avoid clipping inside overflow containers) */}
                                {isDropdownOpen && menuPos &&
                                    createPortal(
                                        <div
                                            ref={menuRef}
                                            className="bg-white border border-gray-200 rounded-lg shadow-lg max-h-72 overflow-hidden"
                                            style={{
                                                position: 'fixed',
                                                top: menuPos.top,
                                                left: menuPos.left,
                                                width: menuPos.width,
                                                zIndex: 1000000,
                                                // Inline styling to ensure nice appearance even outside `.boostbot-admin` scope
                                                backgroundColor: '#ffffff',
                                                border: '1px solid #e5e7eb',
                                                borderRadius: '12px',
                                                boxShadow: '0 10px 40px rgba(0, 0, 0, 0.15)',
                                                overflow: 'hidden',
                                                direction: 'rtl',
                                                fontFamily: 'inherit',
                                            }}
                                            onMouseDown={(e) => e.stopPropagation()}
                                        >
                                            {/* Search input */}
                                            {(useSearchMode || contentItems.length > 10) && (
                                                <div className="sticky top-0 p-2 bg-white border-b" style={{ backgroundColor: '#ffffff', borderBottom: '1px solid #e5e7eb' }}>
                                                    <input
                                                        type="text"
                                                        value={searchQuery}
                                                        onChange={(e) => setSearchQuery(e.target.value)}
                                                        placeholder={t('🔍 Search...')}
                                                        className="w-full px-3 py-1.5 text-sm border border-gray-200 rounded-lg"
                                                        style={{
                                                            width: '100%',
                                                            border: '1px solid #e5e7eb',
                                                            borderRadius: '10px',
                                                            padding: '8px 12px',
                                                            fontSize: '14px',
                                                            outline: 'none',
                                                        }}
                                                    />
                                                </div>
                                            )}

                                            {/* "All items" option */}
                                            <button
                                                type="button"
                                                onClick={handleSelectAll}
                                                className={`w-full px-3 py-2 text-sm text-right hover:bg-gray-100 flex items-center gap-2 ${
                                                    itemIds.length === 0 ? 'bg-primary-50 text-primary-700 font-medium' : ''
                                                }`}
                                                style={{
                                                    width: '100%',
                                                    display: 'flex',
                                                    alignItems: 'center',
                                                    gap: '8px',
                                                    padding: '10px 12px',
                                                    fontSize: '14px',
                                                    backgroundColor: itemIds.length === 0 ? '#eff6ff' : '#ffffff',
                                                    color: itemIds.length === 0 ? '#1d4ed8' : '#111827',
                                                    border: 'none',
                                                    cursor: 'pointer',
                                                    textAlign: 'right',
                                                }}
                                            >
                                                <span className="w-4 h-4 flex items-center justify-center">
                                                    {itemIds.length === 0 && '✓'}
                                                </span>
                                                {allItemsLabel}
                                            </button>

                                            <div className="border-t border-gray-200" style={{ borderTop: '1px solid #e5e7eb' }} />

                                            {/* Scrollable items list */}
                                            <div className="max-h-48 overflow-y-auto" style={{ maxHeight: '260px', overflowY: 'auto' }}>
                                                {isSearching && (
                                                    <div className="px-3 py-2 text-sm text-gray-500 text-center" style={{ padding: '10px 12px', fontSize: '14px', color: '#6b7280' }}>
                                                        {t('Searching...')}
                                                    </div>
                                                )}

                                                {!isSearching && contentItems.length === 0 ? (
                                                    <div className="px-3 py-2 text-sm text-gray-500 text-center" style={{ padding: '10px 12px', fontSize: '14px', color: '#6b7280' }}>
                                                        {searchQuery ? t('No results found') : t('No items')}
                                                    </div>
                                                ) : !isSearching && (
                                                    contentItems.map(item => {
                                                        const isSelected = itemIds.includes(item.id)
                                                        const isDisabled = item.assigned_bot && !isSelected

                                                        return (
                                                            <label
                                                                key={item.id}
                                                                className={`flex items-center gap-3 px-3 py-2 text-sm cursor-pointer hover:bg-gray-50 ${
                                                                    isDisabled ? 'opacity-50 cursor-not-allowed' : ''
                                                                } ${isSelected ? 'bg-primary-50' : ''}`}
                                                                title={isDisabled ? sprintf(t('Assigned to bot: %s'), item.assigned_bot?.bot_name ?? '') : ''}
                                                                style={{
                                                                    display: 'flex',
                                                                    alignItems: 'flex-start',
                                                                    gap: '10px',
                                                                    padding: '10px 12px',
                                                                    cursor: isDisabled ? 'not-allowed' : 'pointer',
                                                                    backgroundColor: isSelected ? '#eff6ff' : '#ffffff',
                                                                    color: '#111827',
                                                                    opacity: isDisabled ? 0.5 : 1,
                                                                    borderBottom: '1px solid rgba(229,231,235,0.6)',
                                                                }}
                                                            >
                                                                <input
                                                                    type="checkbox"
                                                                    checked={isSelected}
                                                                    disabled={!!isDisabled}
                                                                    onChange={() => !isDisabled && toggleItemSelection(item.id)}
                                                                    className="w-4 h-4 text-primary-600 rounded border-gray-300 focus:ring-primary-500"
                                                                    style={{
                                                                        width: '16px',
                                                                        height: '16px',
                                                                        marginTop: '2px',
                                                                        accentColor: '#3BC2D0',
                                                                    }}
                                                                />
                                                                <span
                                                                    className={`flex-1 ${isSelected ? 'text-primary-700 font-medium' : ''}`}
                                                                    style={{
                                                                        flex: 1,
                                                                        whiteSpace: 'normal',
                                                                        overflowWrap: 'anywhere',
                                                                        lineHeight: 1.35,
                                                                    }}
                                                                >
                                                                    {item.title}
                                                                </span>
                                                                {isDisabled && (
                                                                    <span className="text-xs text-gray-400 flex-shrink-0" style={{ fontSize: '12px', color: '#9ca3af', marginTop: '2px' }}>
                                                                        🔒 {item.assigned_bot?.bot_name}
                                                                    </span>
                                                                )}
                                                            </label>
                                                        )
                                                    })
                                                )}
                                            </div>

                                            {/* Footer with selection count */}
                                            {itemIds.length > 0 && (
                                                <div
                                                    className="sticky bottom-0 px-3 py-2 text-xs text-primary-600 bg-primary-50 border-t flex items-center justify-between"
                                                    style={{
                                                        position: 'sticky',
                                                        bottom: 0,
                                                        display: 'flex',
                                                        justifyContent: 'space-between',
                                                        alignItems: 'center',
                                                        padding: '10px 12px',
                                                        fontSize: '12px',
                                                        backgroundColor: '#eff6ff',
                                                        borderTop: '1px solid #e5e7eb',
                                                        color: '#2563eb',
                                                    }}
                                                >
                                                    <span>{sprintf(t('%s items selected'), itemIds.length)}</span>
                                                    <button
                                                        type="button"
                                                        onClick={handleSelectAll}
                                                        className="text-gray-500 hover:text-gray-700"
                                                        style={{
                                                            border: 'none',
                                                            background: 'transparent',
                                                            cursor: 'pointer',
                                                            color: '#6b7280',
                                                            fontSize: '12px',
                                                        }}
                                                    >
                                                        {t('Clear selection')}
                                                    </button>
                                                </div>
                                            )}
                                        </div>,
                                        document.body
                                    )}
                            </div>
                        )}

                        {/* Loading state */}
                        {postType && isLoadingItems && (
                            <div className="flex-1 px-2 py-2 text-sm text-gray-400">
                                {t('Loading items...')}
                            </div>
                        )}
                    </div>
                )}

                {condition.type === 'taxonomy' && (
                    <input
                        type="text"
                        value={condition.value as string || ''}
                        onChange={(e) => onUpdate({ value: e.target.value })}
                        placeholder={t('category:category-name')}
                        className="w-full px-2 py-2 text-sm rounded-lg border border-gray-200"
                        dir="ltr"
                    />
                )}

                {condition.type === 'url_contains' && (
                    <input
                        type="text"
                        value={condition.value as string || ''}
                        onChange={(e) => onUpdate({ value: e.target.value })}
                        placeholder={t('/products/ or /contact/')}
                        className="w-full px-2 py-2 text-sm rounded-lg border border-gray-200"
                        dir="ltr"
                    />
                )}

                {(condition.type === 'all' || condition.type === 'homepage') && (
                    <span className="text-sm text-gray-500 py-2 block">
                        {(() => {
                            if (condition.type === 'all') {
                                if (isLocked) return t('Default bot: displayed everywhere possible (unless excluded)')
                                return condition.operator === 'exclude' ? t('Will not be displayed on all site pages') : t('Will be displayed on all site pages')
                            }
                            return condition.operator === 'exclude' ? t('Will not be displayed on the homepage') : t('Will be displayed on the homepage')
                        })()}
                    </span>
                )}
            </div>

            {/* Remove */}
            <button
                type="button"
                onClick={onRemove}
                disabled={isLocked}
                className="p-2 text-gray-400 hover:text-red-600 transition-colors flex-shrink-0"
                title={t('Remove condition')}
            >
                <Trash2 className="w-4 h-4" />
            </button>
        </div>
    )
}
