/**
 * Shois Chat Button — Template Editor
 *
 * 3-column layout: left sidebar (tabs) | center (controls) | right (live preview).
 *
 * @package ShoisChatButton
 */
import { useState, useCallback, useEffect, Component } from '@wordpress/element';
import { __ } from '@wordpress/i18n';
import apiFetch from '@wordpress/api-fetch';
import DesignTab from './editor/DesignTab';
import ContentTab from './editor/ContentTab';
import BehaviorTab from './editor/BehaviorTab';
import AnimationsTab from './AnimationsTab';




const EDITOR_TABS = [
    { id: 'design', label: __('Design', 'shois-chat-button'), icon: '🎨' },
    { id: 'content', label: __('Content', 'shois-chat-button'), icon: '✏️' },
    { id: 'behavior', label: __('Behavior', 'shois-chat-button'), icon: '⚙️' },
    { id: 'animations', label: __('Animations', 'shois-chat-button'), icon: '🎭' },
];

/**
 * Live Preview panel.
 *
 * @param {Object} props        Component props.
 * @param {Object} props.config Template config to preview.
 * @return {JSX.Element} Preview panel.
 */
const ICON_SVG = {
    chat: '<svg viewBox="0 0 24 24" fill="currentColor"><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>',
    chat_dots: '<svg viewBox="0 0 24 24" fill="currentColor"><path d="M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z"/><circle cx="8" cy="10" r="1"/><circle cx="12" cy="10" r="1"/><circle cx="16" cy="10" r="1"/></svg>',
    headset: '<svg viewBox="0 0 24 24" fill="currentColor"><path d="M12 1a9 9 0 0 0-9 9v7c0 1.66 1.34 3 3 3h3v-8H5v-2a7 7 0 0 1 14 0v2h-4v8h3c1.66 0 3-1.34 3-3v-7a9 9 0 0 0-9-9z"/></svg>',
    help: '<svg viewBox="0 0 24 24" fill="currentColor"><path d="M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zm1 17h-2v-2h2v2zm2.07-7.75l-.9.92C13.45 12.9 13 13.5 13 15h-2v-.5c0-1.1.45-2.1 1.17-2.83l1.24-1.26c.37-.36.59-.86.59-1.41 0-1.1-.9-2-2-2s-2 .9-2 2H8c0-2.21 1.79-4 4-4s4 1.79 4 4c0 .88-.36 1.68-.93 2.25z"/></svg>',
    phone: '<svg viewBox="0 0 24 24" fill="currentColor"><path d="M6.62 10.79c1.44 2.83 3.76 5.14 6.59 6.59l2.2-2.2c.27-.27.67-.36 1.02-.24 1.12.37 2.33.57 3.57.57.55 0 1 .45 1 1V20c0 .55-.45 1-1 1-9.39 0-17-7.61-17-17 0-.55.45-1 1-1h3.5c.55 0 1 .45 1 1 0 1.25.2 2.45.57 3.57.11.35.03.74-.25 1.02l-2.2 2.2z"/></svg>',
    mail: '<svg viewBox="0 0 24 24" fill="currentColor"><path d="M20 4H4c-1.1 0-1.99.9-1.99 2L2 18c0 1.1.9 2 2 2h16c1.1 0 2-.9 2-2V6c0-1.1-.9-2-2-2zm0 4l-8 5-8-5V6l8 5 8-5v2z"/></svg>',
    whatsapp: '<svg viewBox="0 0 24 24" fill="currentColor"><path d="M17.472 14.382c-.297-.149-1.758-.867-2.03-.967-.273-.099-.471-.148-.67.15-.197.297-.767.966-.94 1.164-.173.199-.347.223-.644.075-.297-.15-1.255-.463-2.39-1.475-.883-.788-1.48-1.761-1.653-2.059-.173-.297-.018-.458.13-.606.134-.133.298-.347.446-.52.149-.174.198-.298.298-.497.099-.198.05-.371-.025-.52-.075-.149-.669-1.612-.916-2.207-.242-.579-.487-.5-.669-.51-.173-.008-.371-.01-.57-.01-.198 0-.52.074-.792.372-.272.297-1.04 1.016-1.04 2.479 0 1.462 1.065 2.875 1.213 3.074.149.198 2.096 3.2 5.077 4.487.709.306 1.262.489 1.694.625.712.227 1.36.195 1.871.118.571-.085 1.758-.719 2.006-1.413.248-.694.248-1.289.173-1.413-.074-.124-.272-.198-.57-.347m-5.421 7.403h-.004a9.87 9.87 0 01-5.031-1.378l-.361-.214-3.741.982.998-3.648-.235-.374a9.86 9.86 0 01-1.51-5.26c.001-5.45 4.436-9.884 9.888-9.884 2.64 0 5.122 1.03 6.988 2.898a9.825 9.825 0 012.893 6.994c-.003 5.45-4.437 9.884-9.885 9.884m8.413-18.297A11.815 11.815 0 0012.05 0C5.495 0 .16 5.335.157 11.892c0 2.096.547 4.142 1.588 5.945L.057 24l6.305-1.654a11.882 11.882 0 005.683 1.448h.005c6.554 0 11.89-5.335 11.893-11.893a11.821 11.821 0 00-3.48-8.413z"/></svg>',
    telegram: '<svg viewBox="0 0 24 24" fill="currentColor"><path d="M11.944 0A12 12 0 000 12a12 12 0 0012 12 12 12 0 0012-12A12 12 0 0012 0 12 12 0 0011.944 0zm4.962 7.224c.1-.002.321.023.465.14a.506.506 0 01.171.325c.016.093.036.306.02.472-.18 1.898-.962 6.502-1.36 8.627-.168.9-.499 1.201-.82 1.23-.696.065-1.225-.46-1.9-.902-1.056-.693-1.653-1.124-2.678-1.8-1.185-.78-.417-1.21.258-1.91.177-.184 3.247-2.977 3.307-3.23.007-.032.014-.15-.056-.212s-.174-.041-.249-.024c-.106.024-1.793 1.14-5.061 3.345-.479.33-.913.49-1.302.48-.428-.008-1.252-.241-1.865-.44-.752-.245-1.349-.374-1.297-.789.027-.216.325-.437.893-.663 3.498-1.524 5.83-2.529 6.998-3.014 3.332-1.386 4.025-1.627 4.476-1.635z"/></svg>',
    messenger: '<svg viewBox="0 0 24 24" fill="currentColor"><path d="M.001 11.639C.001 4.949 5.241 0 12.001 0S24 4.95 24 11.639c0 6.689-5.24 11.638-12 11.638-1.21 0-2.38-.16-3.47-.46a.96.96 0 00-.64.05l-2.39 1.05a.96.96 0 01-1.35-.85l-.07-2.14a.97.97 0 00-.32-.68A11.39 11.389 0 01.002 11.64zm8.32-2.19l-3.52 5.6c-.35.53.32 1.139.82.75l3.79-2.87c.29-.21.69-.21.97 0l2.8 2.1c.86.64 2.09.4 2.65-.5l3.52-5.6c.35-.53-.32-1.13-.82-.75l-3.79 2.87c-.29.21-.69.21-.97 0l-2.8-2.1c-.86-.64-2.09-.4-2.65.5z"/></svg>',
    instagram: '<svg viewBox="0 0 24 24" fill="currentColor"><path d="M12 0C8.74 0 8.333.015 7.053.072 5.775.132 4.905.333 4.14.63c-.789.306-1.459.717-2.126 1.384S.935 3.35.63 4.14C.333 4.905.131 5.775.072 7.053.012 8.333 0 8.74 0 12s.015 3.667.072 4.947c.06 1.277.261 2.148.558 2.913.306.788.717 1.459 1.384 2.126.667.666 1.336 1.079 2.126 1.384.766.296 1.636.499 2.913.558C8.333 23.988 8.74 24 12 24s3.667-.015 4.947-.072c1.277-.06 2.148-.262 2.913-.558.788-.306 1.459-.718 2.126-1.384.666-.667 1.079-1.335 1.384-2.126.296-.765.499-1.636.558-2.913.06-1.28.072-1.687.072-4.947s-.015-3.667-.072-4.947c-.06-1.277-.262-2.149-.558-2.913-.306-.789-.718-1.459-1.384-2.126C21.319 1.347 20.651.935 19.86.63c-.765-.297-1.636-.499-2.913-.558C15.667.012 15.26 0 12 0zm0 2.16c3.203 0 3.585.016 4.85.071 1.17.055 1.805.249 2.227.415.562.217.96.477 1.382.896.419.42.679.819.896 1.381.164.422.36 1.057.413 2.227.057 1.266.07 1.646.07 4.85s-.015 3.585-.074 4.85c-.061 1.17-.256 1.805-.421 2.227-.224.562-.479.96-.899 1.382-.419.419-.824.679-1.38.896-.42.164-1.065.36-2.235.413-1.274.057-1.649.07-4.859.07-3.211 0-3.586-.015-4.859-.074-1.171-.061-1.816-.256-2.236-.421-.569-.224-.96-.479-1.379-.899-.421-.419-.69-.824-.9-1.38-.165-.42-.359-1.065-.42-2.235-.045-1.26-.061-1.649-.061-4.844 0-3.196.016-3.586.061-4.861.061-1.17.255-1.814.42-2.234.21-.57.479-.96.9-1.381.419-.419.81-.689 1.379-.898.42-.166 1.051-.361 2.221-.421 1.275-.045 1.65-.06 4.859-.06l.045.03zm0 3.678a6.162 6.162 0 100 12.324 6.162 6.162 0 100-12.324zM12 16c-2.21 0-4-1.79-4-4s1.79-4 4-4 4 1.79 4 4-1.79 4-4 4zm7.846-10.405a1.441 1.441 0 11-2.88 0 1.441 1.441 0 012.88 0z"/></svg>',
    viber: '<svg viewBox="0 0 24 24" fill="currentColor"><path d="M11.398.002C9.473.028 5.331.344 3.014 2.467 1.294 4.177.518 6.769.399 9.932c-.12 3.163-.27 9.098 5.575 10.702l.007.003v2.43s-.038.976.606 1.175c.778.24 1.236-.5 1.98-1.303.408-.44.97-1.088 1.394-1.583 3.84.322 6.8-.414 7.139-.525.778-.255 5.186-.818 5.907-6.677.743-6.034-.354-9.835-2.354-11.553-.6-.55-3.004-2.318-8.568-2.572 0 0-.427-.022-.961-.026l.269-.001zm.27 1.534c.455 0 .832.02.832.02 4.775.22 6.818 1.628 7.34 2.098 1.72 1.478 2.611 4.864 1.96 10.093-.62 5.04-4.347 5.353-5.013 5.57-.283.091-2.856.732-6.148.533 0 0-2.435 2.941-3.197 3.707-.12.12-.26.167-.352.144-.13-.032-.166-.186-.164-.413l.022-4.013c-5.001-1.378-4.704-6.478-4.6-9.21.104-2.733.753-4.98 2.2-6.404 1.997-1.83 5.603-2.129 7.12-2.126z"/></svg>',
    discord: '<svg viewBox="0 0 24 24" fill="currentColor"><path d="M20.317 4.3698a19.7913 19.7913 0 00-4.8851-1.5152.0741.0741 0 00-.0785.0371c-.211.3753-.4447.8648-.6083 1.2495-1.8447-.2762-3.68-.2762-5.4868 0-.1636-.3933-.4058-.8742-.6177-1.2495a.077.077 0 00-.0785-.037 19.7363 19.7363 0 00-4.8852 1.515.0699.0699 0 00-.0321.0277C.5334 9.0458-.319 13.5799.0992 18.0578a.0824.0824 0 00.0312.0561c2.0528 1.5076 4.0413 2.4228 5.9929 3.0294a.0777.0777 0 00.0842-.0276c.4616-.6304.8731-1.2952 1.226-1.9942a.076.076 0 00-.0416-.1057c-.6528-.2476-1.2743-.5495-1.8722-.8923a.077.077 0 01-.0076-.1277c.1258-.0943.2517-.1923.3718-.2914a.0743.0743 0 01.0776-.0105c3.9278 1.7933 8.18 1.7933 12.0614 0a.0739.0739 0 01.0785.0095c.1202.099.246.1981.3728.2924a.077.077 0 01-.0066.1276 12.2986 12.2986 0 01-1.873.8914.0766.0766 0 00-.0407.1067c.3604.698.7719 1.3628 1.225 1.9932a.076.076 0 00.0842.0286c1.961-.6067 3.9495-1.5219 6.0023-3.0294a.077.077 0 00.0313-.0552c.5004-5.177-.8382-9.6739-3.5485-13.6604a.061.061 0 00-.0312-.0286zM8.02 15.3312c-1.1825 0-2.1569-1.0857-2.1569-2.419 0-1.3332.9555-2.4189 2.157-2.4189 1.2108 0 2.1757 1.0952 2.1568 2.419 0 1.3332-.9555 2.4189-2.1569 2.4189zm7.9748 0c-1.1825 0-2.1569-1.0857-2.1569-2.419 0-1.3332.9554-2.4189 2.1569-2.4189 1.2108 0 2.1757 1.0952 2.1568 2.419 0 1.3332-.946 2.4189-2.1568 2.4189z"/></svg>',
    line: '<svg viewBox="0 0 24 24" fill="currentColor"><path d="M24 10.382C24 4.644 18.614.2 12 .2S0 4.644 0 10.382c0 5.043 4.474 9.27 10.52 10.068.41.088.966.27 1.107.62.127.317.083.812.04 1.131 0 0-.147.89-.18 1.078-.054.318-.25 1.246 1.092.68C13.915 23.392 18.978 20.2 21.12 17.64c1.484-1.628 2.878-3.848 2.878-7.258"/></svg>',
    skype: '<svg viewBox="0 0 24 24" fill="currentColor"><path d="M12.069 18.874c-4.023 0-5.82-1.979-5.82-3.464 0-.765.561-1.296 1.333-1.296 1.723 0 1.273 2.477 4.487 2.477 1.641 0 2.55-.895 2.55-1.811 0-.551-.269-1.16-1.354-1.429l-3.576-.895c-2.88-.724-3.403-2.286-3.403-3.751 0-3.047 2.861-4.191 5.549-4.191 2.471 0 5.393 1.373 5.393 3.199 0 .784-.688 1.24-1.453 1.24-1.469 0-1.198-2.037-4.164-2.037-1.469 0-2.292.664-2.292 1.617s1.153 1.258 2.157 1.487l2.637.587c2.891.649 3.624 2.346 3.624 3.944 0 2.476-1.902 4.414-5.722 4.414M24 12.073a11.89 11.89 0 01-.657 3.92 6.017 6.017 0 01.131 1.262c0 3.303-2.686 5.98-5.997 5.98-.682 0-1.341-.115-1.954-.326A11.93 11.93 0 0112.07 24C5.424 24 .001 18.579.001 11.934c0-1.35.224-2.647.633-3.863A6.004 6.004 0 01.459 6.795c0-3.303 2.686-5.98 5.997-5.98.691 0 1.355.118 1.973.334A11.917 11.917 0 0112.07 0c6.645 0 12.068 5.421 12.068 12.073"/></svg>',
    tiktok: '<svg viewBox="0 0 24 24" fill="currentColor"><path d="M12.525.02c1.31-.02 2.61-.01 3.91-.02.08 1.53.63 3.09 1.75 4.17 1.12 1.11 2.7 1.62 4.24 1.79v4.03c-1.44-.05-2.89-.35-4.2-.97-.57-.26-1.1-.59-1.62-.93-.01 2.92.01 5.84-.02 8.75-.08 1.4-.54 2.79-1.35 3.94-1.31 1.92-3.58 3.17-5.91 3.21-1.43.08-2.86-.31-4.08-1.03-2.02-1.19-3.44-3.37-3.65-5.71-.02-.5-.03-1-.01-1.49.18-1.9 1.12-3.72 2.58-4.96 1.66-1.44 3.98-2.13 6.15-1.72.02 1.48-.04 2.96-.04 4.44-.99-.32-2.15-.23-3.02.37-.63.41-1.11 1.04-1.36 1.75-.21.51-.15 1.07-.14 1.61.24 1.64 1.82 3.02 3.5 2.87 1.12-.01 2.19-.66 2.77-1.61.19-.33.4-.67.41-1.06.1-1.79.06-3.57.07-5.36.01-4.03-.01-8.05.02-12.07z"/></svg>',
};

