/**
 * WooCommerce Preset Detail/Edit Page
 * @since 1.3.0 (Week 25)
 *
 * Open layout with 6 card sections (no accordions).
 * Two-tier product model: Global Product Scope + Bundle Product Scope.
 */

import { useState, useEffect, useRef } from 'react'
import { useParams, useNavigate, useSearchParams } from 'react-router-dom'
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query'
import {
    Save,
    ArrowRight,
    Package,
    Tag,
    Settings,
    Plus,
    Trash2,
    X,
    Search,
    Percent,
    ShoppingCart,
    MessageCircle,
    AlertTriangle,
    CreditCard,
    Layers,
} from 'lucide-react'
import { PageHeader } from '@/components/layout/PageHeader'
import { Card, CardContent, CardHeader } from '@/components/common/Card'
import { UnsavedChangesModal } from '@/components/common/UnsavedChangesModal'
import { useUnsavedChanges } from '@/hooks/useUnsavedChanges'
import { apiClient } from '@/api/client'
import { useLanguage } from '@/contexts/LanguageContext'
import { sprintf, t, translateForLocale } from '@/lib/i18n'
import { IndexedProductSearchPicker } from '@/components/shared/IndexedProductSearchPicker'
import { IndexedCategoryMultiSelect } from '@/components/shared/IndexedCategoryMultiSelect'

interface WooCommerceCoupon {
    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
    applicable_categories: number[] | string
    is_active: number
    for_widget: number
    for_bundle: number
    wc_coupon_code?: string
    wc_discount_type?: string
    wc_discount_amount?: number
    wc_is_valid?: boolean
}

interface BudgetRange {
    label_he: string
    label_en: string
    min: number
    max: number
    icon: string
}

interface DiscountTier {
    min_amount: number
    max_amount: number | null
    discount: number
}

interface WooCommercePreset {
    id: number
    name: string
    slug: string
    description: string | null
    is_default: number
    is_system: number
    is_active: number
    language?: string

    budget_ranges: BudgetRange[]
    bundle_enabled: number
    bundle_min_products: number
    bundle_max_products: number
    bundle_discount_type: 'percent' | 'fixed' | 'tiered'
    bundle_discount_value: number
    bundle_discount_method: 'coupon' | 'line_item'

    // Product Settings (Global — Tier 1)
    product_mode: 'all' | 'categories' | 'specific'
    allowed_categories: number[]
    excluded_categories: number[]
    specific_product_ids: number[]
    preferred_product_ids: number[]
    excluded_product_ids: number[]
    include_on_sale: number
    include_variable: number
    include_featured_only: number
    min_stock: number
    min_rating: number
    max_single_product_percent: number

    // Product Cards
    product_card_enabled: number

    // Bundle Product Scope (Tier 2)
    bundle_product_mode: 'all' | 'categories' | 'specific'
    bundle_allowed_categories: number[]
    bundle_excluded_categories: number[]
    bundle_specific_product_ids: number[]
    bundle_excluded_product_ids: number[]

    // Pricing Settings
    discount_tiers: DiscountTier[]
    max_discount_amount: number | null
    min_order_for_discount: number
    show_original_prices: number
    show_savings: number
    show_per_product_savings: number
    round_prices: number
    round_to: number

    // Coupon Settings
    coupon_enabled: number
    coupon_mode: 'none' | 'auto' | 'select' | 'generate'
    coupon_auto_apply: number
    auto_coupon_id: number | null
    auto_select_best_coupon: number
    generate_unique_coupon: number
    generated_coupon_prefix: string
    generated_coupon_discount: number
    generated_coupon_expiry_days: number
    show_coupon_code: number
    show_coupon_value: number
    coupon_max_per_order: number

    // UI Settings
    allow_customization: number
    cart_redirect: number
    show_cart_button: number

    // Messages
    intro_message: string
    loading_message: string
    success_message: string
    empty_message: string
    error_message: string

    coupons?: WooCommerceCoupon[]
}

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

interface CategoryOption {
    id: number
    name: string
    slug: string
    count: number
}

function getCurrencySymbolForLanguage(language: string): string {
    const cfg = (window as any).boostbotAdmin
    return cfg?.woocommerce_currency_by_language?.[language]
        || cfg?.woocommerce_currency_symbol
        || '₪'
}

function getDefaultBudgetRanges(symbol: string): BudgetRange[] {
    return [
        { label_he: sprintf(translateForLocale('Up to %s100', 'he'), symbol), label_en: sprintf('Up to %s100', symbol), min: 0, max: 100, icon: '💰' },
        { label_he: `${symbol}100-300`, label_en: `${symbol}100-300`, min: 100, max: 300, icon: '💎' },
        { label_he: `${symbol}300-500`, label_en: `${symbol}300-500`, min: 300, max: 500, icon: '👑' },
        { label_he: sprintf(translateForLocale('Over %s500', 'he'), symbol), label_en: sprintf('Over %s500', symbol), min: 500, max: 99999, icon: '🌟' },
    ]
}

function safeParseIds(value: unknown): number[] {
    if (Array.isArray(value)) return value.map(Number).filter(n => !isNaN(n))
    if (typeof value === 'string' && value.trim()) {
        try { return JSON.parse(value).map(Number).filter((n: number) => !isNaN(n)) } catch { return [] }
    }
    return []
}

function safeParseJSON<T>(value: unknown, fallback: T): T {
    if (Array.isArray(value)) return value as T
    if (typeof value === 'string' && value.trim()) {
        try { return JSON.parse(value) as T } catch { return fallback }
    }
    return fallback
}

// ---------------------------------------------------------------------------
// SectionHeader — reusable heading for each Card section
// ---------------------------------------------------------------------------
function SectionHeader({ title, subtitle, icon }: { title: string; subtitle?: string; icon?: React.ReactNode }) {
    return (
        <div className="mb-4 flex items-start gap-3">
            {icon && (
                <div className="w-10 h-10 rounded-lg bg-gray-100 flex items-center justify-center flex-shrink-0 mt-0.5">
                    {icon}
                </div>
            )}
            <div>
                <h3 className="text-lg font-semibold text-gray-900">{title}</h3>
                {subtitle && <p className="text-sm text-gray-500 mt-1">{subtitle}</p>}
            </div>
        </div>
    )
}

// ---------------------------------------------------------------------------
// ProductScopeEditor — used for both Global (Tier 1) and Bundle (Tier 2) scope
// ---------------------------------------------------------------------------
interface ProductScopeEditorProps {
    mode: string
    onModeChange: (mode: string) => void
    allowedCategories: number[]
    onAllowedCategoriesChange: (ids: number[]) => void
    excludedCategories: number[]
    onExcludedCategoriesChange: (ids: number[]) => void
    specificProductIds: number[]
    onSpecificProductIdsChange: (ids: number[]) => void
    excludedProductIds: number[]
    onExcludedProductIdsChange: (ids: number[]) => void
    language: string
    showQualityFilters?: boolean
    qualityFilters?: {
        minStock: number
        minRating: number
        includeOnSale: number
        includeVariable: number
        includeFeaturedOnly: number
    }
    onQualityFilterChange?: (field: string, value: number) => void
    showPreferred?: boolean
    preferredProductIds?: number[]
    onPreferredProductIdsChange?: (ids: number[]) => void
    showBundleFilters?: boolean
    includeOnSale?: number
    onIncludeOnSaleChange?: (val: number) => void
    includeVariable?: number
    onIncludeVariableChange?: (val: number) => void
    maxSingleProductPercent?: number
    onMaxSingleProductPercentChange?: (val: number) => void
}

