import { useState } from "react";
import styles from "./ChatbotSettings.module.css";
import { FiMonitor, FiSearch, FiChevronRight, FiMail, FiX, FiUsers, FiMessageSquare, FiHome, FiMessageCircle, FiTruck, FiHelpCircle, FiSend, FiLink } from "react-icons/fi";
import { 
    FaFacebookMessenger, 
    FaTelegram, 
    FaSkype, 
    FaLine, 
    FaTiktok, 
    FaWhatsapp,
    FaInstagram,
    FaPhone
} from "react-icons/fa";

const getContactIcon = (type: string) => {
    switch (type.toLowerCase()) {
        case 'messenger': return FaFacebookMessenger;
        case 'phone call': return FaPhone;
        case 'instagram': return FaInstagram;
        case 'telegram': return FaTelegram;
        case 'skype': return FaSkype;
        case 'line': return FaLine;
        case 'whatsapp': return FaWhatsapp;
        case 'sms': return FiMessageSquare;
        case 'tiktok': return FaTiktok;
        default: return FiMail;
    }
};

const getIconColor = (type: string) => {
    switch (type.toLowerCase()) {
        case 'messenger': return '#0084FF';
        case 'phone call': return '#10b981';
        case 'instagram': return '#E1306C';
        case 'telegram': return '#0088cc';
        case 'skype': return '#00AFF0';
        case 'line': return '#00C300';
        case 'whatsapp': return '#25D366';
        case 'sms': return '#3b82f6';
        case 'tiktok': return '#000000';
        default: return '#fbbf24';
    }
};

// Tab Components
import GeneralTab from "./settings/tabs/GeneralTab";
import ChatPageTab from "./settings/tabs/ChatPageTab";
import AppearanceTab from "./settings/tabs/AppearanceTab";
import AdvancedTab from "./settings/tabs/AdvancedTab";

// Modal Components
import AddQuestionModal from "./settings/modals/AddQuestionModal";
import ContactModal from "./settings/modals/ContactModal";

// API
import { useGetChatbotSettings, useUpdateChatbotSettings, useUpdateChatbotSection } from "app/utils/api";
import { useEffect } from "react";