/**
 * Live Preview panel.
 *
 * @param {Object} props        Component props.
 * @return {JSX.Element} Preview panel.
 */
function LivePreview({ config }) {
    const templateSlug = config.template_slug || 'classic-green';
    const primaryColor = config.primary_color || '#5170ff';
    const headerBg = config.header_bg_color || primaryColor;
    const headerTextColor = config.header_text_color || '#ffffff';
    const textColor = config.text_color || '#1e293b';
    const bgColor = config.bg_color || '#ffffff';
    
    // Use real widget values but they will be scaled down by CSS
    const popupWidth = config.popup_width || 360;
    const btnSize = config.btn_size || 60;
    const iconSize = config.icon_size || 24;
    const btnRadius = config.radius_btn !== undefined ? config.radius_btn : 50;
    const popupRadius = config.radius_popup !== undefined ? config.radius_popup : 16;

    const triggerIcon = config.trigger_icon || 'whatsapp';
    const iconColor = config.icon_color || '#ffffff';

    // Position in mocksite (scaled)
    const positionStyles = {
        bottom: config.position?.includes('bottom') ? '10px' : 'auto',
        top: config.position?.includes('top') ? '10px' : 'auto',
        right: config.position?.includes('right') ? '10px' : 'auto',
        left: config.position?.includes('left') ? '10px' : 'auto',
    };

    return (
        <div className="shcb-editor-preview">
            <div className="shcb-preview-header">
                <span className="shcb-preview-label">
                    {__('Live Preview', 'shois-chat-button')}
                </span>
            </div>
            <div className="shcb-preview-frame">
                <div className="shcb-preview-mocksite">
                    <div className="shcb-mocksite-nav" />
                    <div className="shcb-mocksite-content">
                        <div className="shcb-mocksite-block" />
                        <div className="shcb-mocksite-block shcb-mocksite-block-sm" />
                        <div className="shcb-mocksite-block" />
                    </div>

                    { /* Widget preview — Scaled container */}
                    <div
                        className={`shcb-widget shcb-template-${templateSlug} shcb-pos-${config.position || 'bottom-right'}`}
                        style={{
                            '--scb-primary': primaryColor,
                            '--shcb-header-bg': headerBg,
                            '--shcb-header-text': headerTextColor,
                            '--scb-text': textColor,
                            '--scb-bg': bgColor,
                            '--scb-radius-btn': `${btnRadius}%`,
                            '--scb-radius-popup': `${popupRadius}px`,
                            '--shcb-btn-size': `${btnSize}px`,
                            '--shcb-popup-width': `${popupWidth}px`,
                            '--scb-icon-size': `${iconSize}px`,
                            '--scb-icon-color': iconColor,
                            position: 'absolute',
                            ...positionStyles,
                            transform: 'scale(0.6)',
                            transformOrigin: config.position?.includes('right') ? 'bottom right' : 'bottom left',
                            zIndex: 100,
                            pointerEvents: 'none' // Allow interactions with mocksite if needed
                        }}
                    >
                        { /* Popup preview */}
                        <div className="shcb-popup shcb-popup-visible">
                            <div className="shcb-popup-header">
                                <div className="shcb-header-text">
                                    <div className="shcb-header-title">
                                        {config.header_title || 'Chat with us! 👋'}
                                    </div>
                                    <div className="shcb-header-subtitle">
                                        {config.header_subtitle || 'We reply within minutes'}
                                    </div>
                                </div>
                            </div>
                            <div className="shcb-popup-body">
                                <p className="shcb-welcome-message">
                                    {config.welcome_message || 'Hi! How can we help you today?'}
                                </p>
                                <div 
                                    className="shcb-agent-card"
                                    style={{ 
                                        backgroundColor: config.agent_bg_color || '#f8faf9',
                                    }}
                                >
                                    <div className="shcb-agent-avatar-wrap">
                                        <div
                                            className="shcb-agent-avatar shcb-avatar-initials"
                                            style={{ backgroundColor: primaryColor }}
                                        >
                                            D
                                        </div>
                                    </div>
                                    <div className="shcb-agent-info">
                                        <div className="shcb-agent-name" style={{ color: config.agent_text_color || '#1e293b' }}>Demo Agent</div>
                                        <div className="shcb-agent-status" style={{ color: config.agent_text_color || '#1e293b' }}>
                                            <span className="shcb-status-dot shcb-status-online"></span> Online now
                                        </div>
                                    </div>
                                    <div
                                        className="shcb-platform-btn"
                                        style={{ 
                                            backgroundColor: '#25D366', 
                                            borderRadius: `${config.platform_radius !== undefined ? config.platform_radius : 0}%`,
                                            width: '32px',
                                            height: '32px',
                                            display: 'flex',
                                            alignItems: 'center',
                                            justifyContent: 'center',
                                            color: '#fff'
                                        }}
                                    >
                                        <div style={{ width: '18px', height: '18px', display: 'flex' }} dangerouslySetInnerHTML={{ __html: ICON_SVG.whatsapp }} />
                                    </div>
                                </div>
                            </div>

                            { /* Popup Footer preview */}
                            <div className="shcb-popup-footer">
                                {config.footer_text || 'Powered by Shois Chat Button'}
                            </div>
                        </div>

                        { /* Trigger button preview */}
                        <div className="shcb-trigger-btn">
                            <div
                                className="shcb-trigger-icon"
                                dangerouslySetInnerHTML={{ __html: ICON_SVG[triggerIcon] || ICON_SVG.chat }}
                            />
                        </div>
                    </div>
                </div>
            </div>
        </div>
    );
}


