import { FiArrowLeft, FiMonitor, FiChevronDown, FiChevronRight, FiSmartphone, FiBox, FiMessageSquare, FiSearch, FiEdit2, FiTrash2, FiPlus, FiX } from "react-icons/fi";
import styles from "../../chatbot/components/ChatbotSettings.module.css";
import React, { useState, useEffect } from "react";
import { useCreateProactiveChat, useUpdateProactiveChat } from "app/utils/api";
import { useToast } from "app/components/providers/use-toast";
import { countries } from "../../../countries";

interface ProactiveChatCreateProps {
    initialData?: any;
    onBack: () => void;
}

const defaultData = {
    status: { is_active: true, updated_at: "", priority: 1 },
    general: { name: "Welcome Visitor" },
    trigger: { type: "scrolled", options: { viewed_page_for_seconds: 5, scroll_percentage_value: 10 } },
    conditions: {
        audience: "All",
        audience_sub: "All customers",
        display_time: "All time",
        devices: "All",
        display_duration: { mode: "custom", value_seconds: 10 },
        geography: { mode: "all_countries", country_codes: [] }
    },
    message: {
        active_type: "text",
        types: {
            text: {
                content_mode: "quick_question",
                quick_questions: ["Is this item still available?", "How fast is shipping?", "Which size should I choose?"],
                custom_message: "Hi {{customer_name}} 👋\nHow can we help you?"
            },
            product_recommendation: {
                message_body: "You might like this product!",
                recommendation_type: "best",
                search_products_query: "",
                selected_product_ids: []
            },
            discount: {
                message_body: "Hey there! 🎉\nWe've got an exclusive Black Friday coupon just for you. Click to get your discount! Limited time only!",
                discount_code: "",
                usage_instruction: "This coupon is valid for summer clothing, with all items eligible for a 20% discount"
            }
        }
    },
    appearance: {
        colors: {
            background_color: "#ffffff",
            text_color: "#1a1a1a",
            button_background_color: "#7c3aed",
            button_label_color: "#ffffff"
        }
    }
};