export default function ChatbotSettings() {
    const [activeTab, setActiveTab] = useState("Chat Page");
    const [displayChatbox, setDisplayChatbox] = useState(true);
    const [focusMode, setFocusMode] = useState(false);
    const [showContactModal, setShowContactModal] = useState(false);
    const [showQuestionModal, setShowQuestionModal] = useState(false);

    // General States
    const [logoUrl, setLogoUrl] = useState<string | null>(null);
    const [language, setLanguage] = useState("English");
    const [heading, setHeading] = useState("Hi 👋");
    const [description, setDescription] = useState("How can we help you?");
    const [showLiveChat, setShowLiveChat] = useState(true);
    const [showContact, setShowContact] = useState(true);
    const [showOrderTracking, setShowOrderTracking] = useState(true);
    const [showFaqs, setShowFaqs] = useState(true);
    const [showCategories, setShowCategories] = useState(false);

    // Chat Page States
    const [handover, setHandover] = useState("Only when your team is online");
    const [conversationStarter, setConversationStarter] = useState(true);
    const [chatAvatar, setChatAvatar] = useState("Store branding");
    const [preChatForm, setPreChatForm] = useState("Chat as guest");
    const [preChatDescription, setPreChatDescription] = useState("Please enter your contact information so we can keep you updated with our replies.");
    const [messagesAfter, setMessagesAfter] = useState(1);
    const [marketingOptIn, setMarketingOptIn] = useState(true);
    const [disclaimerConsent, setDisclaimerConsent] = useState(true);
    const [disclaimerText, setDisclaimerText] = useState("By sending us a message, you agree to our privacy policy.");
    const [aiName, setAiName] = useState("Qixs");
    const [welcomeMessage, setWelcomeMessage] = useState("Hi {{customer_name}} 👋\nHow can we help you?");

    // Appearance States
    const [brandColor, setBrandColor] = useState("linear-gradient(135deg, #a5b4fc, #6366f1)");
    const [isCustomColorTab, setIsCustomColorTab] = useState(false);
    const [isGradientHeader, setIsGradientHeader] = useState(true);
    const [headerColor1, setHeaderColor1] = useState("#7f1d1d"); // Volcano default 1
    const [headerColor2, setHeaderColor2] = useState("#450a0a"); // Volcano default 2
    const [headerTextColor, setHeaderTextColor] = useState("#FFFFFF");
    const [chatboxTextColor, setChatboxTextColor] = useState("#232323");
    const [buttonBgColor, setButtonBgColor] = useState("#7f1d1d");
    const [buttonTextColor, setButtonTextColor] = useState("#FFFFFF");

    const [alignment, setAlignment] = useState("Right");
    const [chatboxStyle, setChatboxStyle] = useState("Show navigation");
    const [mobileRatio, setMobileRatio] = useState("full-screen");
    const [launcher, setLauncher] = useState("icon");
    const [previewSection, setPreviewSection] = useState("Home");
    const [buttonIcon, setButtonIcon] = useState("msg1");
    const [buttonLabel, setButtonLabel] = useState("Hi 👋");
    const [buttonSize, setButtonSize] = useState("Small");

    // Contact Config States
    const [chatStatus, setChatStatus] = useState(true);
    const [onlineStatus, setOnlineStatus] = useState("We are online");
    const [offlineStatus, setOfflineStatus] = useState("Usually reply in a few minutes");
    const [showOnlineOutside, setShowOnlineOutside] = useState(true);
    const [showContactMethods, setShowContactMethods] = useState(true);
    const [contactMethods, setContactMethods] = useState([
        { id: '1', type: 'Email', value: 'sarang@gmail.com', icon: 'email' }
    ]);

    const [isPreviewDesktop, setIsPreviewDesktop] = useState(false);
    const [isChatOpenDesktop, setIsChatOpenDesktop] = useState(true);
    const [isChatOpenMobile, setIsChatOpenMobile] = useState(true);
    const [isChatStarted, setIsChatStarted] = useState(false);
    const [previewEmail, setPreviewEmail] = useState("");
    const [previewName, setPreviewName] = useState("");
    const [previewPhone, setPreviewPhone] = useState("");
    const [contactFields, setContactFields] = useState<any[]>([{ label: "Email address", required: true }]);
    const [selectedQuestion, setSelectedQuestion] = useState<any>(null);

    useEffect(() => {
        if (previewSection !== "Message") {
            setIsChatStarted(false);
            setPreviewEmail("");
        }
    }, [previewSection]);

    // Advanced States
    const [displayDevices, setDisplayDevices] = useState("all"); // all, desktop, mobile
    const [displayPages, setDisplayPages] = useState("all_pages"); // all_pages, show_specific, hide_specific
    const [includedPages, setIncludedPages] = useState<string[]>([]);
    const [excludedPages, setExcludedPages] = useState<string[]>([]);
    const [customUrlPattern, setCustomUrlPattern] = useState("");
    const [continueAsEmail, setContinueAsEmail] = useState(false);
    const [customCss, setCustomCss] = useState("");

    const [questions, setQuestions] = useState([
        { id: 1, text: "Track my order", desc: "You can track your order using the tracking number p...", icon: "📦" },
        { id: 2, text: "How long does delivery take?", desc: "Typically, it takes 3–5 business days to receive your or...", icon: "🚚" },
        { id: 3, text: "Return policy", desc: "Please check our return/refund/exchange policy here.", icon: "🔄" },
    ]);

    const tabs = ["General", "Chat Page", "Appearance", "Advanced"];

    const sectionMap: Record<string, string> = {
        "General": "general",
        "Chat Page": "chatPage",
        "Appearance": "appearance",
        "Advanced": "advanced"
    };

    const { data: settings } = useGetChatbotSettings(sectionMap[activeTab] || 'general');
    const updateSettingsMutation = useUpdateChatbotSettings();
    const updateSectionMutation = useUpdateChatbotSection();

    useEffect(() => {
        if (settings?.data) {
            const data = settings.data;
            const currentSection = sectionMap[activeTab];

            // Map data based on the section returned
            if (data.general) {
                const g = data.general;
                setDisplayChatbox(g.displayOnStore !== undefined ? g.displayOnStore : true);
                setFocusMode(g.chatFocusMode !== undefined ? g.chatFocusMode : false);
                setLanguage(g.language === 'en' ? 'English' : g.language);

                if (g.blocks) {
                    setShowLiveChat(g.blocks.liveChat);
                    setShowOrderTracking(g.blocks.orderTracking);
                    setShowFaqs(g.blocks.faqs);
                    setShowCategories(g.blocks.categories);

                    if (g.blocks.contact) {
                        const c = g.blocks.contact;
                        setShowContact(c.enabled);
                        setChatStatus(c.chatStatusEnabled);
                        setOnlineStatus(c.onlineStatusText || "We are online");
                        setOfflineStatus(c.offlineStatusText || "Usually reply in a few minutes");
                        setShowOnlineOutside(c.showOutsideWorkingHours);
                        setShowContactMethods(c.contactMethodsEnabled);
                        if (c.contactMethods) setContactMethods(c.contactMethods);
                    }
                }
            }

            if (data.appearance) {
                const a = data.appearance;
                if (a.brandColors) {
                    if (a.brandColors.preset === "Custom") {
                        setIsCustomColorTab(true);
                        if (a.brandColors.customColor) setButtonBgColor(a.brandColors.customColor);
                    } else {
                        setIsCustomColorTab(false);
                        if (a.brandColors.customColor) setBrandColor(a.brandColors.customColor);
                    }
                }
                if (a.chatboxButton?.alignment) setAlignment(a.chatboxButton.alignment === 'left' ? 'Left' : 'Right');
                if (a.chatboxButton?.launcher) setLauncher(a.chatboxButton.launcher);
                if (a.chatboxButton?.buttonIcon) setButtonIcon(a.chatboxButton.buttonIcon);
                if (a.chatboxButton?.buttonLabel) setButtonLabel(a.chatboxButton.buttonLabel);
                if (a.chatboxButton?.buttonSize) setButtonSize(a.chatboxButton.buttonSize.charAt(0).toUpperCase() + a.chatboxButton.buttonSize.slice(1));
                if (a.chatboxStyle) {
                    if (a.chatboxStyle.displayStyle) setChatboxStyle(a.chatboxStyle.displayStyle === 'navigation' ? 'Show navigation' : 'No navigation');
                    if (a.chatboxStyle.mobileRatio) setMobileRatio(a.chatboxStyle.mobileRatio);
                }
            }

            if (data.chatPage) {
                const cp = data.chatPage;
                if (cp.greeting) {
                    setAiName(cp.greeting.aiName || "Qixs");
                    setWelcomeMessage(cp.greeting.welcomeMessage || "Hi {{customer_name}} 👋\nHow can we help you?");
                }
                if (cp.handoverRule) setHandover(cp.handoverRule);
                if (cp.conversationStartersEnabled !== undefined) setConversationStarter(cp.conversationStartersEnabled);
                if (cp.conversationStarters) {
                    setQuestions(cp.conversationStarters.map((q: any) => ({
                        id: q.id || Math.random(),
                        text: q.question,
                        desc: q.answer,
                        icon: q.icon || "💬"
                    })));
                }
                if (cp.chatAvatar === "STORE_BRANDING") setChatAvatar("Store branding");
                else if (cp.chatAvatar === "TEAM_MEMBER") setChatAvatar("Team member profile");

                if (cp.preChatForm) {
                    const pcf = cp.preChatForm;
                    const modeLabelMap: Record<string, string> = {
                        "CHAT_AS_GUEST": "Chat as guest",
                        "CHAT_AS_ANONYMOUS": "Chat as anonymous",
                        "SHOW_BOTH_OPTIONS": "Show both options"
                    };
                    setPreChatForm(modeLabelMap[pcf.mode] || "Chat as guest");
                    setMessagesAfter(pcf.showAfterMessages || 1);
                    setPreChatDescription(pcf.description || "");
                    if (pcf.fields) {
                        setContactFields(pcf.fields.map((f: any) => ({
                            label: f.label,
                            required: f.required
                        })));
                    }
                    setMarketingOptIn(pcf.marketingOptInEnabled || false);
                    setDisclaimerConsent(pcf.disclaimerConsentEnabled || false);
                    setDisclaimerText(pcf.consentText || "");
                }
            }

            if (data.advanced) {
                const adv = data.advanced;
                if (adv.visibility) {
                    const v = adv.visibility;
                    if (v.displayDevices) setDisplayDevices(v.displayDevices);
                    if (v.displayPages) setDisplayPages(v.displayPages);
                    if (v.includedPages) setIncludedPages(v.includedPages);
                    if (v.excludedPages) setExcludedPages(v.excludedPages);
                    if (v.customUrlPattern) setCustomUrlPattern(v.customUrlPattern);
                }
                setContinueAsEmail(adv.continueAsEmail !== undefined ? adv.continueAsEmail : false);
                setCustomCss(adv.customCss || "");
            }
        }
    }, [settings]);

    function LauncherIcon({ id }: { id: string }) {
        if (!id) return null;
        if (id.startsWith('data:') || id.startsWith('http')) {
            return <img src={id} alt="" style={{ width: '28px', height: '28px', borderRadius: '50%', objectFit: 'cover', flexShrink: 0 }} />;
        }
        switch(id) {
            case 'msg1': return <svg viewBox="0 0 24 24" width="24" height="24" fill="white"><path d="M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z" /></svg>;
            case 'msg2': return <svg viewBox="0 0 24 24" width="24" height="24" fill="white"><path d="M20 2H4c-1.1 0-2 .9-2 2v18l4-4h14c1.1 0 2-.9 2-2V4c0-1.1-.9-2-2-2z"/></svg>;
            case 'msg3': return <svg viewBox="0 0 24 24" width="24" height="24" fill="white"><path d="M20 2H4c-1.1 0-1.99.9-1.99 2L2 22l4-4h14c1.1 0 2-.9 2-2V4c0-1.1-.9-2-2-2zm-2 12H6v-2h12v2zm0-3H6V9h12v2zm0-3H6V6h12v2z"/></svg>;
            case 'messenger': return <FaFacebookMessenger size={22} color="white" />;
            case 'call': return <FaPhone size={20} color="white" />;
            case 'send': return <svg viewBox="0 0 24 24" width="24" height="24" fill="white"><path d="M2.01 21L23 12 2.01 3 2 10l15 2-15 2z"/></svg>;
            default: return <FiMessageSquare size={22} color="white" />;
        }
    }

    function LauncherBody({ isMobile = false }) {
        const showIcon = launcher === "icon_only" || launcher === "icon_label";
        const showLabel = launcher === "label_only" || launcher === "icon_label";

        return (
            <div 
                className={isMobile ? styles.mobileChatLauncher : styles.desktopChatLauncher} 
                style={{ 
                    background: isCustomColorTab ? buttonBgColor : brandColor,
                    ...(isMobile ? {
                        position: 'absolute',
                        bottom: '20px',
                        [alignment === "Left" ? "left" : "right"]: '20px',
                        width: launcher === "icon_only" ? (buttonSize === 'Small' ? '45px' : buttonSize === 'Medium' ? '55px' : '65px') : 'auto',
                        height: launcher === "icon_only" ? (buttonSize === 'Small' ? '45px' : buttonSize === 'Medium' ? '55px' : '65px') : '45px',
                        padding: launcher === "icon_only" ? '0' : '0 20px',
                        borderRadius: launcher === "icon_only" ? '50%' : '25px',
                    } : {
                        width: launcher === "icon_only" ? (buttonSize === 'Small' ? '45px' : buttonSize === 'Medium' ? '55px' : '65px') : 'auto',
                        height: launcher === "icon_only" ? (buttonSize === 'Small' ? '45px' : buttonSize === 'Medium' ? '55px' : '65px') : '45px',
                        padding: launcher === "icon_only" ? '0' : '0 20px',
                        borderRadius: launcher === "icon_only" ? '50%' : '25px',
                    }),
                    display: 'flex',
                    alignItems: 'center',
                    justifyContent: 'center',
                    gap: '8px',
                    boxShadow: '0 4px 12px rgba(0,0,0,0.15)',
                    cursor: 'pointer',
                    zIndex: 10,
                    transition: 'all 0.2s ease'
                }}
                onClick={() => {
                    if (isMobile) {
                        setIsChatOpenMobile(!isChatOpenMobile);
                    } else {
                        setIsChatOpenDesktop(!isChatOpenDesktop);
                    }
                }}
            >
                {showIcon && <div style={{ width: '28px', height: '28px', display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0, color: 'white' }}><LauncherIcon id={buttonIcon} /></div>}
                {showLabel && <span style={{ color: 'white', fontWeight: 600, fontSize: '14px', whiteSpace: 'nowrap' }}>{buttonLabel}</span>}
                {!isMobile && launcher === "icon" && <div className={styles.onlineStatusDot}></div>}
            </div>
        );
    }

    const handleSave = () => {
        let section = sectionMap[activeTab] || 'general';
        let payload: any = {};

        if (section === 'general') {
            payload = {
                displayOnStore: displayChatbox,
                chatFocusMode: focusMode,
                header: {
                    logo: logoUrl || "",
                    heading: heading,
                    description: description
                },
                language: language === 'English' ? 'en' : language,
                blocks: {
                    liveChat: showLiveChat,
                    contact: {
                        enabled: showContact,
                        chatStatusEnabled: chatStatus,
                        onlineStatusText: onlineStatus,
                        offlineStatusText: offlineStatus,
                        showOutsideWorkingHours: showOnlineOutside,
                        contactMethodsEnabled: showContactMethods,
                        contactButtonEnabled: true,
                        contactMethods: contactMethods.map(m => ({
                            type: m.type.toLowerCase(),
                            value: m.value
                        }))
                    },
                    orderTracking: showOrderTracking,
                    faqs: showFaqs,
                    categories: showCategories
                }
            };
        } else if (section === 'chatPage') {
            payload = {
                greeting: {
                    aiName: aiName,
                    welcomeMessage: welcomeMessage
                },
                handoverRule: handover === "Only when your team is online" ? "ONLY_ONLINE" : "ALWAYS",
                conversationStartersEnabled: conversationStarter,
                conversationStarters: questions.map((q, index) => ({
                    question: q.text,
                    answer: q.desc,
                    order: index + 1
                })),
                chatAvatar: chatAvatar === "Store branding" ? "STORE_BRANDING" : "TEAM_MEMBER",
                preChatForm: {
                    mode: preChatForm.toUpperCase().replace(/\s/g, '_'),
                    showAfterMessages: messagesAfter,
                    description: preChatDescription,
                    fields: contactFields.map(f => ({ label: f.label, required: f.required })),
                    marketingOptInEnabled: marketingOptIn,
                    disclaimerConsentEnabled: disclaimerConsent,
                    consentText: disclaimerText
                }
            };
        } else if (section === 'appearance') {
            payload = {
                brandColors: {
                    preset: isCustomColorTab ? "Custom" : ([
                        { name: "Cloud", color: "linear-gradient(135deg, #e2e8f0, #cbd5e1)" },
                        { name: "Midnight", color: "#1e293b" },
                        { name: "Volcano", color: "#7f1d1d" },
                        { name: "Amethyst", color: "#6d28d9" },
                        { name: "Cherry Blossom", color: "#fca5a5" },
                        { name: "Forest", color: "linear-gradient(135deg, #86efac, #22c55e)" },
                        { name: "Woodland", color: "#78350f" },
                        { name: "Sunset", color: "linear-gradient(135deg, #fbbf24, #f59e0b)" },
                        { name: "Twilight", color: "linear-gradient(135deg, #a5b4fc, #6366f1)" },
                        { name: "Ocean", color: "#0ea5e9" }
                    ].find(p => p.color === brandColor)?.name || "Custom"),
                    customColor: isCustomColorTab ? buttonBgColor : brandColor
                },
                chatboxButton: {
                    launcher: launcher,
                    buttonIcon: buttonIcon,
                    buttonLabel: heading,
                    buttonSize: buttonSize.toLowerCase(),
                    alignment: alignment.toLowerCase()
                },
                chatboxStyle: {
                    displayStyle: chatboxStyle === "Show navigation" ? "navigation" : "no_navigation",
                    mobileRatio: mobileRatio
                }
            };
        } else if (section === 'advanced') {
            payload = {
                visibility: {
                    displayDevices,
                    displayPages,
                    includedPages,
                    excludedPages,
                    customUrlPattern
                },
                continueAsEmail,
                customCss
            };
        }

        updateSectionMutation.mutate({ section, payload });
    };

    return (
        <div className={styles.container}>
            <header className={styles.header} style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
                <div>
                    <h1 className={styles.title}>Chatbot</h1>
                    <p className={styles.subtitle}>Set up your customer chat experience.</p>
                </div>
                <button 
                    className={styles.saveButton} 
                    onClick={handleSave}
                    disabled={updateSectionMutation.isPending}
                >
                    {updateSectionMutation.isPending ? "Saving..." : "Save changes"}
                </button>
            </header>

            <div className={styles.tabs}>
                {tabs.map((tab) => (
                    <div
                        key={tab}
                        className={`${styles.tab} ${activeTab === tab ? styles.tabActive : ""}`}
                        onClick={() => setActiveTab(tab)}
                    >
                        {tab}
                    </div>
                ))}
            </div>

            <main className={styles.mainSection}>
                <div className={styles.settingsColumn}>
                    {activeTab === "General" && (
                        <GeneralTab
                            displayChatbox={displayChatbox}
                            setDisplayChatbox={setDisplayChatbox}
                            focusMode={focusMode}
                            setFocusMode={setFocusMode}
                            setShowContactModal={setShowContactModal}
                            logoUrl={logoUrl}
                            setLogoUrl={setLogoUrl}
                            language={language}
                            setLanguage={setLanguage}
                            heading={heading}
                            setHeading={setHeading}
                            description={description}
                            setDescription={setDescription}
                            showLiveChat={showLiveChat}
                            setShowLiveChat={setShowLiveChat}
                            showContact={showContact}
                            setShowContact={setShowContact}
                            showOrderTracking={showOrderTracking}
                            setShowOrderTracking={setShowOrderTracking}
                            showFaqs={showFaqs}
                            setShowFaqs={setShowFaqs}
                            showCategories={showCategories}
                            setShowCategories={setShowCategories}
                            chatStatus={chatStatus}
                            setChatStatus={setChatStatus}
                            onlineStatus={onlineStatus}
                            setOnlineStatus={setOnlineStatus}
                            offlineStatus={offlineStatus}
                            setOfflineStatus={setOfflineStatus}
                            showOnlineOutside={showOnlineOutside}
                            setShowOnlineOutside={setShowOnlineOutside}
                            showContactMethods={showContactMethods}
                            setShowContactMethods={setShowContactMethods}
                            contactMethods={contactMethods}
                            setContactMethods={setContactMethods}
                        />
                    )}
                    {activeTab === "Chat Page" && (
                        <ChatPageTab
                            handover={handover}
                            setHandover={setHandover}
                            conversationStarter={conversationStarter}
                            setConversationStarter={setConversationStarter}
                            questions={questions}
                            setShowQuestionModal={setShowQuestionModal}
                            chatAvatar={chatAvatar}
                            setChatAvatar={setChatAvatar}
                            preChatForm={preChatForm}
                            setPreChatForm={setPreChatForm}
                            aiName={aiName}
                            setAiName={setAiName}
                            preChatDescription={preChatDescription}
                            setPreChatDescription={setPreChatDescription}
                            messagesAfter={messagesAfter}
                            setMessagesAfter={setMessagesAfter}
                            marketingOptIn={marketingOptIn}
                            setMarketingOptIn={setMarketingOptIn}
                            disclaimerConsent={disclaimerConsent}
                            setDisclaimerConsent={setDisclaimerConsent}
                            disclaimerText={disclaimerText}
                            setDisclaimerText={setDisclaimerText}
                            welcomeMessage={welcomeMessage}
                            setWelcomeMessage={setWelcomeMessage}
                            setQuestions={setQuestions}
                            setSelectedQuestion={setSelectedQuestion}
                            contactFields={contactFields}
                            setContactFields={setContactFields}
                        />
                    )}
                    {activeTab === "Appearance" && (
                        <AppearanceTab
                            brandColor={brandColor}
                            setBrandColor={setBrandColor}
                            isCustomColorTab={isCustomColorTab}
                            setIsCustomColorTab={setIsCustomColorTab}
                            isGradientHeader={isGradientHeader}
                            setIsGradientHeader={setIsGradientHeader}
                            headerColor1={headerColor1}
                            setHeaderColor1={setHeaderColor1}
                            headerColor2={headerColor2}
                            setHeaderColor2={setHeaderColor2}
                            headerTextColor={headerTextColor}
                            setHeaderTextColor={setHeaderTextColor}
                            chatboxTextColor={chatboxTextColor}
                            setChatboxTextColor={setChatboxTextColor}
                            buttonBgColor={buttonBgColor}
                            setButtonBgColor={setButtonBgColor}
                            buttonTextColor={buttonTextColor}
                            setButtonTextColor={setButtonTextColor}
                            alignment={alignment}
                            setAlignment={setAlignment}
                            chatboxStyle={chatboxStyle}
                            setChatboxStyle={setChatboxStyle}
                            launcher={launcher}
                            setLauncher={setLauncher}
                            buttonIcon={buttonIcon}
                            setButtonIcon={setButtonIcon}
                            buttonSize={buttonSize}
                            setButtonSize={setButtonSize}
                            mobileRatio={mobileRatio}
                            setMobileRatio={setMobileRatio}
                        />
                    )}
                    {activeTab === "Advanced" && (
                        <AdvancedTab 
                            displayDevices={displayDevices}
                            setDisplayDevices={setDisplayDevices}
                            displayPages={displayPages}
                            setDisplayPages={setDisplayPages}
                            includedPages={includedPages}
                            setIncludedPages={setIncludedPages}
                            excludedPages={excludedPages}
                            setExcludedPages={setExcludedPages}
                            customUrlPattern={customUrlPattern}
                            setCustomUrlPattern={setCustomUrlPattern}
                            continueAsEmail={continueAsEmail}
                            setContinueAsEmail={setContinueAsEmail}
                            customCss={customCss}
                            setCustomCss={setCustomCss}
                        />
                    )}
                </div>

                {showQuestionModal && (
                    <AddQuestionModal 
                        selectedQuestion={selectedQuestion}
                        onClose={() => {
                            setShowQuestionModal(false);
                            setSelectedQuestion(null);
                        }}
                        onSave={(data) => {
                            if (selectedQuestion) {
                                setQuestions(questions.map(q => q.id === selectedQuestion.id ? { ...q, ...data } : q));
                            } else {
                                setQuestions([...questions, { id: Date.now(), ...data }]);
                            }
                            setShowQuestionModal(false);
                            setSelectedQuestion(null);
                        }}
                    />
                )}

                <div className={styles.previewColumn}>
                    <div className={styles.previewCard}>
                        <div className={styles.previewHeader}>
                            <span className={styles.previewTitle}>Preview</span>
                            <div 
                                className={`${styles.desktopToggle} ${isPreviewDesktop ? styles.desktopToggleActive : ""}`}
                                onClick={() => setIsPreviewDesktop(!isPreviewDesktop)}
                                style={{ cursor: 'pointer' }}
                            >
                                <FiMonitor />
                                Desktop
                            </div>
                        </div>

                        <div className={styles.mockupContainer}>
                            {isPreviewDesktop ? (
                                <div className={styles.desktopMockup}>
                                    <div className={styles.desktopHeader}>
                                        <div className={styles.dotGroup}>
                                            <div className={styles.macDot} style={{ background: '#FF5F56' }}></div>
                                            <div className={styles.macDot} style={{ background: '#FFBD2E' }}></div>
                                            <div className={styles.macDot} style={{ background: '#27C93F' }}></div>
                                        </div>
                                        <div className={styles.desktopClose}>
                                            <FiX />
                                        </div>
                                    </div>
                                    <div className={styles.desktopBody}>
                                        <div className={styles.desktopContentArea}>
                                            {/* Screen Content Mockup */}
                                        </div>
                                        <div 
                                            className={styles.desktopLauncherWrapper} 
                                            style={{ [alignment === "Left" ? "left" : "right"]: '40px' }}
                                        >
                                            <LauncherBody />
                                        </div>

                                        {isChatOpenDesktop && (
                                            <div 
                                                className={styles.desktopChatboxOverlay} 
                                                style={{ [alignment === "Left" ? "left" : "right"]: '40px' }}
                                            >
                                                <ChatboxMockup />
                                            </div>
                                        )}
                                    </div>
                                </div>
                            ) : (
                                <div className={styles.mockupScreen} style={{ height: '600px', display: 'block' }}>
                                    <div style={{ height: '100%', background: '#f8fafc', position: 'relative' }}>
                                         {/* Browser-like mockup content for mobile background */}
                                         <div style={{ padding: '20px 16px', display: 'flex', justifyContent: 'space-between', borderBottom: '1px solid #f1f5f9' }}>
                                            <div style={{ display: 'flex', gap: '8px' }}>
                                                <FiMonitor size={16} />
                                                <span style={{ fontSize: '12px' }}>yourstore.com</span>
                                            </div>
                                        </div>
                                        
                                        {!isChatOpenMobile && <LauncherBody isMobile />}

                                        {isChatOpenMobile && (
                                            <div style={{ 
                                                position: 'absolute',
                                                bottom: 0,
                                                left: 0,
                                                right: 0,
                                                height: mobileRatio === 'full-screen' ? '100%' : mobileRatio,
                                                background: 'white',
                                                boxShadow: '0 -4px 12px rgba(0,0,0,0.05)',
                                                borderRadius: mobileRatio === 'full-screen' ? 0 : '16px 16px 0 0',
                                                overflow: 'hidden',
                                                display: 'flex',
                                                flexDirection: 'column'
                                            }}>
                                                <ChatboxMockup />
                                            </div>
                                        )}
                                    </div>
                                </div>
                            )}
                        </div>
                    </div>
                </div>
            </main>

            {showContactModal && (
                <ContactModal 
                    onClose={() => setShowContactModal(false)}
                    chatStatus={chatStatus}
                    setChatStatus={setChatStatus}
                    onlineStatus={onlineStatus}
                    setOnlineStatus={setOnlineStatus}
                    offlineStatus={offlineStatus}
                    setOfflineStatus={setOfflineStatus}
                    showOnlineOutside={showOnlineOutside}
                    setShowOnlineOutside={setShowOnlineOutside}
                    showContactMethods={showContactMethods}
                    setShowContactMethods={setShowContactMethods}
                    contactMethods={contactMethods}
                    setContactMethods={setContactMethods}
                />
            )}
        </div>
    );

    function ChatboxMockup() {
        return (
            <div style={{ display: 'flex', flexDirection: 'column', height: '100%', position: 'relative' }}>
                <div 
                    className={styles.mockupHeader} 
                    style={{ 
                        background: isCustomColorTab 
                            ? (isGradientHeader ? `linear-gradient(135deg, ${headerColor1}, ${headerColor2})` : headerColor1)
                            : brandColor,
                        color: isCustomColorTab ? headerTextColor : '#FFFFFF',
                        borderBottom: 'none'
                    }}
                >
                    <div style={{ display: 'flex', alignItems: 'center', gap: '8px' }}>
                        {activeTab === "Chat Page" && <FiChevronRight style={{ transform: "rotate(180deg)", color: isCustomColorTab ? headerTextColor : '#FFFFFF' }} />}
                        <div style={{ display: 'flex', flexDirection: 'column' }}>
                            <span style={{ fontSize: '12px', fontWeight: 800 }}>{aiName}</span>
                            {activeTab === "Chat Page" && (
                                <div style={{ display: 'flex', alignItems: 'center', gap: '4px', fontSize: '10px', opacity: 0.8 }}>
                                    <div style={{ width: '6px', height: '6px', background: '#10b981', borderRadius: '50%' }}></div>
                                    We are online
                                </div>
                            )}
                        </div>
                    </div>
                    <div style={{ display: 'flex', gap: '8px', alignItems: 'center' }}>
                        {activeTab === "General" ? <FiSearch /> : null}
                        <FiX 
                            onClick={(e) => {
                                e.stopPropagation();
                                if (isPreviewDesktop) {
                                    setIsChatOpenDesktop(false);
                                } else {
                                    setIsChatOpenMobile(false);
                                }
                            }} 
                            style={{ cursor: 'pointer' }} 
                        />
                    </div>
                </div>
                <div className={styles.mockupContent} style={{ 
                    color: isCustomColorTab ? chatboxTextColor : '#232323',
                    paddingBottom: chatboxStyle === "Show navigation" ? '60px' : '16px',
                    display: 'flex',
                    flexDirection: 'column'
                }}>
                    {previewSection === "Home" && (
                        <div style={{ display: 'flex', flexDirection: 'column', gap: '12px' }}>
                            {showLiveChat && (
                                <div className={styles.chatBubble} style={{ background: isCustomColorTab ? buttonBgColor : brandColor, color: isCustomColorTab ? buttonTextColor : '#FFFFFF' }}>
                                    <div style={{ display: 'flex', justifyContent: 'space-between' }}>
                                        <div className={styles.chatGreeting}>{heading}</div>
                                    </div>
                                    <div className={styles.chatSubtext} style={{ opacity: 0.9 }}>{description}</div>
                                </div>
                            )}

                            {showContact && (
                                <div className={styles.contactBox}>
                                    <span style={{ fontSize: '13px', fontWeight: 600 }}>Contact us</span>
                                    <div className={styles.statusIndicator}>
                                        <div className={styles.dot} style={{ background: chatStatus ? '#10b981' : '#9ca3af' }}></div>
                                        {chatStatus ? onlineStatus : offlineStatus}
                                    </div>
                                    <div style={{ display: 'flex', gap: '8px', flexWrap: 'wrap' }}>
                                        <button className={styles.editButton} style={{ background: isCustomColorTab ? buttonBgColor : brandColor, color: isCustomColorTab ? buttonTextColor : '#FFFFFF', padding: '6px 12px', borderRadius: '20px', display: 'flex', alignItems: 'center', gap: '6px', fontSize: '12px', flex: 1, justifyContent: 'center' }}>
                                            <FiSend /> Chat now
                                        </button>
                                        <div className={styles.iconCircle} style={{ background: '#fbbf24', width: '32px', height: '32px', borderRadius: '50%', display: 'flex', alignItems: 'center', justifyContent: 'center', color: 'white' }}>
                                            <FiMail />
                                        </div>
                                    </div>
                                </div>
                            )}

                            {showOrderTracking && (
                                <div className={styles.trackingCard}>
                                    <div className={styles.trackingText}>
                                        <span className={styles.trackingTitle}>Order tracking</span>
                                        <span className={styles.trackingSubtitle}>Track your orders</span>
                                    </div>
                                    <FiChevronRight color="#9ca3af" />
                                </div>
                            )}

                            {showFaqs && (
                                <div className={styles.inputGroup} style={{ gap: '12px' }}>
                                    <div className={styles.searchBar}>
                                        <span>Search for help</span>
                                        <FiSearch />
                                    </div>
                                    <div className={styles.faqList} style={{ display: 'flex', flexDirection: 'column', gap: '8px' }}>
                                        <div className={styles.faqItem}>
                                            <span>How long will it take to receive my order?</span>
                                            <FiChevronRight color="#9ca3af" />
                                        </div>
                                        <div className={styles.faqItem}>
                                            <span>How to track my order?</span>
                                            <FiChevronRight color="#9ca3af" />
                                        </div>
                                    </div>
                                </div>
                            )}
                        </div>
                    )}

                    {previewSection === "Message" && (
                        <div style={{ flex: 1, display: 'flex', flexDirection: 'column', padding: '0 8px', overflow: 'hidden' }}>
                            {(preChatForm === "Chat as guest" || (preChatForm === "Show both options" && !isChatStarted)) && !isChatStarted ? (
                                <div style={{ flex: 1, display: 'flex', flexDirection: 'column', padding: '0 16px', overflow: 'hidden' }}>
                                    <div style={{ display: 'flex', gap: '8px', marginBottom: '20px', marginTop: '16px' }}>
                                        <div style={{ width: '32px', height: '32px', background: '#ecfdf5', borderRadius: '50%', color: '#10b981', display: 'flex', alignItems: 'center', justifyContent: 'center', fontSize: '12px', fontWeight: 600, flexShrink: 0 }}>PR</div>
                                        <div style={{ background: '#f3f4f6', padding: '12px', borderRadius: '0 16px 16px 16px', fontSize: '13px' }}>
                                            {welcomeMessage.replace('{{customer_name}}', '')}
                                        </div>
                                    </div>

                                    <div style={{ background: '#f3f4f6', padding: '20px', borderRadius: '16px', display: 'flex', flexDirection: 'column', gap: '12px' }}>
                                        <p style={{ fontSize: '13px', color: '#374151', margin: 0 }}>{preChatDescription}</p>
                                        
                                        {contactFields.some(f => f.label === "Name") && (
                                            <input 
                                                type="text" 
                                                placeholder="Name" 
                                                value={previewName}
                                                onChange={(e) => setPreviewName(e.target.value)}
                                                style={{ 
                                                    width: '100%', 
                                                    padding: '10px 14px', 
                                                    borderRadius: '8px', 
                                                    border: '1px solid #e5e7eb',
                                                    fontSize: '13px' 
                                                }} 
                                            />
                                        )}

                                        {contactFields.some(f => f.label === "Email address") && (
                                            <input 
                                                type="email" 
                                                placeholder="johndoe@gmail.com" 
                                                value={previewEmail}
                                                onChange={(e) => setPreviewEmail(e.target.value)}
                                                style={{ 
                                                    width: '100%', 
                                                    padding: '10px 14px', 
                                                    borderRadius: '8px', 
                                                    border: '1px solid #e5e7eb',
                                                    fontSize: '13px' 
                                                }} 
                                            />
                                        )}

                                        {contactFields.some(f => f.label === "Phone number") && (
                                            <div style={{ display: 'flex', gap: '8px' }}>
                                                <div style={{ padding: '8px', border: '1px solid #e5e7eb', borderRadius: '8px', fontSize: '13px', background: 'white', display: 'flex', alignItems: 'center', gap: '4px' }}>
                                                    🇺🇸 <FiChevronRight style={{ transform: 'rotate(90deg)' }} size={12} />
                                                </div>
                                                <input 
                                                    type="tel" 
                                                    placeholder="+1" 
                                                    value={previewPhone}
                                                    onChange={(e) => setPreviewPhone(e.target.value)}
                                                    style={{ 
                                                        flex: 1, 
                                                        padding: '10px 14px', 
                                                        borderRadius: '8px', 
                                                        border: '1px solid #e5e7eb',
                                                        fontSize: '13px' 
                                                    }} 
                                                />
                                            </div>
                                        )}

                                        {disclaimerConsent && (
                                            <p style={{ fontSize: '11px', color: '#6b7280', margin: 0 }}>
                                                {disclaimerText || "By sending us a message, you agree to our privacy policy."}
                                            </p>
                                        )}
                                        <button 
                                            onClick={() => setIsChatStarted(true)}
                                            style={{ 
                                                width: '100%', 
                                                padding: '12px', 
                                                background: (isCustomColorTab ? buttonBgColor : brandColor), 
                                                color: (isCustomColorTab ? buttonTextColor : 'white'),
                                                borderRadius: '8px',
                                                fontWeight: 700,
                                                border: 'none',
                                                cursor: 'pointer',
                                                marginTop: '8px'
                                            }}
                                        >
                                            Start chat
                                        </button>
                                        {preChatForm === "Show both options" && (
                                            <button 
                                                onClick={() => {
                                                    setIsChatStarted(true);
                                                    setPreviewEmail("");
                                                    setPreviewName("");
                                                }}
                                                style={{ 
                                                    width: '100%', 
                                                    padding: '10px', 
                                                    background: 'transparent', 
                                                    color: '#64748b',
                                                    border: 'none',
                                                    cursor: 'pointer',
                                                    fontSize: '12px',
                                                    textDecoration: 'underline'
                                                }}
                                            >
                                                Chat anonymously
                                            </button>
                                        )}
                                    </div>
                                </div>
                            ) : (
                                <div style={{ flex: 1, display: 'flex', flexDirection: 'column' }}>
                                    <div style={{ display: 'flex', gap: '8px', marginBottom: '20px', marginTop: '16px' }}>
                                        {chatAvatar === "Store branding" && (
                                            <div style={{ width: '32px', height: '32px', background: isCustomColorTab ? headerColor1 : brandColor, borderRadius: '50%', color: 'white', display: 'flex', alignItems: 'center', justifyContent: 'center', fontSize: '12px', fontWeight: 600, flexShrink: 0 }}>
                                                {logoUrl ? <img src={logoUrl} alt="Logo" style={{ width: '100%', height: '100%', borderRadius: '50%', objectFit: 'cover' }} /> : "QI"}
                                            </div>
                                        )}
                                        {chatAvatar === "Team member profile" && (
                                            <div style={{ width: '32px', height: '32px', background: '#e5e7eb', borderRadius: '50%', color: '#4b5563', display: 'flex', alignItems: 'center', justifyContent: 'center', fontSize: '12px', fontWeight: 600, flexShrink: 0 }}><FiUsers size={14} /></div>
                                        )}
                                        <div style={{ background: '#f3f4f6', padding: '12px', borderRadius: '0 16px 16px 16px', fontSize: '13px', whiteSpace: 'pre-wrap' }}>
                                            {welcomeMessage.replace('{{customer_name}}', previewEmail ? previewEmail.split('@')[0] : '')}
                                        </div>
                                    </div>

                                    {isChatStarted && preChatForm !== "Chat as anonymous" && (
                                        <div style={{ alignSelf: 'flex-end', background: isCustomColorTab ? buttonBgColor : brandColor, color: 'white', padding: '10px 16px', borderRadius: '16px 16px 0 16px', fontSize: '13px', marginBottom: '16px' }}>
                                            {previewEmail}
                                        </div>
                                    )}

                                    {isChatStarted && preChatForm !== "Chat as anonymous" && (
                                        <div style={{ display: 'flex', gap: '8px' }}>
                                            <div style={{ width: '32px', height: '32px', background: '#ecfdf5', borderRadius: '50%', color: '#10b981', display: 'flex', alignItems: 'center', justifyContent: 'center', fontSize: '12px', fontWeight: 600, flexShrink: 0 }}>PR</div>
                                            <div style={{ background: '#f3f4f6', padding: '12px', borderRadius: '0 16px 16px 16px', fontSize: '13px' }}>
                                                Thank you for reaching out. We've received your information and will be with you in a moment.
                                            </div>
                                        </div>
                                    )}

                                    {conversationStarter && (
                                        <div style={{ display: 'flex', flexDirection: 'column', gap: '8px', alignItems: 'flex-end', marginTop: 'auto', marginBottom: '16px' }}>
                                            {questions.map((q) => (
                                                <div key={q.id} style={{ background: 'white', border: '1px solid #e5e7eb', color: isCustomColorTab ? buttonBgColor : brandColor, borderRadius: '20px', padding: '6px 16px', fontSize: '12px', boxShadow: '0 2px 4px rgba(0,0,0,0.05)' }}>
                                                    {q.text}
                                                </div>
                                            ))}
                                        </div>
                                    )}
                                    <div style={{ border: '1px solid #e5e7eb', borderRadius: '24px', padding: '8px 16px', display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: '16px', background: '#f8fafc' }}>
                                        <span style={{ color: '#9ca3af', fontSize: '13px' }}>Type your message</span>
                                        <div style={{ display: 'flex', gap: '8px', alignItems: 'center' }}>
                                            <span style={{ cursor: 'pointer', fontSize: '16px' }}>😊</span>
                                            <FiSend style={{ cursor: 'pointer', color: isCustomColorTab ? buttonBgColor : brandColor }} />
                                        </div>
                                    </div>
                                </div>
                            )}
                        </div>
                    )}

                    {previewSection === "Track" && (
                        <div style={{ padding: '4px 12px', display: 'flex', flexDirection: 'column', gap: '16px' }}>
                            <div style={{ display: 'flex', borderBottom: '1px solid #e5e7eb' }}>
                                <div style={{ padding: '8px 12px', fontSize: '13px', borderBottom: `2px solid ${brandColor}`, fontWeight: 600 }}>Order number</div>
                                <div style={{ padding: '8px 12px', fontSize: '13px', color: '#6b7280' }}>Tracking number</div>
                            </div>
                            <div className={styles.inputGroup}>
                                <label style={{ fontSize: '13px', color: '#4b5563', fontWeight: 500 }}>Order number</label>
                                <div style={{ border: '1px solid #e5e7eb', borderRadius: '8px', padding: '10px 12px', background: '#f9fafb', color: '#9ca3af', fontSize: '14px' }}>e.g. 1001</div>
                            </div>
                            <div style={{ display: 'flex', flexDirection: 'column', gap: '12px' }}>
                                <div style={{ display: 'flex', alignItems: 'center', gap: '8px' }}>
                                    <div style={{ width: '16px', height: '16px', border: `2px solid ${brandColor}`, borderRadius: '50%', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
                                        <div style={{ width: '8px', height: '8px', background: brandColor, borderRadius: '50%' }}></div>
                                    </div>
                                    <span style={{ fontSize: '13px' }}>Email address</span>
                                    <div style={{ width: '16px', height: '16px', border: '2px solid #d1d5db', borderRadius: '50%', marginLeft: '20px' }}></div>
                                    <span style={{ fontSize: '13px' }}>Phone number</span>
                                </div>
                                <div style={{ border: '1px solid #e5e7eb', borderRadius: '8px', padding: '10px 12px', background: '#f9fafb', color: '#9ca3af', fontSize: '14px' }}>example@gmail.com</div>
                            </div>
                            <button style={{ background: isCustomColorTab ? buttonBgColor : brandColor, color: isCustomColorTab ? buttonTextColor : 'white', border: 'none', borderRadius: '8px', padding: '12px', fontWeight: 600, fontSize: '14px', marginTop: '8px' }}>
                                Track
                            </button>
                        </div>
                    )}

                    {previewSection === "Help" && (
                        <div style={{ padding: '4px 12px', display: 'flex', flexDirection: 'column', gap: '16px' }}>
                            <div className={styles.searchBar}>
                                <span>Search for help</span>
                                <FiSearch />
                            </div>
                            <div className={styles.inputGroup}>
                                <p style={{ fontSize: '14px', fontWeight: 600, marginBottom: '12px' }}>Categories</p>
                                <div className={styles.faqList}>
                                    <div className={styles.faqItem}>
                                        <div style={{ display: 'flex', alignItems: 'center', gap: '12px' }}>
                                            <div style={{ width: '32px', height: '32px', background: '#f3f4f6', borderRadius: '8px', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
                                                <svg viewBox="0 0 24 24" width="18" height="18" fill="#4B5563"><path d="M7 18c-1.1 0-1.99.9-1.99 2S5.9 22 7 22s2-.9 2-2-.9-2-2-2zM1 2v2h2l3.6 7.59-1.35 2.45c-.16.28-.25.61-.25.96 0 1.1.9 2 2 2h12v-2H7.42c-.14 0-.25-.11-.25-.25l.03-.12.9-1.63h7.45c.75 0 1.41-.41 1.75-1.03l3.58-6.49c.08-.14.12-.31.12-.48 0-.55-.45-1-1-1H5.21l-.94-2H1zm16 16c-1.1 0-1.99.9-1.99 2s.89 2 1.99 2 2-.9 2-2-.9-2-2-2z"/></svg>
                                            </div>
                                            <div style={{ display: 'flex', flexDirection: 'column' }}>
                                                <span style={{ fontSize: '13px', fontWeight: 600 }}>Order & Shipping</span>
                                                <span style={{ fontSize: '11px', color: '#6b7280' }}>4 Articles</span>
                                            </div>
                                        </div>
                                        <FiChevronRight color="#9ca3af" />
                                    </div>
                                    <div className={styles.faqItem}>
                                        <div style={{ display: 'flex', alignItems: 'center', gap: '12px' }}>
                                            <div style={{ width: '32px', height: '32px', background: '#f3f4f6', borderRadius: '8px', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
                                                <svg viewBox="0 0 24 24" width="18" height="18" fill="#4B5563"><path d="M19 8l-4 4h3c0 3.31-2.69 6-6 6-1.01 0-1.97-.25-2.8-.7l-1.46 1.46C8.97 19.54 10.41 20 12 20c4.42 0 8-3.58 8-8h3l-4-4zM6 12c0-3.31 2.69-6 6-6 1.01 0 1.97.25 2.8.7l1.46-1.46C15.03 4.46 13.59 4 12 4c-4.42 0-8 3.58-8 8H1l4 4 4-4H6z"/></svg>
                                            </div>
                                            <div style={{ display: 'flex', flexDirection: 'column' }}>
                                                <span style={{ fontSize: '13px', fontWeight: 600 }}>Exchange & Return</span>
                                                <span style={{ fontSize: '11px', color: '#6b7280' }}>2 Articles</span>
                                            </div>
                                        </div>
                                        <FiChevronRight color="#9ca3af" />
                                    </div>
                                </div>
                            </div>
                        </div>
                    )}
                </div>

                {chatboxStyle === "Show navigation" && (
                    <div style={{ 
                        padding: '8px 12px', 
                        display: 'flex', 
                        justifyContent: 'space-between', 
                        borderTop: '1px solid #f1f5f9',
                        background: '#ffffff',
                        position: 'absolute',
                        bottom: 0,
                        left: 0,
                        right: 0
                    }}>
                        {[
                            { name: 'Home', icon: <FiHome /> },
                            { name: 'Message', icon: <FiMessageCircle /> },
                            { name: 'Track', icon: <FiTruck /> },
                            { name: 'Help', icon: <FiHelpCircle /> }
                        ].map((item, idx) => (
                            <div 
                                key={idx} 
                                onClick={() => setPreviewSection(item.name)}
                                style={{ 
                                    display: 'flex', 
                                    flexDirection: 'column', 
                                    alignItems: 'center', 
                                    gap: '2px', 
                                    color: previewSection === item.name ? (isCustomColorTab ? buttonBgColor : brandColor) : '#94a3b8', 
                                    cursor: 'pointer',
                                    borderTop: previewSection === item.name ? `2px solid ${isCustomColorTab ? buttonBgColor : brandColor}` : 'none',
                                    marginTop: previewSection === item.name ? '-8px' : '0',
                                    paddingTop: previewSection === item.name ? '6px' : '0'
                                }}
                            >
                                <div style={{ fontSize: '18px' }}>{item.icon}</div>
                                <span style={{ fontSize: '10px', fontWeight: 500 }}>{item.name}</span>
                            </div>
                        ))}
                    </div>
                )}
            </div>
        );
    }
}