function ProductScopeEditor({
    mode,
    onModeChange,
    allowedCategories,
    onAllowedCategoriesChange,
    excludedCategories,
    onExcludedCategoriesChange,
    specificProductIds,
    onSpecificProductIdsChange,
    excludedProductIds,
    onExcludedProductIdsChange,
    language,
    showQualityFilters,
    qualityFilters,
    onQualityFilterChange,
    showPreferred,
    preferredProductIds,
    onPreferredProductIdsChange,
    showBundleFilters,
    includeOnSale,
    onIncludeOnSaleChange,
    includeVariable,
    onIncludeVariableChange,
    maxSingleProductPercent,
    onMaxSingleProductPercentChange,
}: ProductScopeEditorProps) {
    const modeOptions = [
        { value: 'all', label: t('All Products') },
        { value: 'categories', label: t('Selected Categories') },
        { value: 'specific', label: t('Specific Products') },
    ]

    return (
        <div className="space-y-4">
            {/* Product Mode — segmented control */}
            <div className="flex flex-wrap gap-1 bg-gray-100 rounded-lg p-1 max-w-md">
                {modeOptions.map(opt => (
                    <button
                        key={opt.value}
                        type="button"
                        onClick={() => onModeChange(opt.value)}
                        className={`flex-1 px-3 py-2 text-sm font-medium rounded-md transition-colors ${
                            mode === opt.value
                                ? 'bg-white text-gray-900 shadow-sm'
                                : 'text-gray-600 hover:text-gray-900'
                        }`}
                    >
                        {opt.label}
                    </button>
                ))}
            </div>

            {/* Category picker */}
            {mode === 'categories' && (
                <div>
                    <label className="block text-sm font-medium text-gray-700 mb-2">
                        {t('Include products from these categories:')}
                    </label>
                    <IndexedCategoryMultiSelect
                        selectedIds={allowedCategories}
                        onChange={onAllowedCategoriesChange}
                        language={language}
                    />
                </div>
            )}

            {/* Product picker */}
            {mode === 'specific' && (
                <div>
                    <label className="block text-sm font-medium text-gray-700 mb-2">
                        {t('Include these products:')}
                    </label>
                    <IndexedProductSearchPicker
                        selectedIds={specificProductIds}
                        onChange={onSpecificProductIdsChange}
                        language={language}
                    />
                </div>
            )}

            {/* Exclusions panel */}
            <div className="border border-gray-200 rounded-lg p-4 space-y-4 bg-gray-50/50">
                <h4 className="text-sm font-semibold text-gray-800">{t('Exclusions')}</h4>
                <p className="text-xs text-gray-500 -mt-2">
                    {t('Excluded items are hidden from the bot even if they match the selection above.')}
                </p>

                <div>
                    <label className="block text-sm font-medium text-gray-700 mb-2">
                        {t('Never recommend these categories:')}
                    </label>
                    <IndexedCategoryMultiSelect
                        selectedIds={excludedCategories}
                        onChange={onExcludedCategoriesChange}
                        language={language}
                    />
                </div>

                <div>
                    <label className="block text-sm font-medium text-gray-700 mb-2">
                        {t('Never recommend these products:')}
                    </label>
                    <IndexedProductSearchPicker
                        selectedIds={excludedProductIds}
                        onChange={onExcludedProductIdsChange}
                        language={language}
                    />
                </div>
            </div>

            {/* Preferred products (bundle scope) */}
            {showPreferred && preferredProductIds !== undefined && onPreferredProductIdsChange && (
                <div>
                    <label className="block text-sm font-medium text-gray-700 mb-1">
                        {t('Preferred Products')}
                    </label>
                    <p className="text-xs text-gray-500 mb-2">
                        {t('These products are preferred when building bundles')}
                    </p>
                    <IndexedProductSearchPicker
                        selectedIds={preferredProductIds}
                        onChange={onPreferredProductIdsChange}
                        language={language}
                    />
                </div>
            )}

            {/* Bundle-specific filters */}
            {showBundleFilters && (
                <div className="flex flex-wrap gap-4 pt-2">
                    <label className="flex items-center gap-2 cursor-pointer">
                        <input
                            type="checkbox"
                            checked={Number(includeOnSale) === 1}
                            onChange={e => onIncludeOnSaleChange?.(e.target.checked ? 1 : 0)}
                            className="w-4 h-4 text-primary-600 border-gray-300 rounded focus:ring-primary-500"
                        />
                        <span className="text-sm text-gray-700">{t('Include on-sale products')}</span>
                    </label>
                    <label className="flex items-center gap-2 cursor-pointer">
                        <input
                            type="checkbox"
                            checked={Number(includeVariable) === 1}
                            onChange={e => onIncludeVariableChange?.(e.target.checked ? 1 : 0)}
                            className="w-4 h-4 text-primary-600 border-gray-300 rounded focus:ring-primary-500"
                        />
                        <span className="text-sm text-gray-700">{t('Include variable products')}</span>
                    </label>
                    {maxSingleProductPercent !== undefined && onMaxSingleProductPercentChange && (
                        <div className="flex items-center gap-2">
                            <label className="text-sm text-gray-700">{t('Max single product %')}:</label>
                            <input
                                type="number"
                                min={10}
                                max={100}
                                value={maxSingleProductPercent}
                                onChange={e => onMaxSingleProductPercentChange(parseInt(e.target.value) || 50)}
                                className="w-20 px-2 py-1 border border-gray-300 rounded-lg text-sm focus:ring-2 focus:ring-primary-500"
                            />
                            <span className="text-xs text-gray-400" title={t('Prevents one product from dominating the bundle')}>?</span>
                        </div>
                    )}
                </div>
            )}

            {/* Quality filters (global scope only) */}
            {showQualityFilters && qualityFilters && onQualityFilterChange && (
                <div className="pt-3 border-t border-gray-100">
                    <h4 className="text-sm font-semibold text-gray-800 mb-3">{t('Quality Filters')}</h4>
                    <div className="grid grid-cols-2 md:grid-cols-3 gap-4">
                        <div>
                            <label className="block text-xs text-gray-600 mb-1">{t('Min Stock')}</label>
                            <input
                                type="number"
                                min={0}
                                value={qualityFilters.minStock}
                                onChange={e => onQualityFilterChange('min_stock', parseInt(e.target.value) || 0)}
                                className="w-full px-2 py-1.5 border border-gray-300 rounded-lg text-sm focus:ring-2 focus:ring-primary-500"
                            />
                        </div>
                        <div>
                            <label className="block text-xs text-gray-600 mb-1">{t('Min Rating')}</label>
                            <input
                                type="number"
                                min={0}
                                max={5}
                                step={0.5}
                                value={qualityFilters.minRating}
                                onChange={e => onQualityFilterChange('min_rating', parseFloat(e.target.value) || 0)}
                                className="w-full px-2 py-1.5 border border-gray-300 rounded-lg text-sm focus:ring-2 focus:ring-primary-500"
                            />
                        </div>
                    </div>
                    <div className="flex flex-wrap gap-4 mt-3">
                        <label className="flex items-center gap-2 cursor-pointer">
                            <input
                                type="checkbox"
                                checked={qualityFilters.includeOnSale === 1}
                                onChange={e => onQualityFilterChange('include_on_sale', e.target.checked ? 1 : 0)}
                                className="w-4 h-4 text-primary-600 border-gray-300 rounded focus:ring-primary-500"
                            />
                            <span className="text-sm text-gray-700">{t('Include on-sale products')}</span>
                        </label>
                        <label className="flex items-center gap-2 cursor-pointer">
                            <input
                                type="checkbox"
                                checked={qualityFilters.includeVariable === 1}
                                onChange={e => onQualityFilterChange('include_variable', e.target.checked ? 1 : 0)}
                                className="w-4 h-4 text-primary-600 border-gray-300 rounded focus:ring-primary-500"
                            />
                            <span className="text-sm text-gray-700">{t('Include variable products')}</span>
                        </label>
                        <label className="flex items-center gap-2 cursor-pointer">
                            <input
                                type="checkbox"
                                checked={qualityFilters.includeFeaturedOnly === 1}
                                onChange={e => onQualityFilterChange('include_featured_only', e.target.checked ? 1 : 0)}
                                className="w-4 h-4 text-primary-600 border-gray-300 rounded focus:ring-primary-500"
                            />
                            <span className="text-sm text-gray-700">{t('Featured only')}</span>
                        </label>
                    </div>
                </div>
            )}
        </div>
    )
}

