import React, { useState, useEffect } from "react";
import { FiSearch, FiArrowLeft, FiChevronDown, FiChevronRight, FiLink2, FiCopy, FiAlignLeft, FiAlignCenter, FiAlignRight, FiMonitor, FiPlus, FiTrash2, FiEdit2, FiX } from "react-icons/fi";
import styles from "../../chatbot/components/ChatbotSettings.module.css";
import { useDebounce } from "use-debounce";

interface FAQsBlocksTabProps {
    blocksView: string;
    setBlocksView: (view: string) => void;
    FAQIllustration: string;
    activeCategories: string[];
    toggleCategory: (cat: string) => void;
    setIsBrowseFaqOpen: (open: boolean) => void;
    blocks: any[];
    onUpdateBlocks: (newBlocks: any[]) => void;
    onCreateBlock: (payload: any[]) => void;
    onDeleteBlock: (id: string) => void;
    categories: any[];
}

const defaultBlockTemplate = {
    internal_id: `block_${Date.now()}`,
    is_active: true,
    general: {
        public_block_id: `CHATTY-${Math.floor(1000000 + Math.random() * 9000000)}`,
        block_name: "FAQ block",
        heading: "Frequently Asked Questions",
        subheading: "Got a question? We are here to answer!"
    },
    configuration: {
        dont_categorize_faqs: true,
        selected_faq_ids: []
    },
    style: {
        heading_size: "small",
        heading_alignment: "left",
        card_corner_radius: 12,
        colors: {
            title: "#383838",
            subtitle: "#616161",
            question_text: "#1F2937",
            question_background: "#F6F7F8",
            block_background: "#FFFFFF"
        }
    },
    generated_script: ""
};