/**
 * Default color tokens for each template directly extracted from their CSS variables.
 */
export const TEMPLATE_DEFAULTS = {
    'classic-green': { 
        primary_color: '#00ff6e', 
        header_bg_color: '#00ff6e', 
        header_text_color: '#ffffff', 
        text_color: '#333333', 
        bg_color: '#ffffff', 
        agent_bg_color: '#f8faf9', 
        agent_text_color: '#1e293b' 
    },
    'dark-elegance': { primary_color: '#8b5cf6', header_bg_color: 'linear-gradient(135deg, #1a1a2e 0%, #16213e 100%)', header_text_color: '#ffffff', text_color: '#e2e8f0', bg_color: '#1a1a2e' },
    'gradient-sunset': { primary_color: '#f97316', header_bg_color: 'linear-gradient(135deg, #f97316 0%, #ec4899 100%)', header_text_color: '#ffffff', text_color: '#1e293b', bg_color: '#ffffff' },
    'minimal-white': { 
        primary_color: '#0f172a', 
        header_bg_color: '#ffffff', 
        header_text_color: '#0f172a', 
        text_color: '#1e293b', 
        bg_color: '#ffffff',
        agent_bg_color: '#fafafa',
        agent_text_color: '#1e293b'
    },
    'ivory-prism': { primary_color: '#FF5C3A', header_bg_color: '#1A0F0A', header_text_color: '#FFF8F0', text_color: '#2C1A10', bg_color: '#FDFAF6' },
    'bubblegum': { primary_color: '#FF6B9D', header_bg_color: 'linear-gradient(135deg, #FF6B9D 0%, #C084FC 100%)', header_text_color: '#ffffff', text_color: '#3D2B5E', bg_color: '#FEFCFF' },
    'sticker-board': { primary_color: '#FFE566', header_bg_color: '#FFE566', header_text_color: '#1A1A2E', text_color: '#1A1A2E', bg_color: '#FFFEF7' },
    'fold': { primary_color: '#D97706', header_bg_color: '#FAF8F3', header_text_color: '#1C1917', text_color: '#1C1917', bg_color: '#FAF8F3' },
    'ink': { primary_color: '#111111', header_bg_color: '#F9F7F4', header_text_color: '#111111', text_color: '#111111', bg_color: '#F9F7F4' },
    'vinyl': { primary_color: '#E8C547', header_bg_color: '#161414', header_text_color: '#ffffff', text_color: '#ffffff', bg_color: '#161414' },
    'soft': { primary_color: '#111111', header_bg_color: '#111111', header_text_color: '#ffffff', text_color: '#222222', bg_color: '#ffffff' },
};