export function ProactiveChatCreate({ initialData, onBack }: ProactiveChatCreateProps) {
    const [formData, setFormData] = useState<any>(defaultData);
    const [activeCategory, setActiveCategory] = useState("Conditions");
    const [isSaving, setIsSaving] = useState(false);
    const [countryModalOpen, setCountryModalOpen] = useState(false);
    const [desktopPreviewOpen, setDesktopPreviewOpen] = useState(false);
    const [quickQuestionModalOpen, setQuickQuestionModalOpen] = useState(false);
    const [editingQuestionIndex, setEditingQuestionIndex] = useState(-1);
    const [quickQuestionDraft, setQuickQuestionDraft] = useState("");
    const [countrySearch, setCountrySearch] = useState("");
    const [pendingSelectedCountries, setPendingSelectedCountries] = useState<string[]>([]);
    const createMutation = useCreateProactiveChat();
    const updateMutation = useUpdateProactiveChat();
    const { showSuccess, showError } = useToast();

    useEffect(() => {
        if (initialData) {
            setFormData(JSON.parse(JSON.stringify({ ...defaultData, ...initialData })));
        } else {
            setFormData(JSON.parse(JSON.stringify(defaultData)));
        }
    }, [initialData]);

    const updateNested = (path: string[], value: any) => {
        setFormData((prev: any) => {
            const next = JSON.parse(JSON.stringify(prev));
            let curr = next;
            for (let i = 0; i < path.length - 1; i++) {
                if (!curr[path[i]]) curr[path[i]] = {};
                curr = curr[path[i]];
            }
            curr[path[path.length - 1]] = value;
            return next;
        });
    };

    const toggleCategory = (cat: string) => {
        setActiveCategory(activeCategory === cat ? "" : cat);
    };
    console.log(initialData, "test")
    const handleSave = async () => {
        setIsSaving(true);
        try {
            if (initialData?._id) {
                await updateMutation.mutateAsync({ ...formData });
                showSuccess("Proactive chat updated successfully");
            } else {
                await createMutation.mutateAsync(formData);
                showSuccess("Proactive chat created successfully");
            }
            onBack();
        } catch (err: any) {
            const serverMsg = err.response?.data?.message || err.message || "";
            if (serverMsg.includes("E11000") || serverMsg.includes("duplicate key error")) {
                showError("A Proactive Chat already exists for this store. Please edit the existing entry instead.");
            } else {
                showError(serverMsg || "Failed to save proactive chat.");
            }
        } finally {
            setIsSaving(false);
        }
    };

    const toggleCountry = (code: string) => {
        const codes = formData.conditions.geography.country_codes || [];
        if (codes.includes(code)) {
            updateNested(["conditions", "geography", "country_codes"], codes.filter((c: string) => c !== code));
        } else {
            updateNested(["conditions", "geography", "country_codes"], [...codes, code]);
        }
    };

    const togglePendingCountry = (code: string) => {
        if (pendingSelectedCountries.includes(code)) {
            setPendingSelectedCountries(pendingSelectedCountries.filter(c => c !== code));
        } else {
            setPendingSelectedCountries([...pendingSelectedCountries, code]);
        }
    };

    const openCountryModal = () => {
        setPendingSelectedCountries(formData.conditions.geography.country_codes || []);
        setCountrySearch("");
        setCountryModalOpen(true);
    };

    const RichTextToolbar = () => (
        <div className={styles.richTextToolbar} style={{ borderBottom: '1px solid #e5e7eb', padding: '8px 12px', display: 'flex', gap: '12px', alignItems: 'center' }}>
            <div style={{ display: 'flex', alignItems: 'center', gap: '4px', cursor: 'pointer', fontSize: '13px', background: '#f3f4f6', padding: '2px 8px', borderRadius: '4px' }}>
                Paragraph <FiChevronDown size={12} />
            </div>
            <span style={{ fontWeight: 800, fontSize: '13px' }}>A</span>
            <span style={{ textDecoration: 'line-through', fontSize: '13px' }}>Ø</span>
            <span style={{ width: '1px', height: '12px', background: '#e5e7eb' }}></span>
            <span style={{ fontWeight: 800, fontSize: '13px' }}>B</span>
            <span style={{ fontStyle: 'italic', fontSize: '13px' }}>I</span>
            <span style={{ textDecoration: 'underline', fontSize: '13px' }}>U</span>
            <span style={{ width: '1px', height: '12px', background: '#e5e7eb' }}></span>
            <div style={{ display: 'flex', flexDirection: 'column', gap: '2px' }}>
                <span style={{ height: '2px', width: '12px', background: '#4b5563' }}></span>
                <span style={{ height: '2px', width: '12px', background: '#4b5563' }}></span>
                <span style={{ height: '2px', width: '12px', background: '#4b5563' }}></span>
            </div>
            <div style={{ display: 'flex', gap: '2px' }}>
                <span style={{ fontSize: '10px', fontWeight: 800 }}>1.</span>
                <div style={{ display: 'flex', flexDirection: 'column', gap: '2px', marginTop: '2px' }}>
                    <span style={{ height: '2px', width: '8px', background: '#4b5563' }}></span>
                    <span style={{ height: '2px', width: '8px', background: '#4b5563' }}></span>
                </div>
            </div>
            <span style={{ fontWeight: 800, fontSize: '12px' }}>{'<>'}</span>
        </div>
    );

    const renderColorOptions = (key: string, label: string, options: string[], hasCustom: boolean = false) => {
        const val = formData.appearance.colors[key] || '#ffffff';
        return (
            <div className={styles.labelGroup} style={{ marginBottom: '16px' }}>
                <label className={styles.settingsInputLabel} style={{ marginBottom: '8px', display: 'block' }}>{label}</label>
                <div style={{ display: 'flex', gap: '8px', flexWrap: 'wrap', alignItems: 'center' }}>
                    {options.map((opt, i) => (
                        <div
                            key={i}
                            onClick={() => updateNested(["appearance", "colors", key], opt)}
                            style={{
                                width: '28px', height: '28px', borderRadius: '50%', cursor: 'pointer',
                                background: opt,
                                border: val === opt ? '2px solid #3b82f6' : '1px solid #e5e7eb',
                                outline: val === opt ? '2px solid white' : 'none',
                                outlineOffset: '-4px',
                                boxShadow: val === opt ? '0 0 0 2px #3b82f6' : 'none',
                                display: 'flex', alignItems: 'center', justifyContent: 'center'
                            }}
                        />
                    ))}
                    {hasCustom && (
                        <div style={{ position: 'relative', width: '28px', height: '28px', borderRadius: '50%', overflow: 'hidden', cursor: 'pointer', border: !options.includes(val) ? '2px solid #3b82f6' : '1px solid #e5e7eb', boxShadow: !options.includes(val) ? '0 0 0 2px #3b82f6' : 'none', outline: !options.includes(val) ? '2px solid white' : 'none', outlineOffset: '-4px', display: 'flex', alignItems: 'center', justifyContent: 'center', background: !options.includes(val) ? val : 'linear-gradient(45deg, #7c3aed, #ec4899)' }}>
                            <FiEdit2 size={12} color="white" style={{ position: 'absolute', zIndex: 2, pointerEvents: 'none' }} />
                            <input
                                type="color"
                                value={!options.includes(val) ? val : '#710028'}
                                onChange={(e) => updateNested(["appearance", "colors", key], e.target.value)}
                                style={{ position: 'absolute', opacity: 0, width: '200%', height: '200%', top: '-50%', left: '-50%', cursor: 'pointer' }}
                            />
                        </div>
                    )}
                </div>
            </div>
        );
    }

    const renderPreviewContent = () => {
        const msgType = formData.message.active_type;
        const msgTypes = formData.message.types;

        if (msgType === "text") {
            const isQuick = msgTypes.text.content_mode === "quick_question";
            if (isQuick) {
                return (
                    <div style={{ display: 'flex', flexDirection: 'column', gap: '8px' }}>
                        {msgTypes.text.quick_questions.map((q: string, i: number) => (
                            <button key={i} style={{
                                background: 'transparent', border: `1px solid ${formData.appearance.colors.button_background_color}`,
                                color: formData.appearance.colors.button_background_color, borderRadius: '16px', padding: '6px 12px',
                                fontSize: '12px', textAlign: 'left', cursor: 'pointer'
                            }}>
                                {q}
                            </button>
                        ))}
                    </div>
                );
            }
            return (
                <div style={{ fontSize: '13px', whiteSpace: 'pre-wrap', color: formData.appearance.colors.text_color }}>
                    {msgTypes.text.custom_message}
                </div>
            );
        } else if (msgType === "product_recommendation") {
            return (
                <div style={{ fontSize: '13px' }}>
                    <p style={{ margin: '0 0 12px', color: formData.appearance.colors.text_color }}>{msgTypes.product_recommendation.message_body}</p>
                    <div style={{ display: 'flex', gap: '8px', overflowX: 'auto', paddingBottom: '8px' }}>
                        {[1, 2].map(i => (
                            <div key={i} style={{ width: '100px', flexShrink: 0, border: '1px solid #e5e7eb', borderRadius: '8px', overflow: 'hidden', background: '#fff' }}>
                                <div style={{ height: '80px', background: '#f3f4f6' }}></div>
                                <div style={{ padding: '8px' }}>
                                    <div style={{ fontSize: '10px', fontWeight: 600, color: '#111' }}>Product {i}</div>
                                    <div style={{ fontSize: '10px', color: '#6b7280' }}>$20.00</div>
                                </div>
                            </div>
                        ))}
                    </div>
                </div>
            );
        } else if (msgType === "discount") {
            return (
                <div style={{ fontSize: '13px' }}>
                    <p style={{ margin: '0 0 12px', whiteSpace: 'pre-wrap', color: formData.appearance.colors.text_color }}>{msgTypes.discount.message_body}</p>
                    <div style={{ background: '#f9fafb', border: '1px dashed #d1d5db', padding: '12px', borderRadius: '8px', textAlign: 'center', marginBottom: '8px' }}>
                        <strong style={{ fontSize: '14px', color: '#111' }}>{msgTypes.discount.discount_code || 'SUMMER20'}</strong>
                    </div>
                    <p style={{ margin: 0, fontSize: '11px', color: formData.appearance.colors.text_color, opacity: 0.8 }}>{msgTypes.discount.usage_instruction}</p>
                </div>
            );
        }
    };

    const selectedCountriesList = countries.filter(c => (formData.conditions.geography.country_codes || []).includes(c.code));

    return (
        <div className={styles.trainingDataContainer} style={{ background: '#f9fafb', padding: '20px', minHeight: '100vh', position: 'relative' }}>
            <div className={styles.faqHeader} style={{ gap: '16px', display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
                <div style={{ display: 'flex', alignItems: 'center', gap: '16px' }}>
                    <button onClick={onBack} style={{ background: 'none', border: 'none', cursor: 'pointer', display: 'flex', alignItems: 'center', fontSize: '20px', padding: 0 }}>
                        <FiArrowLeft />
                    </button>
                    <div>
                        <h1 className={styles.faqTitle} style={{ fontSize: '20px', margin: 0 }}>{initialData ? "Edit" : "New"} proactive chat</h1>
                    </div>
                </div>
                <button
                    onClick={handleSave}
                    disabled={isSaving}
                    style={{ background: '#222', color: 'white', border: 'none', borderRadius: '6px', padding: '8px 16px', fontSize: '13px', fontWeight: 500, cursor: 'pointer' }}
                >
                    {isSaving ? "Saving..." : "Save"}
                </button>
            </div>

            <div className={styles.faqPageLayout}>
                <div className={styles.settingsPanel}>
                    {/* Activation Card */}
                    <div className={styles.appearanceCard} style={{ padding: '16px 24px', marginBottom: '16px' }}>
                        <div className={styles.toggleRow}>
                            <span style={{ fontSize: '14px', fontWeight: 600 }}>Activate proactive chat</span>
                            <label className={styles.switch}>
                                <input type="checkbox" checked={formData.status.is_active} onChange={e => updateNested(["status", "is_active"], e.target.checked)} />
                                <span className={styles.slider}></span>
                            </label>
                        </div>
                    </div>

                    {/* General Section */}
                    <div className={styles.collapsibleCard}>
                        <div className={styles.collapsibleHeader} onClick={() => toggleCategory("General")}>
                            <span>General</span>
                            {activeCategory === "General" ? <FiChevronDown /> : <FiChevronRight />}
                        </div>
                        {activeCategory === "General" && (
                            <div className={styles.collapsibleContent}>
                                <div className={styles.labelGroup}>
                                    <label className={styles.settingsInputLabel}>Name</label>
                                    <p style={{ fontSize: '12px', color: '#6b7280', margin: '4px 0 8px' }}>Enter a name to identify this proactive chat (visible only to you)</p>
                                    <input type="text" className={styles.chatInput} style={{ textAlign: 'left', width: '100%', maxWidth: '100%' }} value={formData.general.name} onChange={e => updateNested(["general", "name"], e.target.value)} />
                                </div>
                            </div>
                        )}
                    </div>

                    {/* Trigger Section */}
                    <div className={styles.collapsibleCard}>
                        <div className={styles.collapsibleHeader} onClick={() => toggleCategory("Trigger")}>
                            <span>Trigger</span>
                            {activeCategory === "Trigger" ? <FiChevronDown /> : <FiChevronRight />}
                        </div>
                        {activeCategory === "Trigger" && (
                            <div className={styles.collapsibleContent}>
                                <div className={styles.labelGroup}>
                                    <label className={styles.settingsInputLabel} style={{ marginBottom: '8px', display: 'block' }}>Display time</label>
                                    <div style={{ marginTop: '12px' }}>
                                        <div className={`${styles.triggerOption} ${formData.trigger.type === 'viewed_page' ? styles.triggerOptionActive : ''}`} onClick={() => updateNested(["trigger", "type"], 'viewed_page')}>
                                            <div className={`${styles.radioCircle} ${formData.trigger.type === 'viewed_page' ? styles.radioCircleActive : ''}`}>
                                                {formData.trigger.type === 'viewed_page' && <div className={styles.radioInner}></div>}
                                            </div>
                                            <div style={{ flex: 1, display: 'flex', alignItems: 'center', flexWrap: 'wrap', gap: '8px' }}>
                                                <span style={{ fontSize: '14px' }}>Visitor has viewed the page for</span>
                                                {formData.trigger.type === 'viewed_page' && (
                                                    <div className={styles.percentageInputGroup} style={{ margin: 0 }}>
                                                        <input type="number" className={styles.percentageInput} value={formData.trigger.options.viewed_page_for_seconds || ''} onChange={e => updateNested(["trigger", "options", "viewed_page_for_seconds"], parseInt(e.target.value) || 0)} />
                                                        <span className={styles.percentageLabel}>seconds</span>
                                                    </div>
                                                )}
                                            </div>
                                        </div>
                                        <div className={`${styles.triggerOption} ${formData.trigger.type === 'scrolled' ? styles.triggerOptionActive : ''}`} onClick={() => updateNested(["trigger", "type"], 'scrolled')}>
                                            <div className={`${styles.radioCircle} ${formData.trigger.type === 'scrolled' ? styles.radioCircleActive : ''}`}>
                                                {formData.trigger.type === 'scrolled' && <div className={styles.radioInner}></div>}
                                            </div>
                                            <div style={{ flex: 1, display: 'flex', alignItems: 'center', flexWrap: 'wrap', gap: '8px' }}>
                                                <span style={{ fontSize: '14px' }}>Visitor has scrolled to a percentage of the page</span>
                                                {formData.trigger.type === 'scrolled' && (
                                                    <div className={styles.percentageInputGroup} style={{ margin: 0 }}>
                                                        <input type="number" className={styles.percentageInput} value={formData.trigger.options.scroll_percentage_value || ''} onChange={e => updateNested(["trigger", "options", "scroll_percentage_value"], parseInt(e.target.value) || 0)} />
                                                        <span className={styles.percentageLabel}>percentage</span>
                                                    </div>
                                                )}
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        )}
                    </div>

                    {/* Conditions Section */}
                    <div className={styles.collapsibleCard}>
                        <div className={styles.collapsibleHeader} onClick={() => toggleCategory("Conditions")}>
                            <span>Conditions</span>
                            {activeCategory === "Conditions" ? <FiChevronDown /> : <FiChevronRight />}
                        </div>
                        {activeCategory === "Conditions" && (
                            <div className={styles.collapsibleContent}>
                                <div className={styles.labelGroup} style={{ marginBottom: '20px' }}>
                                    <label className={styles.settingsInputLabel} style={{ marginBottom: '8px', display: 'block' }}>Audience</label>
                                    <select className={styles.chatInput} style={{ textAlign: 'left', width: '100%', maxWidth: '100%', marginTop: '8px' }} value={formData.conditions.audience} onChange={e => updateNested(["conditions", "audience"], e.target.value)}>
                                        <option value="All">All</option>
                                        <option value="Only visitors">Only visitors</option>
                                        <option value="Only customers">Only customers</option>
                                    </select>
                                </div>
                                <div className={styles.labelGroup} style={{ marginBottom: '20px' }}>
                                    <label className={styles.settingsInputLabel} style={{ marginBottom: '8px', display: 'block' }}>Display time</label>
                                    <div style={{ marginTop: '12px', display: 'flex', flexDirection: 'column', gap: '8px' }}>
                                        <div className={styles.triggerOption} style={{ padding: '8px 12px', marginBottom: 0, border: 'none' }} onClick={() => updateNested(["conditions", "display_time"], "All time")}>
                                            <div className={`${styles.radioCircle} ${formData.conditions.display_time === 'All time' ? styles.radioCircleActive : ''}`}>{formData.conditions.display_time === 'All time' && <div className={styles.radioInner}></div>}</div>
                                            <span style={{ fontSize: '14px' }}>All time</span>
                                        </div>
                                        <div className={styles.triggerOption} style={{ padding: '8px 12px', marginBottom: 0, border: 'none' }} onClick={() => updateNested(["conditions", "display_time"], "During business hour")}>
                                            <div className={`${styles.radioCircle} ${formData.conditions.display_time === 'During business hour' ? styles.radioCircleActive : ''}`}>{formData.conditions.display_time === 'During business hour' && <div className={styles.radioInner}></div>}</div>
                                            <span style={{ fontSize: '14px' }}>During business hour (including the time when agent is online if any)</span>
                                        </div>
                                    </div>
                                </div>
                                <div className={styles.labelGroup} style={{ marginBottom: '20px' }}>
                                    <label className={styles.settingsInputLabel} style={{ marginBottom: '8px', display: 'block' }}>Device</label>
                                    <div style={{ marginTop: '12px', display: 'flex', flexDirection: 'column', gap: '8px' }}>
                                        <div className={styles.triggerOption} style={{ padding: '8px 12px', marginBottom: 0, border: 'none' }} onClick={() => updateNested(["conditions", "devices"], "All")}>
                                            <div className={`${styles.radioCircle} ${formData.conditions.devices === 'All' ? styles.radioCircleActive : ''}`}>{formData.conditions.devices === 'All' && <div className={styles.radioInner}></div>}</div>
                                            <span style={{ fontSize: '14px' }}>All</span>
                                        </div>
                                        <div className={styles.triggerOption} style={{ padding: '8px 12px', marginBottom: 0, border: 'none' }} onClick={() => updateNested(["conditions", "devices"], "Desktop only")}>
                                            <div className={`${styles.radioCircle} ${formData.conditions.devices === 'Desktop only' ? styles.radioCircleActive : ''}`}>{formData.conditions.devices === 'Desktop only' && <div className={styles.radioInner}></div>}</div>
                                            <span style={{ fontSize: '14px' }}>Desktop only</span>
                                        </div>
                                        <div className={styles.triggerOption} style={{ padding: '8px 12px', marginBottom: 0, border: 'none' }} onClick={() => updateNested(["conditions", "devices"], "Mobile only")}>
                                            <div className={`${styles.radioCircle} ${formData.conditions.devices === 'Mobile only' ? styles.radioCircleActive : ''}`}>{formData.conditions.devices === 'Mobile only' && <div className={styles.radioInner}></div>}</div>
                                            <span style={{ fontSize: '14px' }}>Mobile only</span>
                                        </div>
                                    </div>
                                </div>
                                <div className={styles.labelGroup} style={{ marginBottom: '20px' }}>
                                    <label className={styles.settingsInputLabel} style={{ marginBottom: '8px', display: 'block' }}>Display duration</label>
                                    <div style={{ marginTop: '12px' }}>
                                        <div className={styles.triggerOption} style={{ padding: '8px 12px', marginBottom: '8px', border: 'none' }} onClick={() => updateNested(["conditions", "display_duration", "mode"], "always")}>
                                            <div className={`${styles.radioCircle} ${formData.conditions.display_duration.mode === 'always' ? styles.radioCircleActive : ''}`}>{formData.conditions.display_duration.mode === 'always' && <div className={styles.radioInner}></div>}</div>
                                            <span style={{ fontSize: '14px' }}>Always</span>
                                        </div>
                                        <div className={styles.triggerOption} style={{ padding: '8px 12px', border: 'none' }} onClick={() => updateNested(["conditions", "display_duration", "mode"], "custom")}>
                                            <div className={`${styles.radioCircle} ${formData.conditions.display_duration.mode === 'custom' ? styles.radioCircleActive : ''}`}>{formData.conditions.display_duration.mode === 'custom' && <div className={styles.radioInner}></div>}</div>
                                            <div style={{ flex: 1, display: 'flex', alignItems: 'center', gap: '8px' }}>
                                                <span style={{ fontSize: '14px' }}>Custom</span>
                                            </div>
                                        </div>
                                        {formData.conditions.display_duration.mode === 'custom' && (
                                            <div style={{ paddingLeft: '32px', marginTop: '8px' }}>
                                                <div className={styles.percentageInputGroup} style={{ margin: 0, width: '180px' }}>
                                                    <input type="number" className={styles.percentageInput} value={formData.conditions.display_duration.value_seconds || ''} onChange={e => updateNested(["conditions", "display_duration", "value_seconds"], parseInt(e.target.value) || 0)} />
                                                    <span className={styles.percentageLabel}>seconds</span>
                                                </div>
                                            </div>
                                        )}
                                    </div>
                                </div>
                                <div className={styles.labelGroup}>
                                    <label className={styles.settingsInputLabel} style={{ marginBottom: '8px', display: 'block' }}>Countries</label>
                                    <div style={{ marginTop: '12px' }}>
                                        <div className={styles.triggerOption} style={{ padding: '8px 12px', marginBottom: '8px', border: 'none' }} onClick={() => updateNested(["conditions", "geography", "mode"], "all_countries")}>
                                            <div className={`${styles.radioCircle} ${formData.conditions.geography.mode === 'all_countries' ? styles.radioCircleActive : ''}`}>{formData.conditions.geography.mode === 'all_countries' && <div className={styles.radioInner}></div>}</div>
                                            <span style={{ fontSize: '14px' }}>All countries</span>
                                        </div>
                                        <div className={styles.triggerOption} style={{ padding: '8px 12px', border: 'none' }} onClick={() => updateNested(["conditions", "geography", "mode"], "selected_countries")}>
                                            <div className={`${styles.radioCircle} ${formData.conditions.geography.mode === 'selected_countries' ? styles.radioCircleActive : ''}`}>{formData.conditions.geography.mode === 'selected_countries' && <div className={styles.radioInner}></div>}</div>
                                            <div style={{ flex: 1 }}>
                                                <span style={{ fontSize: '14px' }}>Selected countries</span>
                                            </div>
                                        </div>
                                        {formData.conditions.geography.mode === 'selected_countries' && (
                                            <div style={{ paddingLeft: '32px', marginTop: '8px' }}>
                                                <div style={{ display: 'flex', gap: '8px' }}>
                                                    <div style={{ position: 'relative', flex: 1 }}>
                                                        <FiSearch style={{ position: 'absolute', left: '12px', top: '10px', color: '#9ca3af' }} />
                                                        <input readOnly onClick={openCountryModal} type="text" className={styles.chatInput} placeholder="Search countries" style={{ paddingLeft: '40px', textAlign: 'left', width: '100%', height: '36px', cursor: 'pointer' }} />
                                                    </div>
                                                    <button onClick={openCountryModal} style={{ border: '1px solid #e5e7eb', background: '#fff', borderRadius: '4px', padding: '0 16px', fontSize: '13px', fontWeight: 600, cursor: 'pointer' }}>Browse</button>
                                                </div>
                                                {selectedCountriesList.length > 0 && (
                                                    <div style={{ marginTop: '12px', border: '1px solid #e5e7eb', borderRadius: '8px', background: '#fff' }}>
                                                        <div style={{ padding: '12px', borderBottom: '1px solid #e5e7eb', fontSize: '13px', color: '#4b5563', display: 'flex', justifyContent: 'space-between' }}>
                                                            <span>{selectedCountriesList.length} selected <FiChevronDown /></span>
                                                        </div>
                                                        <div style={{ maxHeight: '200px', overflowY: 'auto' }}>
                                                            {selectedCountriesList.map(c => (
                                                                <div key={c.code} style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', padding: '12px', borderBottom: '1px solid #f3f4f6', fontSize: '14px' }}>
                                                                    <div style={{ display: 'flex', alignItems: 'center', gap: '12px' }}>
                                                                        <span>{c.flag}</span>
                                                                        <span>{c.name}</span>
                                                                    </div>
                                                                    <FiX style={{ cursor: 'pointer', color: '#9ca3af' }} onClick={() => toggleCountry(c.code)} />
                                                                </div>
                                                            ))}
                                                        </div>
                                                    </div>
                                                )}
                                            </div>
                                        )}
                                    </div>
                                </div>
                            </div>
                        )}
                    </div>

                    {/* Message Section */}
                    <div className={styles.collapsibleCard}>
                        <div className={styles.collapsibleHeader} onClick={() => toggleCategory("Message")}>
                            <span>Message</span>
                            {activeCategory === "Message" ? <FiChevronDown /> : <FiChevronRight />}
                        </div>
                        {activeCategory === "Message" && (
                            <div className={styles.collapsibleContent}>
                                <div className={styles.colorTabs} style={{ borderBottom: '1px solid #f3f4f6', marginBottom: '20px', padding: 0 }}>
                                    {[
                                        { id: 'text', label: 'Text' },
                                        { id: 'product_recommendation', label: 'Product Recommendation' },
                                        { id: 'discount', label: 'Discount' }
                                    ].map((tab, idx) => (
                                        <div
                                            key={tab.id}
                                            className={`${styles.colorTab} ${formData.message.active_type === tab.id ? styles.colorTabActive : ""}`}
                                            onClick={() => updateNested(["message", "active_type"], tab.id)}
                                            style={{
                                                padding: '8px 16px',
                                                border: '1px solid #e5e7eb',
                                                background: formData.message.active_type === tab.id ? '#f3f4f6' : '#fff',
                                                borderRight: idx === 2 ? '1px solid #e5e7eb' : 'none',
                                                borderRadius: idx === 0 ? '4px 0 0 4px' : idx === 2 ? '0 4px 4px 0' : '0',
                                                cursor: 'pointer'
                                            }}
                                        >
                                            {formData.message.active_type === tab.id && <FiBox size={12} style={{ marginRight: '6px', opacity: 0.5 }} />}
                                            {tab.label}
                                        </div>
                                    ))}
                                </div>

                                {formData.message.active_type === "text" && (
                                    <div className={styles.labelGroup}>
                                        <label className={styles.settingsInputLabel} style={{ marginBottom: '8px', display: 'block' }}>Content</label>
                                        <div style={{ marginTop: '12px' }}>
                                            <div className={styles.triggerOption} style={{ padding: '8px 0', marginBottom: 0, border: 'none' }} onClick={() => updateNested(["message", "types", "text", "content_mode"], 'quick_question')}>
                                                <div className={`${styles.radioCircle} ${formData.message.types.text.content_mode === 'quick_question' ? styles.radioCircleActive : ''}`}>
                                                    {formData.message.types.text.content_mode === 'quick_question' && <div className={styles.radioInner}></div>}
                                                </div>
                                                <div style={{ flex: 1 }}>
                                                    <span style={{ fontSize: '14px' }}>Quick question</span>
                                                    {formData.message.types.text.content_mode === 'quick_question' && (
                                                        <div className={styles.quickContainer} style={{ marginTop: '12px' }}>
                                                            {formData.message.types.text.quick_questions.map((q: string, i: number) => (
                                                                <div key={i} className={styles.quickItem}>
                                                                    <div style={{ flex: 1, fontSize: '13px', color: '#111' }}>{q}</div>
                                                                    <div className={styles.actions} style={{ display: 'flex', gap: '12px' }}>
                                                                        <FiEdit2 size={14} className={styles.actionIcon} style={{ cursor: 'pointer', color: '#6b7280' }} onClick={(e) => {
                                                                            e.stopPropagation();
                                                                            setEditingQuestionIndex(i);
                                                                            setQuickQuestionDraft(q);
                                                                            setQuickQuestionModalOpen(true);
                                                                        }} />
                                                                        <FiTrash2 size={14} className={styles.deleteIcon} style={{ cursor: 'pointer', color: '#6b7280' }} onClick={(e) => {
                                                                            e.stopPropagation();
                                                                            const newQs = [...formData.message.types.text.quick_questions];
                                                                            newQs.splice(i, 1);
                                                                            updateNested(["message", "types", "text", "quick_questions"], newQs);
                                                                        }} />
                                                                    </div>
                                                                </div>
                                                            ))}
                                                            <button className={styles.addQuestion} onClick={() => {
                                                                setEditingQuestionIndex(-1);
                                                                setQuickQuestionDraft("");
                                                                setQuickQuestionModalOpen(true);
                                                            }}>
                                                                <FiPlus size={14} /> Add question
                                                            </button>
                                                        </div>
                                                    )}
                                                </div>
                                            </div>
                                            <div className={styles.triggerOption} style={{ padding: '8px 0', border: 'none' }} onClick={() => updateNested(["message", "types", "text", "content_mode"], 'custom')}>
                                                <div className={`${styles.radioCircle} ${formData.message.types.text.content_mode === 'custom' ? styles.radioCircleActive : ''}`}>
                                                    {formData.message.types.text.content_mode === 'custom' && <div className={styles.radioInner}></div>}
                                                </div>
                                                <div style={{ flex: 1 }}>
                                                    <span style={{ fontSize: '14px' }}>Custom message</span>
                                                    {formData.message.types.text.content_mode === 'custom' && (
                                                        <div style={{ marginTop: '12px', background: '#fff', border: '1px solid #e5e7eb', borderRadius: '8px' }}>
                                                            <RichTextToolbar />
                                                            <div style={{ padding: '12px' }}>
                                                                <textarea
                                                                    className={styles.instructionTextArea}
                                                                    style={{ border: 'none', minHeight: '80px', background: 'transparent', width: '100%', padding: 0 }}
                                                                    value={formData.message.types.text.custom_message || ''}
                                                                    onChange={e => updateNested(["message", "types", "text", "custom_message"], e.target.value)}
                                                                />
                                                            </div>
                                                        </div>
                                                    )}
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                )}

                                {formData.message.active_type === "product_recommendation" && (
                                    <div className={styles.labelGroup}>
                                        <div style={{ background: '#fff', border: '1px solid #e5e7eb', borderRadius: '8px', marginBottom: '20px' }}>
                                            <RichTextToolbar />
                                            <div style={{ padding: '12px' }}>
                                                <textarea
                                                    className={styles.instructionTextArea}
                                                    style={{ border: 'none', minHeight: '60px', background: 'transparent', width: '100%', padding: 0 }}
                                                    value={formData.message.types.product_recommendation.message_body || ''}
                                                    onChange={e => updateNested(["message", "types", "product_recommendation", "message_body"], e.target.value)}
                                                />
                                            </div>
                                        </div>

                                        <div style={{ display: 'flex', flexDirection: 'column', gap: '8px' }}>
                                            {[
                                                { id: 'best', label: 'Recommend best sellers', desc: 'Suggest top-selling items based on order volume' },
                                                { id: 'new', label: 'Recommend new arrivals', desc: 'Highlight the latest products recently added to your store' },
                                                { id: 'complementary', label: 'Recommend complementary products', desc: 'Show complementary items. Customize further in Search & Discovery app' },
                                                { id: 'custom_recommendation', label: 'Custom recommendation', desc: 'Manually choose specific products to recommend' },
                                            ].map(opt => (
                                                <div key={opt.id} className={styles.triggerOption} style={{ marginBottom: 0, padding: '12px 0', border: 'none', alignItems: 'flex-start' }} onClick={() => updateNested(["message", "types", "product_recommendation", "recommendation_type"], opt.id)}>
                                                    <div className={`${styles.radioCircle} ${formData.message.types.product_recommendation.recommendation_type === opt.id ? styles.radioCircleActive : ''}`} style={{ marginTop: '2px' }}>
                                                        {formData.message.types.product_recommendation.recommendation_type === opt.id && <div className={styles.radioInner}></div>}
                                                    </div>
                                                    <div style={{ flex: 1 }}>
                                                        <span style={{ fontSize: '14px', display: 'block', color: '#111' }}>{opt.label}</span>
                                                        <span style={{ fontSize: '13px', color: '#6b7280', display: 'block', marginTop: '4px' }}>{opt.desc}</span>
                                                        {opt.id === 'custom_recommendation' && formData.message.types.product_recommendation.recommendation_type === 'custom_recommendation' && (
                                                            <div style={{ position: 'relative', marginTop: '12px' }}>
                                                                <FiSearch style={{ position: 'absolute', left: '12px', top: '10px', color: '#9ca3af' }} />
                                                                <input type="text" className={styles.chatInput} placeholder="Search products" style={{ paddingLeft: '40px', textAlign: 'left', maxWidth: '100%', height: '36px' }} />
                                                                <FiChevronRight style={{ position: 'absolute', right: '12px', top: '10px', color: '#9ca3af' }} />
                                                            </div>
                                                        )}
                                                    </div>
                                                </div>
                                            ))}
                                        </div>
                                    </div>
                                )}

                                {formData.message.active_type === "discount" && (
                                    <div className={styles.labelGroup}>
                                        <div style={{ background: '#f9fafb', border: '1px solid #e5e7eb', borderRadius: '8px', marginBottom: '20px' }}>
                                            <RichTextToolbar />
                                            <div style={{ padding: '12px' }}>
                                                <textarea
                                                    className={styles.instructionTextArea}
                                                    style={{ border: 'none', background: 'transparent', minHeight: '100px', width: '100%', padding: 0 }}
                                                    value={formData.message.types.discount.message_body || ""}
                                                    onChange={e => updateNested(["message", "types", "discount", "message_body"], e.target.value)}
                                                />
                                            </div>
                                        </div>

                                        <div style={{ marginBottom: '20px' }}>
                                            <label className={styles.settingsInputLabel} style={{ marginBottom: '8px', display: 'block' }}>Discount code</label>
                                            <div style={{ position: 'relative' }}>
                                                <FiSearch style={{ position: 'absolute', left: '12px', top: '10px', color: '#9ca3af' }} />
                                                <input
                                                    type="text"
                                                    className={styles.chatInput}
                                                    placeholder="Search discount code"
                                                    style={{ paddingLeft: '40px', paddingRight: '80px', textAlign: 'left', maxWidth: '100%', height: '36px' }}
                                                    value={formData.message.types.discount.discount_code || ""}
                                                    onChange={e => updateNested(["message", "types", "discount", "discount_code"], e.target.value)}
                                                />
                                                <button style={{ position: 'absolute', right: '4px', top: '4px', background: '#f9fafb', border: '1px solid #e5e7eb', color: '#111', borderRadius: '4px', padding: '4px 12px', fontSize: '13px', fontWeight: 600, cursor: 'pointer' }}>Select</button>
                                            </div>
                                        </div>

                                        <div>
                                            <label className={styles.settingsInputLabel} style={{ marginBottom: '8px', display: 'block' }}>Usage instruction</label>
                                            <textarea
                                                className={styles.chatInput}
                                                style={{ background: '#f9fafb', border: '1px solid #e5e7eb', padding: '12px', fontSize: '13px', color: '#4b5563', minHeight: '60px', height: 'auto', textAlign: 'left', display: 'block', lineHeight: 1.5, width: '100%' }}
                                                value={formData.message.types.discount.usage_instruction || ""}
                                                onChange={e => updateNested(["message", "types", "discount", "usage_instruction"], e.target.value)}
                                            />
                                        </div>
                                    </div>
                                )}
                            </div>
                        )}
                    </div>

                    {/* Appearance Section */}
                    <div className={styles.collapsibleCard}>
                        <div className={styles.collapsibleHeader} onClick={() => toggleCategory("Appearance")}>
                            <span>Appearance</span>
                            {activeCategory === "Appearance" ? <FiChevronDown /> : <FiChevronRight />}
                        </div>
                        {activeCategory === "Appearance" && (
                            <div className={styles.collapsibleContent}>
                                {renderColorOptions('background_color', 'Background color', ['#ffffff', '#1a1a1a', '#0f172a', '#134e4a', '#2e1065', '#831843', '#e0f2fe', '#fef3c7', '#ede9fe', '#fce7f3'], true)}
                                {renderColorOptions('text_color', 'Text color', ['#ffffff', '#1a1a1a'], false)}
                                {renderColorOptions('button_background_color', 'Button background color', ['#ffffff', '#1a1a1a'], true)}
                                {renderColorOptions('button_label_color', 'Button label color', ['#ffffff', '#1a1a1a'], false)}
                            </div>
                        )}
                    </div>
                </div>

                {/* Preview Sidebar */}
                <div className={styles.previewSidebar}>
                    <div className={styles.feedbackCard} style={{ padding: '24px', position: 'sticky', top: '24px' }}>
                        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: '20px' }}>
                            <h3 className={styles.cardSectionTitle} style={{ margin: 0, display: 'flex', alignItems: 'center', gap: '8px' }}>
                                <FiMonitor size={14} /> Preview
                            </h3>
                            <button
                                className={styles.actionIconBtn}
                                style={{ display: 'flex', alignItems: 'center', justifyContent: 'center', width: '100px', gap: '8px', fontSize: '13px', cursor: 'pointer', background: '#fff', border: '1px solid #e5e7eb', borderRadius: '8px', padding: '6px 0' }}
                                onClick={() => setDesktopPreviewOpen(true)}
                            >
                                <FiMonitor size={14} /> Desktop
                            </button>
                        </div>

                        <div className={styles.phoneFrame} style={{ borderColor: '#e5e7eb', margin: '0 auto', width: '320px', borderRadius: '24px', overflow: 'hidden' }}>
                            <div className={styles.chatBody} style={{ background: '#f3f4f6', position: 'relative', height: '500px' }}>
                                <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', background: '#fff', padding: '16px 20px', borderBottom: '1px solid rgba(0,0,0,0.05)' }}>
                                    <div style={{ fontWeight: 800, fontSize: '14px', color: '#6b7280' }}>☰</div>
                                    <div style={{ fontWeight: 800, fontSize: '12px', color: '#111' }}>YOUR STORE</div>
                                    <div style={{ display: 'flex', gap: '12px', color: '#6b7280' }}>
                                        <div style={{ fontSize: '14px' }}><FiSearch /></div>
                                        <div style={{ fontSize: '14px' }}><FiBox /></div>
                                    </div>
                                </div>

                                {/* Dummy skeleton content */}
                                <div style={{ padding: '20px' }}>
                                    <div style={{ height: '30px', background: '#e5e7eb', borderRadius: '4px', width: '60%', marginBottom: '16px' }}></div>
                                    <div style={{ height: '100px', background: '#e5e7eb', borderRadius: '8px', marginBottom: '16px' }}></div>
                                    <div style={{ display: 'flex', gap: '12px' }}>
                                        <div style={{ height: '140px', background: '#e5e7eb', borderRadius: '8px', flex: 1 }}></div>
                                        <div style={{ height: '140px', background: '#e5e7eb', borderRadius: '8px', flex: 1 }}></div>
                                    </div>
                                </div>

                                {/* Proactive Message Overlay */}
                                {formData.status.is_active && (
                                    <div className={styles.proactiveMessagePreview} style={{
                                        background: formData.appearance.colors.background_color === 'gradient' ? 'linear-gradient(45deg, #7c3aed, #ec4899)' : formData.appearance.colors.background_color,
                                        color: formData.appearance.colors.text_color,
                                        border: '1px solid rgba(0,0,0,0.1)',
                                        boxShadow: '0 10px 15px -3px rgba(0,0,0,0.1)',
                                        borderRadius: '16px',
                                        padding: '20px',
                                        position: 'absolute',
                                        bottom: '80px',
                                        right: '20px',
                                        width: 'calc(100% - 40px)',
                                        maxWidth: '320px',
                                        zIndex: 10
                                    }}>
                                        <div className={styles.previewClose} style={{ color: formData.appearance.colors.text_color, opacity: 0.5, position: 'absolute', top: '12px', right: '12px', cursor: 'pointer' }}><FiX /></div>
                                        <div style={{ marginTop: '8px' }}>
                                            {renderPreviewContent()}
                                        </div>
                                    </div>
                                )}

                                {/* Widget Icon */}
                                <div className={styles.proactiveWidgetIcon} style={{
                                    background: formData.appearance.colors.button_background_color === 'gradient' ? 'linear-gradient(45deg, #7c3aed, #ec4899)' : formData.appearance.colors.button_background_color,
                                    color: formData.appearance.colors.button_label_color,
                                    position: 'absolute',
                                    bottom: '20px',
                                    right: '20px',
                                    width: '52px',
                                    height: '52px',
                                    borderRadius: '26px',
                                    display: 'flex',
                                    alignItems: 'center',
                                    justifyContent: 'center',
                                    boxShadow: '0 4px 6px -1px rgba(0,0,0,0.1)',
                                    zIndex: 10
                                }}>
                                    <FiMessageSquare size={24} />
                                    <div className={styles.proactiveWidgetBadge} style={{ background: '#10b981', width: '12px', height: '12px', borderRadius: '50%', position: 'absolute', top: '2px', right: '2px', border: `2px solid ${formData.appearance.colors.button_background_color === 'gradient' ? '#7c3aed' : formData.appearance.colors.button_background_color}` }}></div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>

            {/* Country Browser Modal */}
            {countryModalOpen && (
                <div style={{ position: 'fixed', top: 0, left: 0, right: 0, bottom: 0, background: 'rgba(0,0,0,0.5)', zIndex: 1000, display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
                    <div style={{ background: '#fff', borderRadius: '12px', width: '500px', maxWidth: '90%', maxHeight: '90vh', display: 'flex', flexDirection: 'column' }}>
                        <div style={{ padding: '16px 20px', borderBottom: '1px solid #e5e7eb', display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
                            <h3 style={{ margin: 0, fontSize: '16px' }}>Browse countries</h3>
                            <FiX size={20} style={{ cursor: 'pointer', color: '#6b7280' }} onClick={() => setCountryModalOpen(false)} />
                        </div>
                        <div style={{ padding: '16px 20px', borderBottom: '1px solid #e5e7eb' }}>
                            <div style={{ position: 'relative' }}>
                                <FiSearch style={{ position: 'absolute', left: '12px', top: '10px', color: '#9ca3af' }} />
                                <input
                                    type="text"
                                    className={styles.chatInput}
                                    placeholder="Search countries"
                                    style={{ paddingLeft: '40px', width: '100%' }}
                                    value={countrySearch}
                                    onChange={(e) => setCountrySearch(e.target.value)}
                                />
                            </div>
                        </div>
                        <div style={{ flex: 1, overflowY: 'auto', padding: '8px 0' }}>
                            {countries.filter(c => c.name.toLowerCase().includes(countrySearch.toLowerCase())).map(c => {
                                const isSelected = pendingSelectedCountries.includes(c.code);
                                return (
                                    <div key={c.code} className={styles.triggerOption} style={{ display: 'flex', alignItems: 'center', gap: '12px', padding: '10px 20px', cursor: 'pointer', margin: 0, border: 'none', borderBottom: '1px solid #f3f4f6' }} onClick={() => togglePendingCountry(c.code)}>
                                        <div style={{ width: '18px', height: '18px', border: isSelected ? 'none' : '1px solid #d1d5db', background: isSelected ? '#111' : '#fff', borderRadius: '4px', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
                                            {isSelected && <svg width="10" height="8" viewBox="0 0 10 8" fill="none" xmlns="http://www.w3.org/2000/svg"><path d="M1 4L3.5 6.5L9 1" stroke="white" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round" /></svg>}
                                        </div>
                                        <span style={{ fontSize: '18px' }}>{c.flag}</span>
                                        <span style={{ fontSize: '14px', color: '#111' }}>{c.name}</span>
                                    </div>
                                )
                            })}
                        </div>
                        <div style={{ padding: '16px 20px', borderTop: '1px solid #e5e7eb', display: 'flex', justifyContent: 'flex-end', gap: '12px' }}>
                            <button onClick={() => setCountryModalOpen(false)} style={{ background: '#fff', border: '1px solid #e5e7eb', padding: '8px 16px', borderRadius: '6px', fontSize: '14px', cursor: 'pointer', fontWeight: 500 }}>Cancel</button>
                            <button onClick={() => {
                                updateNested(["conditions", "geography", "country_codes"], pendingSelectedCountries);
                                setCountryModalOpen(false);
                            }} style={{ background: '#111', color: '#fff', border: 'none', padding: '8px 16px', borderRadius: '6px', fontSize: '14px', cursor: 'pointer', fontWeight: 500 }}>Done</button>
                        </div>
                    </div>
                </div>
            )}

            {/* Desktop Preview Modal Overlay */}
            {desktopPreviewOpen && (
                <div style={{ position: 'fixed', top: 0, left: 0, right: 0, bottom: 0, background: 'rgba(0,0,0,0.5)', zIndex: 1000, display: 'flex', alignItems: 'center', justifyContent: 'center' }} onClick={() => setDesktopPreviewOpen(false)}>
                    <div style={{ width: '800px', height: '600px', borderRadius: '16px', display: 'flex', flexDirection: 'column', overflow: 'hidden', background: '#f3f4f6' }} onClick={e => e.stopPropagation()}>
                        <div style={{ padding: '16px 24px', borderBottom: '1px solid #e5e7eb', display: 'flex', justifyContent: 'space-between', alignItems: 'center', background: '#fff' }}>
                            <h2 style={{ fontSize: '16px', fontWeight: 600, color: '#111827', margin: 0 }}>Desktop preview</h2>
                            <button onClick={() => setDesktopPreviewOpen(false)} style={{ border: 'none', background: 'transparent', cursor: 'pointer', padding: 0 }}>
                                <FiX size={20} color="#6b7280" />
                            </button>
                        </div>
                        <div style={{ flex: 1, padding: '40px 60px', display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center' }}>
                            <div style={{ width: '100%', height: '100%', background: '#fff', borderRadius: '12px', border: '1px solid #e5e7eb', overflow: 'hidden', boxShadow: '0 4px 6px -1px rgba(0,0,0,0.1)', position: 'relative' }}>
                                <div style={{ background: '#f9fafb', padding: '12px 16px', display: 'flex', alignItems: 'center', gap: '8px', borderBottom: '1px solid #e5e7eb' }}>
                                    <div style={{ width: '12px', height: '12px', borderRadius: '50%', background: '#ef4444' }}></div>
                                    <div style={{ width: '12px', height: '12px', borderRadius: '50%', background: '#f59e0b' }}></div>
                                    <div style={{ width: '12px', height: '12px', borderRadius: '50%', background: '#10b981' }}></div>
                                </div>
                                <div style={{ height: 'calc(100% - 40px)', background: '#fff', position: 'relative' }}>
                                    {formData.status.is_active && (
                                        <div className={styles.proactiveMessagePreview} style={{
                                            background: formData.appearance.colors.background_color === 'gradient' ? 'linear-gradient(45deg, #7c3aed, #ec4899)' : formData.appearance.colors.background_color,
                                            color: formData.appearance.colors.text_color,
                                            border: '1px solid rgba(0,0,0,0.1)',
                                            boxShadow: '0 10px 15px -3px rgba(0,0,0,0.1)',
                                            borderRadius: '16px',
                                            padding: '20px',
                                            position: 'absolute',
                                            bottom: '90px',
                                            right: '24px',
                                            width: '320px',
                                            zIndex: 10
                                        }}>
                                            <div className={styles.previewClose} style={{ color: formData.appearance.colors.text_color, opacity: 0.5, position: 'absolute', top: '12px', right: '12px', cursor: 'pointer' }}><FiX /></div>
                                            <div style={{ marginTop: '8px' }}>
                                                {renderPreviewContent()}
                                            </div>
                                        </div>
                                    )}

                                    {/* Widget Icon */}
                                    <div className={styles.proactiveWidgetIcon} style={{
                                        background: formData.appearance.colors.button_background_color === 'gradient' ? 'linear-gradient(45deg, #7c3aed, #ec4899)' : formData.appearance.colors.button_background_color,
                                        color: formData.appearance.colors.button_label_color,
                                        position: 'absolute',
                                        bottom: '24px',
                                        right: '24px',
                                        width: '56px',
                                        height: '56px',
                                        borderRadius: '28px',
                                        display: 'flex',
                                        alignItems: 'center',
                                        justifyContent: 'center',
                                        boxShadow: '0 4px 10px rgba(0,0,0,0.1)',
                                        zIndex: 10,
                                        cursor: 'pointer'
                                    }}>
                                        <FiChevronDown size={28} />
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            )}

            {/* Quick Question Modal Overlay */}
            {quickQuestionModalOpen && (
                <div style={{ position: 'fixed', top: 0, left: 0, right: 0, bottom: 0, background: 'rgba(0,0,0,0.5)', zIndex: 1000, display: 'flex', alignItems: 'center', justifyContent: 'center' }} onClick={() => setQuickQuestionModalOpen(false)}>
                    <div style={{ background: '#fff', borderRadius: '12px', width: '500px', maxWidth: '90%', display: 'flex', flexDirection: 'column' }} onClick={e => e.stopPropagation()}>
                        <div style={{ padding: '16px 20px', borderBottom: '1px solid #e5e7eb', display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
                            <h3 style={{ margin: 0, fontSize: '15px' }}>{editingQuestionIndex >= 0 ? "Edit question" : "Add question"}</h3>
                            <FiX size={18} style={{ cursor: 'pointer', color: '#6b7280' }} onClick={() => setQuickQuestionModalOpen(false)} />
                        </div>
                        <div style={{ padding: '20px' }}>
                            <label style={{ display: 'block', fontSize: '13px', marginBottom: '8px', color: '#374151' }}>Question</label>
                            <input
                                type="text"
                                value={quickQuestionDraft}
                                onChange={e => setQuickQuestionDraft(e.target.value)}
                                style={{ width: '100%', padding: '10px 14px', borderRadius: '8px', border: '1px solid #d1d5db', fontSize: '14px', outline: 'none' }}
                            />
                        </div>
                        <div style={{ padding: '16px 20px', borderTop: '1px solid #e5e7eb', display: 'flex', justifyContent: 'flex-end', gap: '12px' }}>
                            <button onClick={() => setQuickQuestionModalOpen(false)} style={{ background: '#f3f4f6', border: 'none', padding: '8px 16px', borderRadius: '6px', fontSize: '13px', cursor: 'pointer', fontWeight: 500, color: '#4b5563' }}>Cancel</button>
                            <button
                                disabled={!quickQuestionDraft.trim()}
                                onClick={() => {
                                    const newQs = [...formData.message.types.text.quick_questions];
                                    if (editingQuestionIndex >= 0) {
                                        newQs[editingQuestionIndex] = quickQuestionDraft;
                                    } else {
                                        newQs.push(quickQuestionDraft);
                                    }
                                    updateNested(["message", "types", "text", "quick_questions"], newQs);
                                    setQuickQuestionModalOpen(false);
                                }}
                                style={{ background: quickQuestionDraft.trim() ? '#111' : '#e5e7eb', color: quickQuestionDraft.trim() ? '#fff' : '#9ca3af', border: 'none', padding: '8px 16px', borderRadius: '6px', fontSize: '13px', cursor: quickQuestionDraft.trim() ? 'pointer' : 'not-allowed', fontWeight: 500 }}
                            >
                                Save
                            </button>
                        </div>
                    </div>
                </div>
            )}
        </div>
    );
}