export function FAQsBlocksTab({
    blocksView,
    setBlocksView,
    FAQIllustration,
    activeCategories,
    toggleCategory,
    setIsBrowseFaqOpen,
    blocks,
    onUpdateBlocks,
    onCreateBlock,
    onDeleteBlock,
    categories
}: FAQsBlocksTabProps) {
    const [searchTerm, setSearchTerm] = useState("");
    const [draftBlock, setDraftBlock] = useState<any>(null);
    const [isEditingNew, setIsEditingNew] = useState(false);
    const [deleteModalId, setDeleteModalId] = useState<string | null>(null);

    const [localBlocksList, setLocalBlocksList] = useState(blocks || []);

    useEffect(() => {
        if (blocks && blocks.length >= 0) {
            setLocalBlocksList(blocks);
        }
    }, [blocks]);

    // Filter blocks list safely, handling older or defective payloads
    const filteredBlocks = localBlocksList.filter(b => b?.general?.block_name?.toLowerCase()?.includes(searchTerm.toLowerCase()) || false);

    const handleCreateBlock = () => {
        const newBlock = JSON.parse(JSON.stringify(defaultBlockTemplate));
        newBlock.internal_id = `block_${Date.now()}`;
        newBlock.generated_script = `<div class="Avada-Faqs-Block-Container" data-chatty-faq-block-id="${newBlock.general.public_block_id}"></div>\n<script src="https://cdn-fe.chatty.net/scripttag/chatty-faq-block.min.js" defer></script>`;

        setDraftBlock(newBlock);
        setIsEditingNew(true);
        setBlocksView("add");
    };

    const handleEditBlock = (id: string) => {
        const b = localBlocksList.find(x => x.internal_id === id);
        if (b) {
            setDraftBlock(JSON.parse(JSON.stringify(b)));
            setIsEditingNew(false);
            setBlocksView("add");
        }
    };

    const handleDeleteBlock = (id: string) => {
        setDeleteModalId(id);
    };

    const confirmDelete = () => {
        if (!deleteModalId) return;
        const newArr = localBlocksList.filter(b => b.internal_id !== deleteModalId);
        setLocalBlocksList(newArr);
        onDeleteBlock(deleteModalId);
        setDeleteModalId(null);
    };

    if (blocksView === "list") {
        return (
            <div style={{ padding: '0' }}>
                <div style={{ background: 'white', borderRadius: '12px', padding: '20px', marginBottom: '20px', display: 'flex', justifyContent: 'space-between', alignItems: 'center', border: '1px solid #eaeaea' }}>
                    <div>
                        <h3 style={{ fontSize: '15px', fontWeight: 600, margin: '0 0 4px', color: '#111' }}>FAQs block</h3>
                        <p style={{ margin: 0, fontSize: '13px', color: '#666' }}>Add an FAQs block to display specific FAQs on any pages of your store</p>
                    </div>
                    <button onClick={handleCreateBlock} style={{ background: '#222', color: 'white', border: 'none', borderRadius: '6px', padding: '8px 16px', fontSize: '13px', fontWeight: 500, cursor: 'pointer' }}>Add block</button>
                </div>

                {localBlocksList.length === 0 ? (
                    <div className={styles.blocksEmptyState} style={{ background: 'white', borderRadius: '12px', border: '1px solid #eaeaea', padding: '40px' }}>
                        <div className={styles.faqIllustrationBox}>
                            <img src={FAQIllustration} alt="FAQ Illustration" />
                        </div>
                        <h3 className={styles.cardSectionTitle} style={{ fontSize: '18px', marginBottom: '8px' }}>Add FAQs Block</h3>
                        <p className={styles.toggleDesc} style={{ maxWidth: '400px', margin: '0 0 24px' }}>
                            Add an FAQs block to display specific FAQs on any pages of your store.
                        </p>
                        <button
                            className={styles.syncBtn}
                            style={{ background: '#7c3aed', padding: '12px 32px' }}
                            onClick={handleCreateBlock}
                        >
                            Add block
                        </button>
                    </div>
                ) : (
                    <div style={{ background: 'white', borderRadius: '12px', border: '1px solid #eaeaea', overflow: 'hidden' }}>
                        <div style={{ padding: '16px', background: '#fcfcfc', borderBottom: '1px solid #eaeaea' }}>
                            <div style={{ position: 'relative', border: '1px solid #eaeaea', borderRadius: '6px', overflow: 'hidden', background: 'white' }}>
                                <FiSearch style={{ position: 'absolute', left: '12px', top: '10px', color: '#999' }} />
                                <input type="text" placeholder="Search by block name" value={searchTerm} onChange={e => setSearchTerm(e.target.value)} style={{ width: '100%', padding: '8px 8px 8px 36px', border: 'none', fontSize: '13px', outline: 'none' }} />
                            </div>
                        </div>

                        <table style={{ width: '100%', borderCollapse: 'collapse', textAlign: 'left', fontSize: '13px' }}>
                            <thead>
                                <tr style={{ borderBottom: '1px solid #eaeaea', color: '#666' }}>
                                    <th style={{ padding: '12px 16px', fontWeight: 500 }}>Block ID</th>
                                    <th style={{ padding: '12px 16px', fontWeight: 500 }}>Block name</th>
                                    <th style={{ padding: '12px 16px', fontWeight: 500 }}>Number of FAQs</th>
                                    <th style={{ padding: '12px 16px', fontWeight: 500 }}>Display condition</th>
                                    <th style={{ padding: '12px 16px', fontWeight: 500 }}>Status</th>
                                    <th style={{ padding: '12px 16px', fontWeight: 500 }}>Updated at</th>
                                    <th style={{ padding: '12px 16px', fontWeight: 500 }}></th>
                                </tr>
                            </thead>
                            <tbody>
                                {filteredBlocks.map(block => (
                                    <tr key={block.internal_id} style={{ borderBottom: '1px solid #eaeaea' }}>
                                        <td style={{ padding: '12px 16px' }}>
                                            <div style={{ display: 'flex', alignItems: 'center', gap: '8px' }}>
                                                {block?.general?.public_block_id || 'N/A'}
                                                <FiCopy style={{ cursor: 'pointer', color: '#666' }} onClick={() => navigator.clipboard.writeText(block?.general?.public_block_id || '')} />
                                            </div>
                                        </td>
                                        <td style={{ padding: '12px 16px' }}>{block?.general?.block_name || 'Unnamed Block'}</td>
                                        <td style={{ padding: '12px 16px' }}>{block?.configuration?.selected_faq_ids?.length || 1}</td>
                                        <td style={{ padding: '12px 16px' }}>Specific products</td>
                                        <td style={{ padding: '12px 16px' }}>
                                            <span style={{
                                                background: block.is_active ? '#edf7ed' : '#f3f4f6',
                                                color: block.is_active ? '#1e4620' : '#8c8c8c',
                                                padding: '4px 8px', borderRadius: '12px', fontSize: '11px', fontWeight: 500
                                            }}>
                                                {block.is_active ? 'Active' : 'Inactive'}
                                            </span>
                                        </td>
                                        <td style={{ padding: '12px 16px', color: '#333' }}>03 Apr 2026 17:26</td>
                                        <td style={{ padding: '12px 16px', textAlign: 'right' }}>
                                            <div style={{ display: 'flex', gap: '12px', justifyContent: 'flex-end', color: '#666' }}>
                                                <FiEdit2 style={{ cursor: 'pointer' }} onClick={() => handleEditBlock(block.internal_id)} />
                                                <FiTrash2 style={{ cursor: 'pointer' }} onClick={() => handleDeleteBlock(block.internal_id)} />
                                            </div>
                                        </td>
                                    </tr>
                                ))}
                            </tbody>
                        </table>

                        {/* Pagination */}
                        <div style={{ padding: '16px', display: 'flex', justifyContent: 'center', alignItems: 'center', borderTop: '1px solid #eaeaea', gap: '16px', fontSize: '13px', position: 'relative', background: '#fcfcfc' }}>
                            <div style={{ display: 'flex', alignItems: 'center', gap: '8px' }}>
                                <button style={{ border: 'none', background: '#eaeaea', borderRadius: '4px', padding: '4px 8px', color: '#fff', cursor: 'not-allowed' }}>&lt;</button>
                                <span style={{ color: '#666' }}>Page 1 / 1</span>
                                <button style={{ border: 'none', background: '#eaeaea', borderRadius: '4px', padding: '4px 8px', color: '#fff', cursor: 'not-allowed' }}>&gt;</button>
                            </div>
                            <div style={{ display: 'flex', alignItems: 'center', gap: '8px', position: 'absolute', right: '16px' }}>
                                <span style={{ color: '#666' }}>Items per page</span>
                                <select style={{ border: '1px solid #999', borderRadius: '4px', padding: '4px 8px', outline: 'none', background: 'transparent' }}>
                                    <option>10</option>
                                </select>
                            </div>
                        </div>
                    </div>
                )}

                {/* Custom Delete Modal */}
                {deleteModalId && (
                    <div className={styles.modalOverlay} onClick={() => setDeleteModalId(null)}>
                        <div 
                            className={styles.modalContent} 
                            style={{ width: '500px', borderRadius: '12px', padding: 0 }} 
                            onClick={e => e.stopPropagation()}
                        >
                            <div className={styles.modalHeader} style={{ padding: '20px 24px', borderBottom: '1px solid #e5e7eb', display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
                                <h2 style={{ fontSize: '16px', fontWeight: 600, color: '#111827', margin: 0 }}>
                                    Delete FAQ block?
                                </h2>
                                <button className={styles.closeButton} onClick={() => setDeleteModalId(null)} style={{ border: 'none', background: 'transparent', cursor: 'pointer', padding: 0, display: 'flex' }}>
                                    <FiX size={20} color="#6b7280" />
                                </button>
                            </div>
                            
                            <div className={styles.modalBody} style={{ padding: '24px', fontSize: '14px', color: '#4b5563', lineHeight: '1.5' }}>
                                <p style={{ margin: 0 }}>Are you sure you want to delete this block?</p>
                            </div>
                            
                            <div style={{ display: 'flex', justifyContent: 'flex-end', gap: '12px', padding: '16px 24px', borderTop: '1px solid #e5e7eb', background: '#fff', borderBottomLeftRadius: '12px', borderBottomRightRadius: '12px' }}>
                                <button 
                                    onClick={() => setDeleteModalId(null)} 
                                    style={{ padding: '8px 16px', borderRadius: '8px', border: '1px solid #d1d5db', background: 'white', color: '#374151', fontSize: '14px', fontWeight: 500, cursor: 'pointer' }}
                                >
                                    Cancel
                                </button>
                                <button 
                                    onClick={confirmDelete} 
                                    style={{ padding: '8px 16px', borderRadius: '8px', border: 'none', background: '#dc2626', color: 'white', fontSize: '14px', fontWeight: 500, cursor: 'pointer' }}
                                >
                                    Delete
                                </button>
                            </div>
                        </div>
                    </div>
                )}
            </div>
        );
    }

    if (blocksView === "add" && draftBlock) {
        return (
            <BlockEditor
                block={draftBlock}
                isEditingNew={isEditingNew}
                onSaveBlock={(savedBlock: any) => {
                    let newArr = [];
                    if (isEditingNew) {
                        newArr = [...localBlocksList, savedBlock];
                        onCreateBlock([savedBlock]);
                    } else {
                        newArr = localBlocksList.map(b => b.internal_id === savedBlock.internal_id ? savedBlock : b);
                        onUpdateBlocks([savedBlock]);
                    }
                    setLocalBlocksList(newArr);
                    setBlocksView("list");
                }}
                setBlocksView={setBlocksView}
                activeCategories={activeCategories}
                toggleCategory={toggleCategory}
                setIsBrowseFaqOpen={setIsBrowseFaqOpen}
                categories={categories}
            />
        );
    }

    return null;
}

// Separated component for manual saving of Block config
function BlockEditor({ block, isEditingNew, onSaveBlock, setBlocksView, activeCategories, toggleCategory, setIsBrowseFaqOpen, categories }: any) {
    const [localBlock, setLocalBlock] = useState(block);
    // No more useDebounce. Manual save pushes state up.
    const handleSave = () => {
        onSaveBlock(localBlock);
    };

    const updateNested = (path: string[], value: any) => {
        setLocalBlock((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;
        });
    };

    // Calculate dynamic styles for preview with fallbacks
    const s = localBlock?.style || defaultBlockTemplate.style;
    const c = localBlock?.style?.colors || defaultBlockTemplate.style.colors;

    const renderPreviewFAQs = () => {
        // Find selected FAQs or just mock 2 rows
        // If not categorize, mock list
        return (
            <div style={{ marginTop: '16px' }}>
                {[1, 2].map(i => (
                    <div key={i} style={{
                        display: 'flex', justifyContent: 'space-between', padding: '12px 16px',
                        marginBottom: '8px', background: c.question_background,
                        borderRadius: `${s.card_corner_radius}px`, color: c.question_text,
                        fontSize: '11px', fontWeight: 500
                    }}>
                        <div>{i === 1 ? 'How long will it take to receive my order?' : 'How to track my order?'}</div>
                        <div><FiChevronDown /></div>
                    </div>
                ))}
            </div>
        );
    };

    return (
        <div className={styles.faqPageLayout}>
            <div className={styles.settingsPanel}>
                <div className={styles.addBlockViewHeader} style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
                    <div style={{ display: 'flex', alignItems: 'center', gap: '12px' }}>
                        <button className={styles.backBtn} onClick={() => setBlocksView("list")}>
                            <FiArrowLeft />
                        </button>
                        <div className={styles.addBlockTitleGroup}>
                            <h2>{isEditingNew ? "Add FAQs Block" : "Edit FAQs Block"}</h2>
                            <p>Show relevant FAQs on any page.</p>
                        </div>
                    </div>
                    <button onClick={handleSave} style={{ background: '#222', color: 'white', border: 'none', borderRadius: '6px', padding: '8px 16px', fontSize: '13px', fontWeight: 500, cursor: 'pointer' }}>
                        Save block
                    </button>
                </div>

                <div className={styles.appearanceCard} style={{ padding: '16px 24px', marginBottom: '16px' }}>
                    <div className={styles.toggleRow}>
                        <span style={{ fontSize: '14px', fontWeight: 600 }}>Display FAQs block</span>
                        <label className={styles.switch}>
                            <input type="checkbox" checked={localBlock.is_active} onChange={e => updateNested(['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>
                        {activeCategories.includes("General") ? <FiChevronDown /> : <FiChevronRight />}
                    </div>
                    {activeCategories.includes("General") && (
                        <div className={styles.collapsibleContent}>
                            <div className={styles.labelGroup} style={{ marginBottom: '16px' }}>
                                <div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: '8px' }}>
                                    <label className={styles.settingsInputLabel}>Block ID</label>
                                    <a href="#" style={{ fontSize: '12px', color: '#7c3aed', display: 'flex', alignItems: 'center', gap: '4px' }}>
                                        Go to theme <FiLink2 size={12} />
                                    </a>
                                </div>
                                <div className={styles.idBox}>
                                    <span>{localBlock?.general?.public_block_id}</span>
                                    <FiCopy className={styles.copyIcon} onClick={() => navigator.clipboard.writeText(localBlock?.general?.public_block_id || '')} />
                                </div>
                                <p style={{ fontSize: '11px', color: '#6b7280', marginTop: '8px' }}>Paste this block ID into your theme editor to display the FAQs block.</p>
                            </div>
                            <div className={styles.labelGroup} style={{ marginBottom: '16px' }}>
                                <label className={styles.settingsInputLabel}>Block name</label>
                                <p style={{ fontSize: '11px', color: '#6b7280', margin: '4px 0 8px' }}>Enter a name to identify this block. Only visible in admin</p>
                                <input type="text" className={styles.chatInput} style={{ textAlign: 'left', width: '100%', maxWidth: '100%' }} value={localBlock?.general?.block_name || ''} onChange={e => updateNested(['general', 'block_name'], e.target.value)} />
                            </div>
                            <div className={styles.labelGroup} style={{ marginBottom: '16px' }}>
                                <label className={styles.settingsInputLabel}>Heading</label>
                                <input type="text" className={styles.chatInput} style={{ textAlign: 'left', width: '100%', maxWidth: '100%', marginTop: '8px' }} value={localBlock?.general?.heading || ''} onChange={e => updateNested(['general', 'heading'], e.target.value)} />
                            </div>
                            <div className={styles.labelGroup}>
                                <label className={styles.settingsInputLabel}>Subheading</label>
                                <textarea className={styles.instructionTextArea} style={{ marginTop: '8px', minHeight: '60px' }} value={localBlock?.general?.subheading || ''} onChange={e => updateNested(['general', 'subheading'], e.target.value)} />
                            </div>
                        </div>
                    )}
                </div>

                {/* FAQs Section */}
                <div className={styles.collapsibleCard}>
                    <div className={styles.collapsibleHeader} onClick={() => toggleCategory("FAQs")}>
                        <span>FAQs</span>
                        {activeCategories.includes("FAQs") ? <FiChevronDown /> : <FiChevronRight />}
                    </div>
                    {activeCategories.includes("FAQs") && (
                        <div className={styles.collapsibleContent}>
                            <div className={styles.toggleRow} style={{ marginBottom: '16px' }}>
                                <div style={{ display: 'flex', flexDirection: 'column' }}>
                                    <span style={{ fontSize: '13px', fontWeight: 600 }}>Don't categorize FAQs</span>
                                    <span style={{ fontSize: '11px', color: '#6b7280' }}>Enable to display all FAQs without categorizing them</span>
                                </div>
                                <label className={styles.switch}>
                                    <input type="checkbox" checked={localBlock?.configuration?.dont_categorize_faqs || false} onChange={e => updateNested(['configuration', 'dont_categorize_faqs'], e.target.checked)} />
                                    <span className={styles.slider}></span>
                                </label>
                            </div>
                            <div style={{ position: 'relative' }} onClick={() => setIsBrowseFaqOpen(true)}>
                                <FiSearch style={{ position: 'absolute', left: '12px', top: '12px', color: '#9ca3af' }} />
                                <input
                                    type="text"
                                    className={styles.chatInput}
                                    placeholder="Search FAQs (Browse)"
                                    readOnly
                                    style={{ paddingLeft: '40px', textAlign: 'left', maxWidth: '100%', cursor: 'pointer' }}
                                />
                                <button style={{ position: 'absolute', right: '8px', top: '8px', padding: '4px 12px', border: '1px solid #e5e7eb', borderRadius: '4px', background: 'white', fontSize: '12px', fontWeight: 600 }}>Browse</button>
                            </div>
                        </div>
                    )}
                </div>

                {/* Display condition Section */}
                <div className={styles.collapsibleCard}>
                    <div className={styles.collapsibleHeader} onClick={() => toggleCategory("Condition")}>
                        <span>Display condition</span>
                        {activeCategories.includes("Condition") ? <FiChevronDown /> : <FiChevronRight />}
                    </div>
                    {activeCategories.includes("Condition") && (
                        <div className={styles.collapsibleContent}>
                            <p style={{ fontSize: '12px', color: '#6b7280' }}>(Not fully implemented in dummy. Shows options mapping to page inclusion rules in real app.)</p>
                        </div>
                    )}
                </div>

                {/* Appearance Section */}
                <div className={styles.collapsibleCard}>
                    <div className={styles.collapsibleHeader} onClick={() => toggleCategory("Appearance")}>
                        <span>Appearance</span>
                        {activeCategories.includes("Appearance") ? <FiChevronDown /> : <FiChevronRight />}
                    </div>
                    {activeCategories.includes("Appearance") && (
                        <div className={styles.collapsibleContent}>
                            <div className={styles.labelGroup} style={{ marginBottom: '20px' }}>
                                <label className={styles.settingsInputLabel}>Heading size</label>
                                <div className={styles.selectionButtonGroup} style={{ marginTop: '8px' }}>
                                    {['small', 'medium', 'large'].map(sz => (
                                        <button
                                            key={sz}
                                            className={`${styles.selectionButton} ${s.heading_size === sz ? styles.selectionButtonActive : ''}`}
                                            onClick={() => updateNested(['style', 'heading_size'], sz)}
                                            style={{ textTransform: 'capitalize' }}
                                        >
                                            {sz}
                                        </button>
                                    ))}
                                </div>
                            </div>
                            <div className={styles.labelGroup} style={{ marginBottom: '20px' }}>
                                <label className={styles.settingsInputLabel}>Heading alignment</label>
                                <div className={styles.alignGrid} style={{ marginTop: '8px' }}>
                                    {[
                                        { val: 'left', icon: <FiAlignLeft /> },
                                        { val: 'center', icon: <FiAlignCenter /> },
                                        { val: 'right', icon: <FiAlignRight /> }
                                    ].map(al => (
                                        <div
                                            key={al.val}
                                            className={`${styles.alignBtn} ${s.heading_alignment === al.val ? styles.alignBtnActive : ''}`}
                                            onClick={() => updateNested(['style', 'heading_alignment'], al.val)}
                                        >
                                            {al.icon}
                                        </div>
                                    ))}
                                </div>
                            </div>
                            <div className={styles.labelGroup} style={{ marginBottom: '20px' }}>
                                <label className={styles.settingsInputLabel}>Card corner radius</label>
                                <div style={{ display: 'flex', alignItems: 'center', gap: '16px', marginTop: '8px' }}>
                                    <input
                                        type="range"
                                        min="0" max="32"
                                        value={s.card_corner_radius}
                                        onChange={e => updateNested(['style', 'card_corner_radius'], parseInt(e.target.value))}
                                        style={{ flex: 1 }}
                                    />
                                    <div className={styles.inputWithUnit} style={{ width: '80px', marginTop: 0 }}>
                                        <input type="number" className={styles.chatInput} style={{ textAlign: 'center', padding: '6px' }} value={s.card_corner_radius} onChange={e => updateNested(['style', 'card_corner_radius'], parseInt(e.target.value))} />
                                        <span className={styles.unitLabel} style={{ right: '8px' }}>px</span>
                                    </div>
                                </div>
                            </div>
                            <div className={styles.colorSection} style={{ marginTop: '24px' }}>
                                <label className={styles.settingsInputLabel}>Colors</label>
                                <div className={styles.customColorGrid} style={{ marginTop: '12px', display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '12px' }}>
                                    {[
                                        { label: "Title", key: "title" },
                                        { label: "Subtitle", key: "subtitle" },
                                        { label: "Question text", key: "question_text" },
                                        { label: "Question background", key: "question_background" },
                                        { label: "Block background", key: "block_background" }
                                    ].map(clr => (
                                        <div key={clr.label} className={styles.colorPickerItem} style={{ display: 'flex', alignItems: 'center', gap: '8px' }}>
                                            <input
                                                type="color"
                                                value={(c as any)[clr.key]}
                                                onChange={e => updateNested(['style', 'colors', clr.key], e.target.value)}
                                                style={{ width: '28px', height: '28px', border: 'none', padding: 0, borderRadius: '4px', cursor: 'pointer', outline: 'none' }}
                                            />
                                            <div className={styles.pickerInfo} style={{ display: 'flex', flexDirection: 'column' }}>
                                                <span className={styles.pickerLabel} style={{ fontSize: '11px', color: '#4b5563', whiteSpace: 'nowrap' }}>{clr.label}</span>
                                                <span className={styles.pickerHex} style={{ fontSize: '10px', color: '#9ca3af' }}>{(c as any)[clr.key]?.toUpperCase()}</span>
                                            </div>
                                        </div>
                                    ))}
                                </div>
                            </div>
                        </div>
                    )}
                </div>

                {/* Get FAQs block code Section */}
                <div className={styles.collapsibleCard}>
                    <div className={styles.collapsibleHeader} onClick={() => toggleCategory("Code")}>
                        <span>Get FAQs block code</span>
                        {activeCategories.includes("Code") ? <FiChevronDown /> : <FiChevronRight />}
                    </div>
                    {activeCategories.includes("Code") && (
                        <div className={styles.collapsibleContent}>
                            <p style={{ fontSize: '12px', color: '#6b7280', marginBottom: '12px' }}>Copy this code and add it to your website's HTML to display the FAQs block.</p>
                            <div className={styles.codeSnippet} style={{ background: '#f9fafb', padding: '12px', borderRadius: '8px', fontSize: '11px', color: '#374151', whiteSpace: 'pre-wrap', position: 'relative', border: '1px solid #e5e7eb' }}>
                                {localBlock?.generated_script || ''}
                                <button onClick={() => navigator.clipboard.writeText(localBlock?.generated_script || '')} style={{ position: 'absolute', right: '8px', top: '8px', background: 'white', border: '1px solid #e5e7eb', borderRadius: '4px', padding: '4px 8px', fontSize: '11px', fontWeight: 600, display: 'flex', gap: '4px', alignItems: 'center', cursor: 'pointer' }}>
                                    <FiCopy /> Copy
                                </button>
                            </div>
                        </div>
                    )}
                </div>
            </div>

            {/* Preview Sidebar */}
            <div className={styles.previewSidebar}>
                <div className={styles.feedbackCard} style={{ padding: '24px' }}>
                    <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: '20px' }}>
                        <h3 className={styles.cardSectionTitle} style={{ margin: 0 }}>Preview</h3>
                        <div className={styles.actionIconBtn} style={{ width: '100px', gap: '8px', fontSize: '13px' }}>
                            <FiMonitor /> Desktop
                        </div>
                    </div>
                    <div className={styles.phoneFrame} style={{ borderColor: '#f3f4f6', background: c.block_background }}>
                        <div className={styles.chatBody} style={{ background: c.block_background, padding: '16px', minHeight: '100%' }}>
                            <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: '20px', borderBottom: '1px solid #e5e7eb', paddingBottom: '12px', color: '#111' }}>
                                <div style={{ fontWeight: 800, fontSize: '10px' }}>☰</div>
                                <div style={{ fontWeight: 800, fontSize: '10px' }}>YOUR STORE</div>
                                <div style={{ display: 'flex', gap: '8px' }}>
                                    <div style={{ fontSize: '10px' }}>🔍</div>
                                    <div style={{ fontSize: '10px' }}>🛒</div>
                                </div>
                            </div>

                            <div style={{ height: '80px', background: '#d1d5db', borderRadius: '8px', marginBottom: '16px' }}></div>
                            <div style={{ height: '20px', background: '#e5e7eb', borderRadius: '4px', marginBottom: '8px', width: '80%' }}></div>
                            <div style={{ height: '20px', background: '#e5e7eb', borderRadius: '4px', marginBottom: '8px', width: '60%' }}></div>
                            <div style={{ height: '20px', background: '#e5e7eb', borderRadius: '4px', marginBottom: '16px', width: '90%' }}></div>

                            <div style={{
                                textAlign: s.heading_alignment,
                                margin: '32px 0 16px'
                            }}>
                                <h5 style={{
                                    fontSize: s.heading_size === 'large' ? '24px' : s.heading_size === 'medium' ? '20px' : '16px',
                                    fontWeight: 800, color: c.title, margin: '0 0 6px'
                                }}>
                                    {localBlock?.general?.heading}
                                </h5>
                                <p style={{ fontSize: '11px', color: c.subtitle }}>{localBlock?.general?.subheading}</p>
                            </div>

                            {!localBlock?.configuration?.dont_categorize_faqs && (
                                <div style={{ fontSize: '12px', fontWeight: 600, color: '#10b981', marginBottom: '8px', marginTop: '16px', textAlign: s.heading_alignment }}>Order & Shipping</div>
                            )}

                            {renderPreviewFAQs()}
                        </div>
                    </div>
                </div>
            </div>
        </div>
    );
}