/**
 * TemplateEditor — 3-column editor with live preview.
 *
 * @param {Object}   props          Component props.
 * @param {Object}   props.template Template to edit.
 * @param {Function} props.onBack   Back navigation handler.
 * @return {JSX.Element} Template editor.
 */
export default function TemplateEditor({ template, onBack }) {
    const templateSlug = template?.slug || 'classic-green';
    const tplDefaults = TEMPLATE_DEFAULTS[templateSlug] || {};

    const [activeTab, setActiveTab] = useState('design');
    const [config, setConfig] = useState({
        template_slug: templateSlug,
        primary_color: tplDefaults.primary_color || '#5170ff',
        header_bg_color: tplDefaults.header_bg_color || tplDefaults.primary_color || '#5170ff',
        header_text_color: tplDefaults.header_text_color || '#ffffff',
        text_color: tplDefaults.text_color || '#1e293b',
        bg_color: tplDefaults.bg_color || '#ffffff',
        agent_bg_color: tplDefaults.agent_bg_color || '#f8faf9',
        agent_text_color: tplDefaults.agent_text_color || '#1e293b',
        header_title: 'Chat with us! 👋',
        header_subtitle: 'We reply within minutes',
        welcome_message: 'Hi! How can we help you today?',
        offline_message: "We're currently offline.",
        position: 'bottom-right',
        btn_size: 60,
        icon_size: 24,
        icon_color: '#ffffff',
        popup_width: 360,
        auto_open: false,
        auto_open_delay: 3,
        close_on_outside_click: true,
        remember_closed: false,
        show_after_delay: false,
        delay_seconds: 0,
        show_after_scroll: false,
        scroll_percentage: 25,
    });
    const [animations, setAnimations] = useState({});
    const [saving, setSaving] = useState(false);
    const [saved, setSaved] = useState(false);

    // Color keys that must be reset when switching templates.
    const COLOR_KEYS = [
        'primary_color', 'header_bg_color', 'header_text_color',
        'text_color', 'bg_color', 'agent_bg_color', 'agent_text_color',
    ];

    // Load existing config and animations from settings on mount.
    useEffect(() => {
        apiFetch({ path: '/shois-chat/v1/settings' })
            .then((data) => {
                if (data && data.template_config) {
                    const savedConfig = data.template_config;
                    
                    setConfig((prev) => {
                        // Priority: 
                        // 1. Current template from props (slug and defaults)
                        // 2. Saved settings for other values (content, behavior, etc.)
                        
                        const isDifferentTemplate = template && template.slug !== savedConfig.template_slug;
                        
                        if (isDifferentTemplate) {
                            // If switching to a new template:
                            // Keep new template slug and colors (from prev), 
                            // but pull in content/behavior from saved config.
                            const merged = { ...prev };
                            Object.keys(savedConfig).forEach(key => {
                                if (!COLOR_KEYS.includes(key) && key !== 'template_slug') {
                                    merged[key] = savedConfig[key];
                                }
                            });
                            return merged;
                        }

                        // If same template as saved: merge everything but ensure slug is correct
                        return {
                            ...prev,
                            ...savedConfig,
                            template_slug: templateSlug // Force the correct slug
                        };
                    });
                }
                if (data && data.animations) {
                    setAnimations(data.animations);
                }
            })
            .catch(() => { });
    }, [template, templateSlug]);

    const updateConfig = useCallback((updates) => {
        setConfig((prev) => ({ ...prev, ...updates }));
        setSaved(false);
    }, []);

    const updateAnimations = useCallback((updates) => {
        setAnimations((prev) => ({ ...prev, ...updates }));
        setSaved(false);
    }, []);

    const handleSave = () => {
        setSaving(true);
        apiFetch({
            path: '/shois-chat/v1/settings',
            method: 'POST',
            data: {
                template_config: config,
                animations: animations,
                active_template_slug: config.template_slug,
            },
        })
            .then(() => {
                setSaved(true);
                setTimeout(() => setSaved(false), 2000);
            })
            .catch(() => { })
            .finally(() => setSaving(false));
    };

    const renderTabContent = () => {
        switch (activeTab) {
            case 'design':
                return <DesignTab config={config} onChange={updateConfig} templateDefaults={TEMPLATE_DEFAULTS[config.template_slug] || {}} />;
            case 'content':
                return <ContentTab config={config} onChange={updateConfig} />;
            case 'behavior':
                return <BehaviorTab config={config} onChange={updateConfig} />;
            case 'animations': {
                const animValues = {
                    entrance: config.entrance || '',
                    idle: config.idle || '',
                    hover: config.hover || '',
                    popup: config.popup || '',
                    idle_interval: config.idle_interval || 5,
                    enable_pulse_ring: config.enable_pulse_ring !== false,
                };
                return (
                    <AnimationsTab
                        values={animValues}
                        onChange={(updatedValues) => updateConfig(updatedValues)}
                    />
                );
            }
            default:
                return null;
        }
    };

    return (
        <div className="shcb-template-editor">
            { /* Editor Toolbar */}
            <div className="shcb-editor-toolbar">
                <button className="shcb-btn shcb-btn-secondary" onClick={onBack} type="button">
                    ← {__('Back', 'shois-chat-button')}
                </button>
                <h3 className="shcb-editor-title">
                    {__('Editing:', 'shois-chat-button')} {template?.name || 'Template'}
                </h3>
                <div className="shcb-editor-toolbar-right">
                    {saved && (
                        <span className="shcb-saved-indicator">
                            ✓ {__('Saved', 'shois-chat-button')}
                        </span>
                    )}
                    <button
                        className="shcb-btn shcb-btn-primary"
                        onClick={handleSave}
                        disabled={saving}
                        type="button"
                    >
                        {saving ? __('Saving...', 'shois-chat-button') : __('Save Changes', 'shois-chat-button')}
                    </button>
                </div>
            </div>

            <div className="shcb-editor-layout">
                { /* Left: Tab sidebar */}
                <div className="shcb-editor-sidebar">
                    {EDITOR_TABS.map((tab) => (
                        <button
                            key={tab.id}
                            className={`shcb-editor-tab ${activeTab === tab.id ? 'shcb-editor-tab-active' : ''}`}
                            onClick={() => setActiveTab(tab.id)}
                            type="button"
                        >
                            <span className="shcb-editor-tab-icon">{tab.icon}</span>
                            <span>{tab.label}</span>
                        </button>
                    ))}
                </div>

                { /* Center: Controls */}
                <div className="shcb-editor-controls">
                    {renderTabContent()}
                </div>

                { /* Right: Live Preview */}
                <LivePreview config={config} />
            </div>
        </div>
    );
}