// ---------------------------------------------------------------------------
// Main page component
// ---------------------------------------------------------------------------
export function WooCommercePresetDetail() {
    const { id } = useParams()
    const navigate = useNavigate()
    const [searchParams] = useSearchParams()
    const returnTo = searchParams.get('returnTo')
    const queryClient = useQueryClient()
    const { currentLanguage } = useLanguage()
    const isNew = !id || id === 'new'
    const currencySymbol = getCurrencySymbolForLanguage(currentLanguage)

    const [formData, setFormData] = useState<Partial<WooCommercePreset>>({
        name: '',
        description: '',
        is_active: 1,

        budget_ranges: getDefaultBudgetRanges(currencySymbol),

        // Bundle Settings
        bundle_enabled: 1,
        bundle_min_products: 2,
        bundle_max_products: 5,
        bundle_discount_type: 'percent',
        bundle_discount_value: 10,
        bundle_discount_method: 'coupon',

        // Product Settings (Global — Tier 1)
        product_mode: 'all',
        allowed_categories: [],
        excluded_categories: [],
        specific_product_ids: [],
        preferred_product_ids: [],
        excluded_product_ids: [],
        include_on_sale: 1,
        include_variable: 1,
        include_featured_only: 0,
        min_stock: 1,
        min_rating: 0,
        max_single_product_percent: 50,

        // Product Cards
        product_card_enabled: 1,

        // Bundle Product Scope (Tier 2)
        bundle_product_mode: 'all',
        bundle_allowed_categories: [],
        bundle_excluded_categories: [],
        bundle_specific_product_ids: [],
        bundle_excluded_product_ids: [],

        // Pricing Settings
        discount_tiers: [],
        max_discount_amount: null,
        min_order_for_discount: 0,
        show_original_prices: 1,
        show_savings: 1,
        show_per_product_savings: 0,
        round_prices: 1,
        round_to: 0,

        // Coupon Settings
        coupon_enabled: 0,
        coupon_mode: 'none',
        auto_coupon_id: null,
        auto_select_best_coupon: 0,
        generate_unique_coupon: 0,
        generated_coupon_prefix: 'BUNDLE-',
        generated_coupon_discount: 10,
        generated_coupon_expiry_days: 7,
        show_coupon_code: 1,
        show_coupon_value: 1,
        coupon_max_per_order: 1,

        // UI Settings
        allow_customization: 1,
        cart_redirect: 1,
        show_cart_button: 0,

        // Messages
        intro_message: t('Let me build the perfect bundle for you! 🎁'),
        loading_message: t('Looking for the perfect products for you... ⏳'),
        success_message: t('Here is the bundle I prepared for you! 🎉'),
        empty_message: t('No matching products were found. Try something else?'),
        error_message: t('Something went wrong. Please try again.'),
    })

    const [showAddCoupon, setShowAddCoupon] = useState(false)
    const [couponSearchQuery, setCouponSearchQuery] = useState('')
    const justSavedRef = useRef(false)

    // Fetch preset
    const { data: presetData, isLoading } = useQuery({
        queryKey: ['woocommerce-preset', id],
        queryFn: () => apiClient.get<{ data: { preset: WooCommercePreset } }>(`woocommerce/presets/${id}`),
        enabled: !isNew,
    })

    // Fetch WooCommerce coupons for selection
    const { data: wcCouponsData } = useQuery({
        queryKey: ['woocommerce-available-coupons'],
        queryFn: () => apiClient.get<{ data: { coupons: WCCouponOption[] } }>('woocommerce/available-coupons'),
    })

    // Pre-fetch indexed categories for react-query cache (used by IndexedCategoryMultiSelect)
    useQuery({
        queryKey: ['woocommerce-indexed-categories', currentLanguage],
        queryFn: () => apiClient.get<{ data: { categories: CategoryOption[] } }>('woocommerce/indexed-categories', { language: currentLanguage }),
    })

    const [isDataLoaded, setIsDataLoaded] = useState(false)

    const defaultBudgetRanges: BudgetRange[] = getDefaultBudgetRanges(currencySymbol)

    // Update form when data loads
    useEffect(() => {
        if (presetData?.data?.preset) {
            if (justSavedRef.current) {
                justSavedRef.current = false
                return
            }
            // Only hydrate the form on the initial load. Later refetches must not
            // clobber the user's unsaved edits to other fields (coupon mutations
            // update formData.coupons directly instead of refetching the preset).
            if (isDataLoaded) {
                return
            }
            const preset = presetData.data.preset
            setFormData({
                ...preset,
                budget_ranges: safeParseJSON<BudgetRange[]>(preset.budget_ranges, defaultBudgetRanges),
                product_card_enabled: preset.product_card_enabled ?? 1,
                bundle_product_mode: (preset.bundle_product_mode || 'all') as 'all' | 'categories' | 'specific',
                bundle_allowed_categories: safeParseIds(preset.bundle_allowed_categories),
                bundle_excluded_categories: safeParseIds(preset.bundle_excluded_categories),
                bundle_specific_product_ids: safeParseIds(preset.bundle_specific_product_ids),
                bundle_excluded_product_ids: safeParseIds(preset.bundle_excluded_product_ids),
                show_cart_button: preset.show_cart_button ?? 0,
            })
            setIsDataLoaded(true)
        }
    }, [presetData])

    // Save mutation
    const saveMutation = useMutation({
        mutationFn: (data: Partial<WooCommercePreset>) => {
            if (isNew) {
                return apiClient.post('woocommerce/presets', { ...data, language: currentLanguage })
            }
            return apiClient.put(`woocommerce/presets/${id}`, data)
        },
        onSuccess: (response: any) => {
            queryClient.invalidateQueries({ queryKey: ['woocommerce-presets'] })
            queryClient.invalidateQueries({ queryKey: ['woocommerce-preset', id] })
            
            if (isNew && response?.data?.preset?.id) {
                const returnQuery = returnTo ? `?returnTo=${encodeURIComponent(returnTo)}` : ''
                navigate(`/woocommerce-presets/${response.data.preset.id}${returnQuery}`)
            }
            
            alert(t('Preset saved successfully!'))
        },
        onError: (error: any) => {
            console.error('Save failed:', error)
            alert(error?.message || t('Error saving preset'))
        },
    })

    // Add coupon mutation — merge the new coupon into formData.coupons instead of
    // invalidating/refetching the preset (which would clobber unsaved edits).
    const addCouponMutation = useMutation({
        mutationFn: (data: Partial<WooCommerceCoupon>) =>
            apiClient.post<{ data: { coupon: WooCommerceCoupon } }>(`woocommerce/presets/${id}/coupons`, data),
        onSuccess: (response: any) => {
            const newCoupon = response?.data?.coupon as WooCommerceCoupon | undefined
            if (newCoupon) {
                // The create endpoint returns the raw row without WC enrichment;
                // pull the display fields from the selected WC coupon so the list
                // renders correctly without a full refetch.
                const wc = wcCoupons.find(c => c.id === Number(newCoupon.wc_coupon_id))
                const merged: WooCommerceCoupon = wc
                    ? {
                          ...newCoupon,
                          wc_coupon_code: wc.code,
                          wc_discount_type: wc.discount_type,
                          wc_discount_amount: wc.discount_amount,
                          wc_is_valid: true,
                      }
                    : newCoupon
                setFormData(prev => ({
                    ...prev,
                    coupons: [...(prev.coupons || []), merged],
                }))
            }
            setShowAddCoupon(false)
            setCouponSearchQuery('')
        },
        onError: (error: any) => {
            console.error('Add coupon failed:', error)
            alert(error?.message || t('Error adding coupon'))
        },
    })

    // Delete coupon mutation — drop the coupon from formData.coupons directly.
    const deleteCouponMutation = useMutation({
        mutationFn: (couponId: number) => apiClient.delete(`woocommerce/coupons/${couponId}`),
        onSuccess: (_response: any, couponId: number) => {
            setFormData(prev => ({
                ...prev,
                coupons: (prev.coupons || []).filter(c => c.id !== couponId),
            }))
        },
        onError: (error: any) => {
            console.error('Delete coupon failed:', error)
            alert(error?.message || t('Error deleting coupon'))
        },
    })

    const updateCouponMutation = useMutation({
        mutationFn: ({ couponId, data }: { couponId: number; data: Partial<WooCommerceCoupon> }) =>
            apiClient.put<{ data: { coupon: WooCommerceCoupon } }>(`woocommerce/coupons/${couponId}`, data),
        onSuccess: (response: any) => {
            const updated = response?.data?.coupon as WooCommerceCoupon | undefined
            if (updated) {
                // Merge the updated row onto the existing coupon so the WC-enriched
                // display fields (not returned by this endpoint) are preserved.
                setFormData(prev => ({
                    ...prev,
                    coupons: (prev.coupons || []).map(c =>
                        c.id === updated.id ? { ...c, ...updated } : c
                    ),
                }))
            }
        },
        onError: (error: any) => {
            console.error('Update coupon failed:', error)
            alert(error?.message || t('Error updating coupon'))
        },
    })

    const handleSave = async () => {
        if (!formData.name?.trim()) {
            alert(t('Preset name is required'))
            return
        }
        await saveMutation.mutateAsync(formData)
        if (!isNew) {
            justSavedRef.current = true
            setOriginalData()
        }
    }

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

    const handleBack = () => {
        checkNavigationSafe(() => {
            if (returnTo && returnTo.startsWith('/') && !returnTo.startsWith('//')) {
                navigate(returnTo)
            } else {
                navigate('/woocommerce-settings')
            }
        })
    }

    const handleAddCoupon = (wcCoupon: WCCouponOption) => {
        addCouponMutation.mutate({
            wc_coupon_id: wcCoupon.id,
            display_name: wcCoupon.code,
            description: wcCoupon.description,
            priority: 0,
            for_widget: 1,
            for_bundle: 1,
        })
    }

    const handleCouponPurposeToggle = (
        couponId: number,
        field: 'for_widget' | 'for_bundle',
        checked: boolean
    ) => {
        updateCouponMutation.mutate({
            couponId,
            data: {
                [field]: checked ? 1 : 0,
            },
        })
    }

    const handleDeleteCoupon = (couponId: number, couponName: string) => {
        if (confirm(`${t('Are you sure you want to remove')} "${couponName}"?`)) {
            deleteCouponMutation.mutate(couponId)
        }
    }

    const wcCoupons = wcCouponsData?.data?.coupons || []
    const presetCoupons = formData.coupons || presetData?.data?.preset?.coupons || []

    const existingCouponIds = presetCoupons.map(c => c.wc_coupon_id)
    const availableCoupons = wcCoupons.filter(c => !existingCouponIds.includes(c.id))
    const filteredCoupons = availableCoupons.filter(c =>
        c.code.toLowerCase().includes(couponSearchQuery.toLowerCase()) ||
        c.description?.toLowerCase().includes(couponSearchQuery.toLowerCase())
    )

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

    const presetLanguage = (formData as any).language || currentLanguage

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

            <PageHeader
                title={isNew ? t('New WooCommerce Preset') : `${t('Edit')}: ${formData.name}`}
                subtitle={isNew ? t('Configure bundles and coupons') : t('Update preset settings')}
            >
                <div className="flex items-center gap-2">
                    <button
                        onClick={handleBack}
                        className="flex items-center gap-2 px-4 py-2 border border-gray-300 text-gray-700 rounded-lg hover:bg-gray-50 transition-colors"
                    >
                        <ArrowRight className="w-4 h-4" />
                        {t('Back')}
                    </button>
                    <button
                        onClick={handleSave}
                        disabled={saveMutation.isPending}
                        className={`flex items-center gap-2 px-4 py-2 rounded-lg transition-all disabled:opacity-50 ${
                            hasUnsavedChanges
                                ? 'bg-amber-500 hover:bg-amber-600 animate-pulse'
                                : 'bg-primary-600 hover:bg-primary-700'
                        } text-white`}
                    >
                        {saveMutation.isPending ? (
                            <div className="w-4 h-4 border-2 border-white border-t-transparent rounded-full animate-spin" />
                        ) : (
                            <Save className="w-4 h-4" />
                        )}
                        {saveMutation.isPending ? t('Saving...') : hasUnsavedChanges ? t('Save Changes') : t('Save')}
                    </button>
                </div>
            </PageHeader>

            {/* Unsaved changes indicator */}
            {hasUnsavedChanges && (
                <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>
            )}

            {/* ================================================================ */}
            {/* Section 1: Preset Info                                           */}
            {/* ================================================================ */}
            <Card>
                <CardHeader>
                    <SectionHeader
                        title={t('Preset Info')}
                        icon={<Settings className="w-5 h-5 text-primary-600" />}
                    />
                </CardHeader>
                <CardContent className="space-y-4">
                    <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                        <div>
                            <label className="block text-sm font-medium text-gray-700 mb-1">
                                {t('Preset Name')} *
                            </label>
                            <input
                                type="text"
                                value={formData.name || ''}
                                onChange={e => setFormData(prev => ({ ...prev, name: 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"
                                placeholder={t('e.g. 15% Bundle Discount')}
                            />
                        </div>
                        <div className="flex items-center gap-6">
                            <label className="flex items-center gap-2 cursor-pointer">
                                <input
                                    type="checkbox"
                                    checked={Number(formData.is_active) === 1}
                                    onChange={e => setFormData(prev => ({ ...prev, is_active: e.target.checked ? 1 : 0 }))}
                                    className="w-4 h-4 text-primary-600 border-gray-300 rounded focus:ring-primary-500"
                                />
                                <span className="text-sm text-gray-700">{t('Active')}</span>
                            </label>
                            {!isNew && presetLanguage && (
                                <span className="text-xs text-gray-400 border border-gray-200 px-2 py-1 rounded">
                                    {presetLanguage === 'he' ? '🇮🇱 Hebrew' : '🇺🇸 English'}
                                </span>
                            )}
                        </div>
                    </div>
                    <div>
                        <label className="block text-sm font-medium text-gray-700 mb-1">
                            {t('Description')}
                        </label>
                        <textarea
                            value={formData.description || ''}
                            onChange={e => setFormData(prev => ({ ...prev, description: e.target.value }))}
                            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"
                            placeholder={t('Short description of this preset...')}
                        />
                    </div>
                </CardContent>
            </Card>

            {/* ================================================================ */}
            {/* Section 2: Product Access — Global Scope (Tier 1)                */}
            {/* ================================================================ */}
            <Card>
                <CardHeader>
                    <SectionHeader
                        title={t('Product Access')}
                        subtitle={t('Define which products this bot can recommend and reference in conversations.')}
                        icon={<ShoppingCart className="w-5 h-5 text-blue-600" />}
                    />
                </CardHeader>
                <CardContent>
                    <ProductScopeEditor
                        mode={formData.product_mode || 'all'}
                        onModeChange={m => setFormData(prev => ({ ...prev, product_mode: m as 'all' | 'categories' | 'specific' }))}
                        allowedCategories={safeParseIds(formData.allowed_categories)}
                        onAllowedCategoriesChange={ids => setFormData(prev => ({ ...prev, allowed_categories: ids }))}
                        excludedCategories={safeParseIds(formData.excluded_categories)}
                        onExcludedCategoriesChange={ids => setFormData(prev => ({ ...prev, excluded_categories: ids }))}
                        specificProductIds={safeParseIds(formData.specific_product_ids)}
                        onSpecificProductIdsChange={ids => setFormData(prev => ({ ...prev, specific_product_ids: ids }))}
                        excludedProductIds={safeParseIds(formData.excluded_product_ids)}
                        onExcludedProductIdsChange={ids => setFormData(prev => ({ ...prev, excluded_product_ids: ids }))}
                        language={currentLanguage}
                        showQualityFilters
                        qualityFilters={{
                            minStock: Number(formData.min_stock) || 0,
                            minRating: Number(formData.min_rating) || 0,
                            includeOnSale: Number(formData.include_on_sale),
                            includeVariable: Number(formData.include_variable),
                            includeFeaturedOnly: Number(formData.include_featured_only),
                        }}
                        onQualityFilterChange={(field, value) => setFormData(prev => ({ ...prev, [field]: value }))}
                    />
                </CardContent>
            </Card>

            {/* ================================================================ */}
            {/* Section 3: Product Cards                                         */}
            {/* ================================================================ */}
            <Card>
                <CardHeader>
                    <SectionHeader
                        title={t('Product Cards')}
                        icon={<CreditCard className="w-5 h-5 text-indigo-600" />}
                    />
                </CardHeader>
                <CardContent>
                    <label className="flex items-center gap-3 cursor-pointer">
                        <input
                            type="checkbox"
                            checked={Number(formData.product_card_enabled) === 1}
                            onChange={e => setFormData(prev => ({ ...prev, product_card_enabled: e.target.checked ? 1 : 0 }))}
                            className="w-4 h-4 text-primary-600 border-gray-300 rounded focus:ring-primary-500"
                        />
                        <span className="text-sm font-medium text-gray-700">
                            {t('Allow this bot to show product cards')}
                        </span>
                    </label>
                    {Number(formData.product_card_enabled) === 1 && (
                        <p className="text-sm text-gray-500 mt-2 ms-7">
                            {t('The bot will display product cards when recommending individual items from the product scope above.')}
                        </p>
                    )}
                </CardContent>
            </Card>

            {/* ================================================================ */}
            {/* Section 4: Coupons                                               */}
            {/* ================================================================ */}
            <Card>
                <CardHeader>
                    <SectionHeader
                        title={t('Coupons')}
                        icon={<Tag className="w-5 h-5 text-green-600" />}
                    />
                </CardHeader>
                <CardContent className="space-y-4">
                    <label className="flex items-center gap-3 cursor-pointer">
                        <input
                            type="checkbox"
                            checked={Number(formData.coupon_enabled) === 1}
                            onChange={e => setFormData(prev => ({ ...prev, coupon_enabled: e.target.checked ? 1 : 0 }))}
                            className="w-4 h-4 text-primary-600 border-gray-300 rounded focus:ring-primary-500"
                        />
                        <span className="text-sm font-medium text-gray-700">
                            {t('Allow this bot to offer coupons')}
                        </span>
                    </label>

                    {Number(formData.coupon_enabled) === 1 && (
                        <div className="space-y-4 pt-2">
                            <p className="text-sm text-gray-500">
                                {t('Each linked coupon can be used separately for the coupon widget and for bundle discounts.')}
                            </p>
                            {/* Coupon mode + display settings */}
                            <div className="flex items-center gap-4 flex-wrap">
                                <label className="flex items-center gap-2 cursor-pointer">
                                    <input
                                        type="checkbox"
                                        checked={Number(formData.coupon_auto_apply) === 1}
                                        onChange={e => setFormData(prev => ({ ...prev, coupon_auto_apply: e.target.checked ? 1 : 0 }))}
                                        className="w-4 h-4 text-primary-600 border-gray-300 rounded focus:ring-primary-500"
                                    />
                                    <span className="text-sm text-gray-700">{t('Auto-apply coupon')}</span>
                                </label>
                                <label className="flex items-center gap-2 cursor-pointer">
                                    <input
                                        type="checkbox"
                                        checked={Number(formData.show_coupon_code) === 1}
                                        onChange={e => setFormData(prev => ({ ...prev, show_coupon_code: e.target.checked ? 1 : 0 }))}
                                        className="w-4 h-4 text-primary-600 border-gray-300 rounded focus:ring-primary-500"
                                    />
                                    <span className="text-sm text-gray-700">{t('Show coupon code')}</span>
                                </label>
                                <label className="flex items-center gap-2 cursor-pointer">
                                    <input
                                        type="checkbox"
                                        checked={Number(formData.show_coupon_value) === 1}
                                        onChange={e => setFormData(prev => ({ ...prev, show_coupon_value: e.target.checked ? 1 : 0 }))}
                                        className="w-4 h-4 text-primary-600 border-gray-300 rounded focus:ring-primary-500"
                                    />
                                    <span className="text-sm text-gray-700">{t('Show coupon value')}</span>
                                </label>
                                <div className="flex items-center gap-2">
                                    <label className="text-sm text-gray-700">{t('Max per order')}:</label>
                                    <input
                                        type="number"
                                        min={1}
                                        max={5}
                                        value={formData.coupon_max_per_order || 1}
                                        onChange={e => setFormData(prev => ({ ...prev, coupon_max_per_order: parseInt(e.target.value) || 1 }))}
                                        className="w-16 px-2 py-1 border border-gray-300 rounded focus:ring-2 focus:ring-primary-500"
                                    />
                                </div>
                            </div>

                            {/* Linked coupons list */}
                            {!isNew && presetCoupons.length > 0 && (
                                <div className="space-y-2">
                                    <h4 className="text-sm font-semibold text-gray-800">{t('Linked Coupons')}</h4>
                                    {presetCoupons.map(coupon => (
                                        <div
                                            key={coupon.id}
                                            className="flex items-center justify-between p-3 bg-gray-50 rounded-lg"
                                        >
                                            <div className="flex items-center gap-3">
                                                <div className="w-8 h-8 rounded-full bg-green-100 flex items-center justify-center">
                                                    <Tag className="w-4 h-4 text-green-600" />
                                                </div>
                                                <div>
                                                    <p className="font-medium text-gray-900">
                                                        {coupon.wc_coupon_code || coupon.display_name}
                                                    </p>
                                                    <p className="text-xs text-gray-500">
                                                        {coupon.wc_discount_type === 'percent' 
                                                            ? `${coupon.wc_discount_amount}%`
                                                            : `${currencySymbol}${coupon.wc_discount_amount}`
                                                        }
                                                        {coupon.min_cart_total && ` | ${t('Min')} ${currencySymbol}${coupon.min_cart_total}`}
                                                    </p>
                                                    <div className="flex flex-wrap gap-2 mt-2">
                                                        <label className="inline-flex items-center gap-2 text-xs text-gray-600">
                                                            <input
                                                                type="checkbox"
                                                                checked={Number(coupon.for_widget ?? 1) === 1}
                                                                disabled={updateCouponMutation.isPending}
                                                                onChange={e =>
                                                                    handleCouponPurposeToggle(coupon.id, 'for_widget', e.target.checked)
                                                                }
                                                                className="w-3.5 h-3.5 text-primary-600 border-gray-300 rounded focus:ring-primary-500"
                                                            />
                                                            <span>{t('Use in coupon widget')}</span>
                                                        </label>
                                                        <label className="inline-flex items-center gap-2 text-xs text-gray-600">
                                                            <input
                                                                type="checkbox"
                                                                checked={Number(coupon.for_bundle ?? 1) === 1}
                                                                disabled={updateCouponMutation.isPending}
                                                                onChange={e =>
                                                                    handleCouponPurposeToggle(coupon.id, 'for_bundle', e.target.checked)
                                                                }
                                                                className="w-3.5 h-3.5 text-primary-600 border-gray-300 rounded focus:ring-primary-500"
                                                            />
                                                            <span>{t('Use for bundle discounts')}</span>
                                                        </label>
                                                    </div>
                                                </div>
                                            </div>
                                            <div className="flex items-center gap-2">
                                                {coupon.wc_is_valid === false && (
                                                    <span className="px-2 py-1 text-xs bg-red-100 text-red-700 rounded-full">
                                                        {t('Invalid')}
                                                    </span>
                                                )}
                                                <span className="px-2 py-1 text-xs bg-blue-100 text-blue-700 rounded-full">
                                                    {t('Priority')}: {coupon.priority}
                                                </span>
                                                <button
                                                    onClick={() => handleDeleteCoupon(coupon.id, coupon.display_name)}
                                                    className="p-1 text-red-500 hover:bg-red-50 rounded transition-colors"
                                                >
                                                    <Trash2 className="w-4 h-4" />
                                                </button>
                                            </div>
                                        </div>
                                    ))}
                                </div>
                            )}

                            {/* Add coupon */}
                            {!isNew && (
                                <>
                                    {!showAddCoupon ? (
                                        <button
                                            onClick={() => setShowAddCoupon(true)}
                                            className="flex items-center gap-2 px-4 py-2 border border-dashed border-gray-300 rounded-lg text-gray-600 hover:bg-gray-50 hover:border-primary-300 transition-colors w-full justify-center"
                                        >
                                            <Plus className="w-4 h-4" />
                                            {t('Add Coupon')}
                                        </button>
                                    ) : (
                                        <div className="p-4 bg-gray-50 rounded-lg space-y-3">
                                            <div className="flex items-center justify-between">
                                                <h4 className="font-medium text-gray-900">{t('Select WooCommerce coupon')}</h4>
                                                <button
                                                    onClick={() => { setShowAddCoupon(false); setCouponSearchQuery('') }}
                                                    className="p-1 text-gray-400 hover:text-gray-600"
                                                >
                                                    <X className="w-4 h-4" />
                                                </button>
                                            </div>
                                            <div className="relative">
                                                <Search className="absolute right-3 top-1/2 -translate-y-1/2 w-4 h-4 text-gray-400" />
                                                <input
                                                    type="text"
                                                    value={couponSearchQuery}
                                                    onChange={e => setCouponSearchQuery(e.target.value)}
                                                    placeholder={t('Search coupons...')}
                                                    className="w-full pr-10 pl-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-primary-500"
                                                />
                                            </div>
                                            <div className="max-h-48 overflow-y-auto space-y-2">
                                                {filteredCoupons.length === 0 ? (
                                                    <p className="text-sm text-gray-500 text-center py-4">
                                                        {availableCoupons.length === 0 
                                                            ? t('All coupons are already linked to this preset')
                                                            : t('No matching coupons found')
                                                        }
                                                    </p>
                                                ) : (
                                                    filteredCoupons.map(coupon => (
                                                        <button
                                                            key={coupon.id}
                                                            onClick={() => handleAddCoupon(coupon)}
                                                            disabled={addCouponMutation.isPending}
                                                            className="w-full flex items-center justify-between p-3 bg-white rounded-lg border border-gray-200 hover:border-primary-300 hover:bg-primary-50 transition-colors disabled:opacity-50"
                                                        >
                                                            <div className="text-right">
                                                                <p className="font-medium text-gray-900">{coupon.code}</p>
                                                                <p className="text-xs text-gray-500">
                                                                    {coupon.discount_type === 'percent' 
                                                                        ? `${coupon.discount_amount}%`
                                                                        : `${currencySymbol}${coupon.discount_amount}`
                                                                    }
                                                                    {coupon.usage_limit && ` | ${coupon.usage_count}/${coupon.usage_limit}`}
                                                                </p>
                                                            </div>
                                                            <Plus className="w-4 h-4 text-primary-600" />
                                                        </button>
                                                    ))
                                                )}
                                            </div>
                                        </div>
                                    )}
                                </>
                            )}
                        </div>
                    )}
                </CardContent>
            </Card>

            {/* ================================================================ */}
            {/* Section 5: Bundle Builder                                         */}
            {/* ================================================================ */}
            <Card>
                <CardHeader>
                    <SectionHeader
                        title={t('Bundle Builder')}
                        icon={<Package className="w-5 h-5 text-purple-600" />}
                    />
                </CardHeader>
                <CardContent className="space-y-6">
                    <label className="flex items-center gap-3 cursor-pointer">
                        <input
                            type="checkbox"
                            checked={Number(formData.bundle_enabled) === 1}
                            onChange={e => setFormData(prev => ({ ...prev, bundle_enabled: e.target.checked ? 1 : 0 }))}
                            className="w-4 h-4 text-primary-600 border-gray-300 rounded focus:ring-primary-500"
                        />
                        <span className="text-sm font-medium text-gray-700">
                            {t('Allow this bot to build product bundles')}
                        </span>
                    </label>

                    {Number(formData.bundle_enabled) === 1 && (
                        <div className="space-y-8">
                            {/* Sub-section 5A: Bundle Product Scope */}
                            <div className="border-t border-gray-100 pt-6">
                                <h4 className="text-base font-semibold text-gray-900 mb-1 flex items-center gap-2">
                                    <Layers className="w-4 h-4 text-purple-500" />
                                    {t('Bundle Products')}
                                </h4>
                                <p className="text-sm text-gray-500 mb-4">
                                    {t('Choose which products can be included in bundles. This is independent from the general product access above.')}
                                </p>
                                <ProductScopeEditor
                                    mode={formData.bundle_product_mode || 'all'}
                                    onModeChange={m => setFormData(prev => ({ ...prev, bundle_product_mode: m as 'all' | 'categories' | 'specific' }))}
                                    allowedCategories={safeParseIds(formData.bundle_allowed_categories)}
                                    onAllowedCategoriesChange={ids => setFormData(prev => ({ ...prev, bundle_allowed_categories: ids }))}
                                    excludedCategories={safeParseIds(formData.bundle_excluded_categories)}
                                    onExcludedCategoriesChange={ids => setFormData(prev => ({ ...prev, bundle_excluded_categories: ids }))}
                                    specificProductIds={safeParseIds(formData.bundle_specific_product_ids)}
                                    onSpecificProductIdsChange={ids => setFormData(prev => ({ ...prev, bundle_specific_product_ids: ids }))}
                                    excludedProductIds={safeParseIds(formData.bundle_excluded_product_ids)}
                                    onExcludedProductIdsChange={ids => setFormData(prev => ({ ...prev, bundle_excluded_product_ids: ids }))}
                                    language={currentLanguage}
                                    showPreferred
                                    preferredProductIds={safeParseIds(formData.preferred_product_ids)}
                                    onPreferredProductIdsChange={ids => setFormData(prev => ({ ...prev, preferred_product_ids: ids }))}
                                    showBundleFilters
                                    includeOnSale={Number(formData.include_on_sale)}
                                    onIncludeOnSaleChange={v => setFormData(prev => ({ ...prev, include_on_sale: v }))}
                                    includeVariable={Number(formData.include_variable)}
                                    onIncludeVariableChange={v => setFormData(prev => ({ ...prev, include_variable: v }))}
                                    maxSingleProductPercent={Number(formData.max_single_product_percent) || 50}
                                    onMaxSingleProductPercentChange={v => setFormData(prev => ({ ...prev, max_single_product_percent: v }))}
                                />
                            </div>

                            {/* Sub-section 5B: Bundle Rules */}
                            <div className="border-t border-gray-100 pt-6">
                                <h4 className="text-base font-semibold text-gray-900 mb-4">{t('Bundle Rules')}</h4>
                                <div className="grid grid-cols-1 md:grid-cols-2 gap-4 max-w-md">
                                    <div>
                                        <label className="block text-sm font-medium text-gray-700 mb-1">
                                            {t('Min products per bundle')}
                                        </label>
                                        <input
                                            type="number"
                                            min={1}
                                            max={10}
                                            value={formData.bundle_min_products || 2}
                                            onChange={e => setFormData(prev => ({ ...prev, bundle_min_products: parseInt(e.target.value) || 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>
                                        <label className="block text-sm font-medium text-gray-700 mb-1">
                                            {t('Max products per bundle')}
                                        </label>
                                        <input
                                            type="number"
                                            min={1}
                                            max={20}
                                            value={formData.bundle_max_products || 5}
                                            onChange={e => setFormData(prev => ({ ...prev, bundle_max_products: parseInt(e.target.value) || 5 }))}
                                            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>

                            {/* Sub-section 5C: Pricing & Discounts */}
                            <div className="border-t border-gray-100 pt-6">
                                <h4 className="text-base font-semibold text-gray-900 mb-4 flex items-center gap-2">
                                    <Percent className="w-4 h-4 text-amber-500" />
                                    {t('Pricing & Discounts')}
                                </h4>
                                <div className="space-y-4">
                                    <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                                        <div>
                                            <label className="block text-sm font-medium text-gray-700 mb-1">
                                                {t('Discount Type')}
                                            </label>
                                            <select
                                                value={formData.bundle_discount_type || 'percent'}
                                                onChange={e => setFormData(prev => ({ ...prev, bundle_discount_type: e.target.value as 'percent' | 'fixed' | 'tiered' }))}
                                                className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-primary-500"
                                            >
                                                <option value="percent">{t('Percentage')}</option>
                                                <option value="fixed">{t('Fixed Amount')}</option>
                                                <option value="tiered">{t('Tiered by Amount')}</option>
                                            </select>
                                        </div>
                                        {formData.bundle_discount_type !== 'tiered' && (
                                            <div>
                                                <label className="block text-sm font-medium text-gray-700 mb-1">
                                                    {t('Discount Value')}
                                                </label>
                                                <div className="relative">
                                                    <input
                                                        type="number"
                                                        min={0}
                                                        max={formData.bundle_discount_type === 'percent' ? 100 : 9999}
                                                        value={formData.bundle_discount_value || 0}
                                                        onChange={e => setFormData(prev => ({ ...prev, bundle_discount_value: parseFloat(e.target.value) || 0 }))}
                                                        className="w-full px-3 py-2 pl-8 border border-gray-300 rounded-lg focus:ring-2 focus:ring-primary-500"
                                                    />
                                                    <span className="absolute left-3 top-1/2 -translate-y-1/2 text-gray-500">
                                                        {formData.bundle_discount_type === 'percent' ? '%' : currencySymbol}
                                                    </span>
                                                </div>
                                            </div>
                                        )}
                                    </div>

                                    {/* Bundle discount method toggle */}
                                    <div className="bg-gray-50 rounded-lg p-4">
                                        <label className="block text-sm font-medium text-gray-700 mb-2">
                                            {t('Bundle discount method')}
                                        </label>
                                        <div className="flex gap-4">
                                            <label className="flex items-center gap-2 cursor-pointer">
                                                <input
                                                    type="radio"
                                                    name="bundle_discount_method"
                                                    value="coupon"
                                                    checked={formData.bundle_discount_method !== 'line_item'}
                                                    onChange={() => setFormData(prev => ({ ...prev, bundle_discount_method: 'coupon' }))}
                                                    className="text-primary-600 focus:ring-primary-500"
                                                />
                                                <span className="text-sm text-gray-700">{t('Coupon code')}</span>
                                            </label>
                                            <label className="flex items-center gap-2 cursor-pointer">
                                                <input
                                                    type="radio"
                                                    name="bundle_discount_method"
                                                    value="line_item"
                                                    checked={formData.bundle_discount_method === 'line_item'}
                                                    onChange={() => setFormData(prev => ({ ...prev, bundle_discount_method: 'line_item' }))}
                                                    className="text-primary-600 focus:ring-primary-500"
                                                />
                                                <span className="text-sm text-gray-700">{t('Line-item price adjustment')}</span>
                                            </label>
                                        </div>
                                        <p className="text-xs text-gray-500 mt-1.5">
                                            {t('Coupon: discount shown as a separate coupon line. Line-item: each product shows its discounted price directly.')}
                                        </p>
                                    </div>

                                    {/* Tiered discount editor */}
                                    {formData.bundle_discount_type === 'tiered' && (
                                        <div className="space-y-2">
                                            <label className="block text-sm font-medium text-gray-700">{t('Discount Tiers')}</label>
                                            {(formData.discount_tiers || []).map((tier, idx) => (
                                                <div key={idx} className="flex items-center gap-2 bg-gray-50 p-2 rounded">
                                                    <span className="text-gray-500 text-sm">{t('From')}</span>
                                                    <input
                                                        type="number"
                                                        value={tier.min_amount}
                                                        onChange={e => {
                                                            const newTiers = [...(formData.discount_tiers || [])]
                                                            newTiers[idx] = { ...tier, min_amount: Number(e.target.value) }
                                                            setFormData(prev => ({ ...prev, discount_tiers: newTiers }))
                                                        }}
                                                        className="w-20 px-2 py-1 border rounded text-sm"
                                                    />
                                                    <span className="text-gray-500 text-sm">{t('To')}</span>
                                                    <input
                                                        type="number"
                                                        value={tier.max_amount ?? ''}
                                                        placeholder="∞"
                                                        onChange={e => {
                                                            const newTiers = [...(formData.discount_tiers || [])]
                                                            newTiers[idx] = { ...tier, max_amount: e.target.value ? Number(e.target.value) : null }
                                                            setFormData(prev => ({ ...prev, discount_tiers: newTiers }))
                                                        }}
                                                        className="w-20 px-2 py-1 border rounded text-sm"
                                                    />
                                                    <span className="text-gray-500 text-sm">{currencySymbol} →</span>
                                                    <input
                                                        type="number"
                                                        value={tier.discount}
                                                        onChange={e => {
                                                            const newTiers = [...(formData.discount_tiers || [])]
                                                            newTiers[idx] = { ...tier, discount: Number(e.target.value) }
                                                            setFormData(prev => ({ ...prev, discount_tiers: newTiers }))
                                                        }}
                                                        className="w-16 px-2 py-1 border rounded text-sm"
                                                    />
                                                    <span className="text-gray-500 text-sm">%</span>
                                                    <button
                                                        type="button"
                                                        onClick={() => {
                                                            const newTiers = (formData.discount_tiers || []).filter((_, i) => i !== idx)
                                                            setFormData(prev => ({ ...prev, discount_tiers: newTiers }))
                                                        }}
                                                        className="p-1 text-red-500 hover:bg-red-50 rounded"
                                                    >
                                                        <Trash2 className="w-4 h-4" />
                                                    </button>
                                                </div>
                                            ))}
                                            <button
                                                type="button"
                                                onClick={() => {
                                                    const tiers = formData.discount_tiers || []
                                                    const lastTier = tiers[tiers.length - 1]
                                                    setFormData(prev => ({
                                                        ...prev,
                                                        discount_tiers: [
                                                            ...tiers,
                                                            { min_amount: lastTier ? (lastTier.max_amount || 500) : 0, max_amount: null, discount: 15 }
                                                        ]
                                                    }))
                                                }}
                                                className="flex items-center gap-1 text-sm text-primary-600 hover:text-primary-700"
                                            >
                                                <Plus className="w-4 h-4" />
                                                {t('Add Tier')}
                                            </button>
                                        </div>
                                    )}

                                    {/* Caps */}
                                    <div className="grid grid-cols-1 md:grid-cols-2 gap-4 pt-2">
                                        <div>
                                            <label className="block text-sm font-medium text-gray-700 mb-1">
                                                {t('Max discount cap')}
                                            </label>
                                            <div className="relative">
                                                <input
                                                    type="number"
                                                    min={0}
                                                    value={formData.max_discount_amount || ''}
                                                    placeholder={t('Unlimited')}
                                                    onChange={e => setFormData(prev => ({ ...prev, max_discount_amount: e.target.value ? parseFloat(e.target.value) : null }))}
                                                    className="w-full px-3 py-2 pl-8 border border-gray-300 rounded-lg focus:ring-2 focus:ring-primary-500"
                                                />
                                                <span className="absolute left-3 top-1/2 -translate-y-1/2 text-gray-500">{currencySymbol}</span>
                                            </div>
                                        </div>
                                        <div>
                                            <label className="block text-sm font-medium text-gray-700 mb-1">
                                                {t('Min order for discount')}
                                            </label>
                                            <div className="relative">
                                                <input
                                                    type="number"
                                                    min={0}
                                                    value={formData.min_order_for_discount || 0}
                                                    onChange={e => setFormData(prev => ({ ...prev, min_order_for_discount: parseFloat(e.target.value) || 0 }))}
                                                    className="w-full px-3 py-2 pl-8 border border-gray-300 rounded-lg focus:ring-2 focus:ring-primary-500"
                                                />
                                                <span className="absolute left-3 top-1/2 -translate-y-1/2 text-gray-500">{currencySymbol}</span>
                                            </div>
                                        </div>
                                    </div>

                                    {/* Display toggles */}
                                    <div className="flex flex-wrap gap-4 pt-2">
                                        <label className="flex items-center gap-2 cursor-pointer">
                                            <input
                                                type="checkbox"
                                                checked={Number(formData.show_savings) === 1}
                                                onChange={e => setFormData(prev => ({ ...prev, show_savings: e.target.checked ? 1 : 0 }))}
                                                className="w-4 h-4 text-primary-600 border-gray-300 rounded focus:ring-primary-500"
                                            />
                                            <span className="text-sm text-gray-700">{t('Show savings')}</span>
                                        </label>
                                        <label className="flex items-center gap-2 cursor-pointer">
                                            <input
                                                type="checkbox"
                                                checked={Number(formData.show_original_prices) === 1}
                                                onChange={e => setFormData(prev => ({ ...prev, show_original_prices: e.target.checked ? 1 : 0 }))}
                                                className="w-4 h-4 text-primary-600 border-gray-300 rounded focus:ring-primary-500"
                                            />
                                            <span className="text-sm text-gray-700">{t('Show original prices')}</span>
                                        </label>
                                        <label className="flex items-center gap-2 cursor-pointer">
                                            <input
                                                type="checkbox"
                                                checked={Number(formData.show_per_product_savings) === 1}
                                                onChange={e => setFormData(prev => ({ ...prev, show_per_product_savings: e.target.checked ? 1 : 0 }))}
                                                className="w-4 h-4 text-primary-600 border-gray-300 rounded focus:ring-primary-500"
                                            />
                                            <span className="text-sm text-gray-700">{t('Show per-product savings')}</span>
                                        </label>
                                        <label className="flex items-center gap-2 cursor-pointer">
                                            <input
                                                type="checkbox"
                                                checked={Number(formData.round_prices) === 1}
                                                onChange={e => setFormData(prev => ({ ...prev, round_prices: e.target.checked ? 1 : 0 }))}
                                                className="w-4 h-4 text-primary-600 border-gray-300 rounded focus:ring-primary-500"
                                            />
                                            <span className="text-sm text-gray-700">{t('Round prices')}</span>
                                        </label>
                                    </div>
                                </div>
                            </div>

                            {/* Sub-section 5D: Bundle Settings */}
                            <div className="border-t border-gray-100 pt-6">
                                <h4 className="text-base font-semibold text-gray-900 mb-1 flex items-center gap-2">
                                    <Package className="w-4 h-4 text-teal-500" />
                                    {t('Bundle Settings')}
                                </h4>
                                <p className="text-sm text-gray-500 mb-4">
                                    {t('Define the budget guidance Gemini can use while qualifying bundle requests before showing the bundle widget.')}
                                </p>

                                <div className="mt-2">
                                    <h5 className="text-sm font-semibold text-gray-800 mb-3 flex items-center gap-2">
                                        💰 {t('Budget Ranges')}
                                    </h5>

                                    <div className="space-y-2">
                                        {(formData.budget_ranges || []).map((range, idx) => {
                                            const labelKey = currentLanguage === 'he' ? 'label_he' : 'label_en'
                                            const ranges = formData.budget_ranges || []
                                            return (
                                                <div
                                                    key={idx}
                                                    className="flex items-center gap-3 p-3 bg-white rounded-lg border border-gray-200"
                                                >
                                                    <div className="flex-1">
                                                        <input
                                                            type="text"
                                                            value={range[labelKey]}
                                                            onChange={e => {
                                                                const newRanges = [...ranges]
                                                                newRanges[idx] = { ...range, [labelKey]: e.target.value }
                                                                setFormData(prev => ({ ...prev, budget_ranges: newRanges }))
                                                            }}
                                                            placeholder={t('Range Label')}
                                                            className="w-full px-3 py-1.5 border border-gray-300 rounded-lg text-sm focus:ring-2 focus:ring-primary-500"
                                                        />
                                                    </div>
                                                    <div className="w-24">
                                                        <div className="relative">
                                                            <input
                                                                type="number"
                                                                min={0}
                                                                value={range.min}
                                                                onChange={e => {
                                                                    const newRanges = [...ranges]
                                                                    newRanges[idx] = { ...range, min: Number(e.target.value) || 0 }
                                                                    setFormData(prev => ({ ...prev, budget_ranges: newRanges }))
                                                                }}
                                                                className="w-full px-2 py-1.5 border border-gray-300 rounded-lg text-sm focus:ring-2 focus:ring-primary-500"
                                                                placeholder={t('Min')}
                                                            />
                                                        </div>
                                                    </div>
                                                    <span className="text-gray-400 text-sm">–</span>
                                                    <div className="w-24">
                                                        <input
                                                            type="number"
                                                            min={0}
                                                            value={range.max}
                                                            onChange={e => {
                                                                const newRanges = [...ranges]
                                                                newRanges[idx] = { ...range, max: Number(e.target.value) || 0 }
                                                                setFormData(prev => ({ ...prev, budget_ranges: newRanges }))
                                                            }}
                                                            className="w-full px-2 py-1.5 border border-gray-300 rounded-lg text-sm focus:ring-2 focus:ring-primary-500"
                                                            placeholder={t('Max')}
                                                        />
                                                    </div>
                                                    <div className="w-16">
                                                        <input
                                                            type="text"
                                                            value={range.icon}
                                                            onChange={e => {
                                                                const newRanges = [...ranges]
                                                                newRanges[idx] = { ...range, icon: e.target.value }
                                                                setFormData(prev => ({ ...prev, budget_ranges: newRanges }))
                                                            }}
                                                            className="w-full px-2 py-1.5 border border-gray-300 rounded-lg text-sm text-center focus:ring-2 focus:ring-primary-500"
                                                            placeholder={t('Icon')}
                                                        />
                                                    </div>
                                                    <button
                                                        type="button"
                                                        onClick={() => {
                                                            const newRanges = ranges.filter((_, i) => i !== idx)
                                                            setFormData(prev => ({ ...prev, budget_ranges: newRanges }))
                                                        }}
                                                        className="p-1 text-red-400 hover:text-red-600 hover:bg-red-50 rounded transition-colors"
                                                    >
                                                        <Trash2 className="w-4 h-4" />
                                                    </button>
                                                </div>
                                            )
                                        })}
                                    </div>

                                    {(formData.budget_ranges || []).length > 0 && (
                                        <div className="flex items-center gap-3 px-3 mt-1 text-xs text-gray-400">
                                            <span className="flex-1">{t('Range Label')}</span>
                                            <span className="w-24 text-center">{t('Min')}</span>
                                            <span className="w-3" />
                                            <span className="w-24 text-center">{t('Max')}</span>
                                            <span className="w-16 text-center">{t('Icon')}</span>
                                            <span className="w-6" />
                                        </div>
                                    )}

                                    <button
                                        type="button"
                                        onClick={() => {
                                            const ranges = formData.budget_ranges || []
                                            const lastRange = ranges[ranges.length - 1]
                                            const newRange: BudgetRange = {
                                                label_he: '',
                                                label_en: '',
                                                min: lastRange ? lastRange.max : 0,
                                                max: lastRange ? lastRange.max + 200 : 100,
                                                icon: '💰',
                                            }
                                            setFormData(prev => ({ ...prev, budget_ranges: [...ranges, newRange] }))
                                        }}
                                        className="mt-3 flex items-center gap-2 px-4 py-2 border border-dashed border-gray-300 rounded-lg text-gray-600 hover:bg-gray-50 hover:border-primary-300 transition-colors w-full justify-center text-sm"
                                    >
                                        <Plus className="w-4 h-4" />
                                        {t('Add Range')}
                                    </button>
                                </div>
                            </div>
                        </div>
                    )}
                </CardContent>
            </Card>

            {/* ================================================================ */}
            {/* Section 6: Messages                                              */}
            {/* ================================================================ */}
            <Card>
                <CardHeader>
                    <SectionHeader
                        title={t('Messages')}
                        subtitle={t('Customize the messages shown during the bundle flow.')}
                        icon={<MessageCircle className="w-5 h-5 text-indigo-600" />}
                    />
                </CardHeader>
                <CardContent className="space-y-4">
                    <div>
                        <label className="block text-sm font-medium text-gray-700 mb-1">
                            {t('Intro Message')}
                        </label>
                        <textarea
                            value={formData.intro_message || ''}
                            onChange={e => setFormData(prev => ({ ...prev, intro_message: e.target.value }))}
                            rows={2}
                            className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-primary-500"
                            placeholder={t('Let me build the perfect bundle for you! 🎁')}
                        />
                        <p className="text-xs text-gray-400 mt-1">{t('Shown when the bundle flow starts.')}</p>
                    </div>
                    <div>
                        <label className="block text-sm font-medium text-gray-700 mb-1">
                            {t('Loading Message')}
                        </label>
                        <textarea
                            value={formData.loading_message || ''}
                            onChange={e => setFormData(prev => ({ ...prev, loading_message: e.target.value }))}
                            rows={2}
                            className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-primary-500"
                            placeholder={t('Looking for the perfect products for you... ⏳')}
                        />
                        <p className="text-xs text-gray-400 mt-1">{t('Shown while products are loading.')}</p>
                    </div>
                    <div>
                        <label className="block text-sm font-medium text-gray-700 mb-1">
                            {t('Success Message')}
                        </label>
                        <textarea
                            value={formData.success_message || ''}
                            onChange={e => setFormData(prev => ({ ...prev, success_message: e.target.value }))}
                            rows={2}
                            className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-primary-500"
                            placeholder={t('Here is the bundle I prepared for you! 🎉')}
                        />
                        <p className="text-xs text-gray-400 mt-1">{t('Shown when a bundle is found.')}</p>
                    </div>
                    <div>
                        <label className="block text-sm font-medium text-gray-700 mb-1">
                            {t('Empty Message')}
                        </label>
                        <textarea
                            value={formData.empty_message || ''}
                            onChange={e => setFormData(prev => ({ ...prev, empty_message: e.target.value }))}
                            rows={2}
                            className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-primary-500"
                            placeholder={t('No matching products were found. Try something else?')}
                        />
                        <p className="text-xs text-gray-400 mt-1">{t('Shown when no matching products are found.')}</p>
                    </div>
                    <div>
                        <label className="block text-sm font-medium text-gray-700 mb-1">
                            {t('Error Message')}
                        </label>
                        <textarea
                            value={formData.error_message || ''}
                            onChange={e => setFormData(prev => ({ ...prev, error_message: e.target.value }))}
                            rows={2}
                            className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-primary-500"
                            placeholder={t('Something went wrong. Please try again.')}
                        />
                        <p className="text-xs text-gray-400 mt-1">{t('Shown when an error occurs.')}</p>
                    </div>

                    <div className="pt-4 border-t border-gray-100 flex flex-wrap gap-4">
                        <label className="flex items-center gap-2 cursor-pointer">
                            <input
                                type="checkbox"
                                checked={Number(formData.allow_customization) === 1}
                                onChange={e => setFormData(prev => ({ ...prev, allow_customization: e.target.checked ? 1 : 0 }))}
                                className="w-4 h-4 text-primary-600 border-gray-300 rounded focus:ring-primary-500"
                            />
                            <span className="text-sm text-gray-700">{t('Allow customer to edit bundle')}</span>
                        </label>
                        <label className="flex items-center gap-2 cursor-pointer">
                            <input
                                type="checkbox"
                                checked={Number(formData.cart_redirect) === 1}
                                onChange={e => setFormData(prev => ({ ...prev, cart_redirect: e.target.checked ? 1 : 0 }))}
                                className="w-4 h-4 text-primary-600 border-gray-300 rounded focus:ring-primary-500"
                            />
                            <span className="text-sm text-gray-700">{t('Redirect to cart after adding bundle')}</span>
                        </label>
                    </div>
                    <div className="rounded-lg border border-gray-200 bg-gray-50 px-4 py-3">
                        <label className="flex items-start gap-3 cursor-pointer">
                            <input
                                type="checkbox"
                                checked={Number(formData.show_cart_button) === 1}
                                onChange={e => setFormData(prev => ({ ...prev, show_cart_button: e.target.checked ? 1 : 0 }))}
                                className="mt-0.5 h-4 w-4 text-primary-600 border-gray-300 rounded focus:ring-primary-500"
                            />
                            <span className="block">
                                <span className="block text-sm font-medium text-gray-900">{t('Show cart button in chat')}</span>
                                <span className="mt-1 block text-xs text-gray-500">
                                    {t('Display a shopping cart button in the chat header. Visitors can view their cart, update quantities, and proceed to checkout without leaving the chat.')}
                                </span>
                            </span>
                        </label>
                    </div>
                </CardContent>
            </Card>

            {/* Save Button (Bottom) */}
            <div className="flex justify-end">
                <button
                    onClick={handleSave}
                    disabled={saveMutation.isPending}
                    className={`flex items-center gap-2 px-6 py-2.5 rounded-lg transition-all disabled:opacity-50 ${
                        hasUnsavedChanges
                            ? 'bg-amber-500 hover:bg-amber-600 animate-pulse'
                            : 'bg-primary-600 hover:bg-primary-700'
                    } text-white`}
                >
                    {saveMutation.isPending ? (
                        <div className="w-4 h-4 border-2 border-white border-t-transparent rounded-full animate-spin" />
                    ) : (
                        <Save className="w-4 h-4" />
                    )}
                    {saveMutation.isPending ? t('Saving...') : hasUnsavedChanges ? t('Save Changes') : t('Save Preset')}
                </button>
            </div>
        </div>
    )
}
