/**
 * Shois Chat Button — Admin App
 *
 * Main React component with hash-based routing and left sidebar navigation.
 *
 * @package ShoisChatButton
 */
import { useState, useEffect, useCallback } from '@wordpress/element';
import { __ } from '@wordpress/i18n';
import apiFetch from '@wordpress/api-fetch';
import TemplatesPage from './pages/TemplatesPage';
import TemplateEditor from './pages/TemplateEditor';
import AgentsPage from './pages/AgentsPage';
import AnalyticsPage from './pages/AnalyticsPage';
import SettingsPage from './pages/SettingsPage';

/**
 * Navigation tab definitions with SVG icons.
 */
const TABS = [
    {
        id: 'dashboard',
        label: __('Dashboard', 'shois-chat-button'),
        icon: (
            <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
                <rect x="3" y="3" width="7" height="7" rx="1" />
                <rect x="14" y="3" width="7" height="7" rx="1" />
                <rect x="3" y="14" width="7" height="7" rx="1" />
                <rect x="14" y="14" width="7" height="7" rx="1" />
            </svg>
        ),
    },
    {
        id: 'templates',
        label: __('Templates', 'shois-chat-button'),
        icon: (
            <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
                <path d="M12 2L2 7l10 5 10-5-10-5z" />
                <path d="M2 17l10 5 10-5" />
                <path d="M2 12l10 5 10-5" />
            </svg>
        ),
    },
    {
        id: 'agents',
        label: __('Agents', 'shois-chat-button'),
        icon: (
            <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
                <path d="M17 21v-2a4 4 0 0 0-4-4H5a4 4 0 0 0-4 4v2" />
                <circle cx="9" cy="7" r="4" />
                <path d="M23 21v-2a4 4 0 0 0-3-3.87" />
                <path d="M16 3.13a4 4 0 0 1 0 7.75" />
            </svg>
        ),
    },
    {
        id: 'analytics',
        label: __('Analytics', 'shois-chat-button'),
        icon: (
            <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
                <line x1="18" y1="20" x2="18" y2="10" />
                <line x1="12" y1="20" x2="12" y2="4" />
                <line x1="6" y1="20" x2="6" y2="14" />
            </svg>
        ),
    },
    {
        id: 'settings',
        label: __('Settings', 'shois-chat-button'),
        icon: (
            <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
                <circle cx="12" cy="12" r="3" />
                <path d="M19.4 15a1.65 1.65 0 0 0 .33 1.82l.06.06a2 2 0 0 1-2.83 2.83l-.06-.06a1.65 1.65 0 0 0-1.82-.33 1.65 1.65 0 0 0-1 1.51V21a2 2 0 0 1-4 0v-.09A1.65 1.65 0 0 0 9 19.4a1.65 1.65 0 0 0-1.82.33l-.06.06a2 2 0 0 1-2.83-2.83l.06-.06A1.65 1.65 0 0 0 4.68 15a1.65 1.65 0 0 0-1.51-1H3a2 2 0 0 1 0-4h.09A1.65 1.65 0 0 0 4.6 9a1.65 1.65 0 0 0-.33-1.82l-.06-.06a2 2 0 0 1 2.83-2.83l.06.06A1.65 1.65 0 0 0 9 4.68a1.65 1.65 0 0 0 1-1.51V3a2 2 0 0 1 4 0v.09a1.65 1.65 0 0 0 1 1.51 1.65 1.65 0 0 0 1.82-.33l.06-.06a2 2 0 0 1 2.83 2.83l-.06.06A1.65 1.65 0 0 0 19.4 9a1.65 1.65 0 0 0 1.51 1H21a2 2 0 0 1 0 4h-.09a1.65 1.65 0 0 0-1.51 1z" />
            </svg>
        ),
    },
];

/**
 * Get the current tab from the URL hash.
 *
 * @return {string} The current tab ID.
 */
function getTabFromHash() {
    const hash = window.location.hash.replace('#/', '').replace('#', '');
    const valid = TABS.find((tab) => tab.id === hash);
    return valid ? hash : 'dashboard';
}

/**
 * Sidebar Navigation component.
 *
 * @param {Object}   props            Component properties.
 * @param {string}   props.activeTab  Currently active tab.
 * @param {Function} props.onTabChange Tab change handler.
 * @return {JSX.Element} Sidebar element.
 */
function Sidebar({ activeTab, onTabChange }) {
    return (
        <aside className="shcb-sidebar">
            <div className="shcb-sidebar-brand">
                <div className="shcb-sidebar-logo">
                    <svg width="28" height="28" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
                        <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>
                </div>
                <div className="shcb-sidebar-brand-text">
                    <span className="shcb-sidebar-title">{__('Shois Chat', 'shois-chat-button')}</span>
                    <span className="shcb-sidebar-subtitle">{__('ADMIN DASHBOARD', 'shois-chat-button')}</span>
                </div>
            </div>

            <nav className="shcb-sidebar-nav">
                {TABS.map((tab) => (
                    <button
                        key={tab.id}
                        className={`shcb-sidebar-item ${activeTab === tab.id ? 'shcb-sidebar-item-active' : ''}`}
                        onClick={() => onTabChange(tab.id)}
                        type="button"
                    >
                        <span className="shcb-sidebar-icon">{tab.icon}</span>
                        <span className="shcb-sidebar-label">{tab.label}</span>
                    </button>
                ))}
            </nav>

            <div className="shcb-sidebar-footer">
                <span className="shcb-sidebar-version">
                    v{window.shcbAdmin?.version || '1.0.0'}
                </span>
            </div>
        </aside>
    );
}

/**
 * Top Bar component with status and toggle.
 *
 * @param {Object}   props           Component properties.
 * @param {string}   props.pageTitle Current page title.
 * @param {boolean}  props.active    Whether widget is active.
 * @param {Function} props.onToggle  Toggle handler.
 * @param {boolean}  props.saving    Whether save is in progress.
 * @return {JSX.Element} Top bar element.
 */
function TopBar({ pageTitle, active, onToggle, saving }) {
    return (
        <header className="shcb-topbar">
            <h2 className="shcb-topbar-title">{pageTitle}</h2>
            <div className="shcb-topbar-actions">
                <span className={`shcb-status-pill ${active ? 'shcb-status-pill-active' : 'shcb-status-pill-inactive'}`}>
                    <span className="shcb-status-dot"></span>
                    {active
                        ? __('Widget Active', 'shois-chat-button')
                        : __('Widget Inactive', 'shois-chat-button')
                    }
                </span>
                <label className="shcb-master-toggle" title={active ? __('Disable Widget', 'shois-chat-button') : __('Enable Widget', 'shois-chat-button')}>
                    <input
                        type="checkbox"
                        checked={active}
                        onChange={onToggle}
                        disabled={saving}
                    />
                    <span className="shcb-toggle-slider"></span>
                </label>
                <a
                    href={window.shcbAdmin?.siteUrl || '/'}
                    target="_blank"
                    rel="noopener noreferrer"
                    className="shcb-topbar-view-site"
                >
                    <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
                        <path d="M18 13v6a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h6" />
                        <polyline points="15 3 21 3 21 9" />
                        <line x1="10" y1="14" x2="21" y2="3" />
                    </svg>
                    {__('View Site', 'shois-chat-button')}
                </a>
            </div>
        </header>
    );
}

/**
 * Dashboard page component.
 *
 * @param {Object} props
 * @param {Function} props.onTabChange
 * @return {JSX.Element} Dashboard content.
 */
function DashboardPage({ onTabChange }) {
    const [pluginStatus, setPluginStatus] = useState({});
    const [actionLoading, setActionLoading] = useState(false);

    useEffect(() => {
        apiFetch({ path: '/shois-chat/v1/recommendations' })
            .then((data) => {
                setPluginStatus(data || {});
            })
            .catch(() => {});
    }, []);

    const handlePluginAction = (slug, action) => {
        if (actionLoading) return;
        setActionLoading(slug);

        apiFetch({
            path: '/shois-chat/v1/recommendations/action',
            method: 'POST',
            data: { slug, action }
        }).then((res) => {
            if (res.success) {
                // Optimistically update
                setPluginStatus(prev => ({
                    ...prev,
                    [slug]: {
                        installed: action === 'install' ? true : prev[slug]?.installed,
                        active: action === 'activate' ? true : prev[slug]?.active,
                    }
                }));
                if (action === 'activate') {
                    window.location.reload(); // Refresh to ensure admin menus update
                }
            } else {
                alert(res.message || __('Action failed.', 'shois-chat-button'));
            }
        }).catch((err) => {
            const errorMsg = err?.message || err?.statusText || __('Unknown error.', 'shois-chat-button');
            alert(__('Action failed: ', 'shois-chat-button') + errorMsg);
        }).finally(() => {
            setActionLoading(false);
        });
    };

    const RECOMMENDED_PLUGINS = [
        {
            id: 'smartwait-animated-preloader',
            title: __('SmartWait Preloader', 'shois-chat-button'),
            desc: __('Boost user engagement with beautiful animated preloaders.', 'shois-chat-button'),
            icon: <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><circle cx="12" cy="12" r="10"></circle><polyline points="12 6 12 12 16 14"></polyline></svg>,
            colorClass: 'bg-indigo'
        },
        {
            id: 'login-page-customizer-and-designer',
            title: __('Login Page Customizer', 'shois-chat-button'),
            desc: __('Customize your WordPress login page to match your brand.', 'shois-chat-button'),
            icon: <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M12 22s8-4 8-10V5l-8-3-8 3v7c0 6 8 10 8 10z"></path></svg>,
            colorClass: 'bg-red-500'
        },
        {
            id: 'uply-scroll-to-top',
            title: __('Uply Scroll to Top', 'shois-chat-button'),
            desc: __('Add a customizable scroll to top button and progress bar.', 'shois-chat-button'),
            icon: <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><line x1="12" y1="19" x2="12" y2="5"></line><polyline points="5 12 12 5 19 12"></polyline></svg>,
            colorClass: 'bg-amber-500'
        }
    ];

    return (
        <div className="shcb-dashboard-v2">
            <section className="shcb-dash-header-section">
                <div className="shcb-dash-title-row">
                    <h1 className="shcb-dash-title">{__('Welcome to Shois Chat Button, Admin! 👋', 'shois-chat-button')}</h1>
                </div>
                <p className="shcb-dash-subtitle">{__('Your all-in-one WhatsApp & multi-platform chat solution.', 'shois-chat-button')}</p>
            </section>

            {/* Setup Steps */}
            <section className="shcb-dash-section">
                <h3 className="shcb-dash-section-title">{__('Quick Setup', 'shois-chat-button')}</h3>
                <div className="shcb-dash-grid-3">
                    {/* Step 1 */}
                    <div className="shcb-dash-card shcb-dash-card-hover group">
                        <div className="shcb-dash-icon-box text-primary bg-primary-light group-hover-scale">
                            <svg width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M16 21v-2a4 4 0 0 0-4-4H5a4 4 0 0 0-4 4v2"></path><circle cx="8.5" cy="7" r="4"></circle><line x1="20" y1="8" x2="20" y2="14"></line><line x1="23" y1="11" x2="17" y2="11"></line></svg>
                        </div>
                        <h4 className="shcb-dash-card-title">{__('Step 1: Add your Agents', 'shois-chat-button')}</h4>
                        <p className="shcb-dash-card-desc mb-4">{__('Configure names, photos, and roles for your team members.', 'shois-chat-button')}</p>
                        <button className="shcb-dash-link-btn group-hover-gap" onClick={() => onTabChange && onTabChange('agents')}>
                            {__('Manage Agents', 'shois-chat-button')} <span className="shcb-icon-chevron">›</span>
                        </button>
                    </div>

                    {/* Step 2 */}
                    <div className="shcb-dash-card shcb-dash-card-hover group">
                        <div className="shcb-dash-icon-box text-primary bg-primary-light group-hover-scale">
                            <svg width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><circle cx="13.5" cy="6.5" r=".5" fill="currentColor"></circle><circle cx="17.5" cy="10.5" r=".5" fill="currentColor"></circle><circle cx="8.5" cy="7.5" r=".5" fill="currentColor"></circle><circle cx="6.5" cy="12.5" r=".5" fill="currentColor"></circle><path d="M12 2C6.5 2 2 6.5 2 12s4.5 10 10 10c.926 0 1.648-.746 1.648-1.688 0-.437-.18-.835-.437-1.125-.29-.289-.438-.652-.438-1.125a1.64 1.64 0 0 1 1.668-1.668h3.016C21.6 16.394 22 14.34 22 12c0-5.5-4.5-10-10-10z"></path></svg>
                        </div>
                        <h4 className="shcb-dash-card-title">{__('Step 2: Customize your Widget', 'shois-chat-button')}</h4>
                        <p className="shcb-dash-card-desc mb-4">{__('Tailor colors, fonts, and layout to match your brand identity.', 'shois-chat-button')}</p>
                        <button className="shcb-dash-link-btn group-hover-gap" onClick={() => onTabChange && onTabChange('templates')}>
                            {__('Open Editor', 'shois-chat-button')} <span className="shcb-icon-chevron">›</span>
                        </button>
                    </div>

                    {/* Step 3 */}
                    <div className="shcb-dash-card shcb-dash-card-hover group">
                        <div className="shcb-dash-icon-box text-primary bg-primary-light group-hover-scale">
                            <svg width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M1 12s4-8 11-8 11 8 11 8-4 8-11 8-11-8-11-8z"></path><circle cx="12" cy="12" r="3"></circle></svg>
                        </div>
                        <h4 className="shcb-dash-card-title">{__('Step 3: Set Display Rules', 'shois-chat-button')}</h4>
                        <p className="shcb-dash-card-desc mb-4">{__('Control exactly where and when your chat widget appears.', 'shois-chat-button')}</p>
                        <button className="shcb-dash-link-btn group-hover-gap" onClick={() => onTabChange && onTabChange('settings')}>
                            {__('Configure Rules', 'shois-chat-button')} <span className="shcb-icon-chevron">›</span>
                        </button>
                    </div>
                </div>
            </section>

            {/* Support & Resources + Plugins */}
            <div className="shcb-dash-grid-1-2 gap-8">
                <div className="shcb-dash-col-left">
                    <h3 className="shcb-dash-section-title">{__('Support & Resources', 'shois-chat-button')}</h3>
                    <div className="shcb-dash-col-inner">
                        {/* Card A */}
                        <div className="shcb-dash-card-horizontal">
                            <div className="shcb-dash-icon-circle bg-gray text-slate-600">
                                <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M4 19.5A2.5 2.5 0 0 1 6.5 17H20"></path><path d="M6.5 2H20v20H6.5A2.5 2.5 0 0 1 4 19.5v-15A2.5 2.5 0 0 1 6.5 2z"></path></svg>
                            </div>
                            <div className="shcb-dash-card-content">
                                <h4 className="shcb-dash-card-title-sm">{__('Documentation', 'shois-chat-button')}</h4>
                                <p className="shcb-dash-card-desc-xs mb-3">{__('Learn how to make the most of Shois Chat Button.', 'shois-chat-button')}</p>
                                <a href="https://wordpress.org/plugins/shois-chat-button/" target="_blank" className="shcb-dash-btn-outline">{__('Read Guides', 'shois-chat-button')}</a>
                            </div>
                        </div>
                        {/* Card B */}
                        <div className="shcb-dash-card-horizontal">
                            <div className="shcb-dash-icon-circle bg-gray text-slate-600">
                                <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><circle cx="12" cy="12" r="10"></circle><path d="M9.09 9a3 3 0 0 1 5.83 1c0 2-3 3-3 3"></path><line x1="12" y1="17" x2="12.01" y2="17"></line></svg>
                            </div>
                            <div className="shcb-dash-card-content">
                                <h4 className="shcb-dash-card-title-sm">{__('Get Support', 'shois-chat-button')}</h4>
                                <p className="shcb-dash-card-desc-xs mb-3">{__('Our team is here to help you.', 'shois-chat-button')}</p>
                                <a href="https://wordpress.org/support/plugin/shois-chat-button/" target="_blank" className="shcb-dash-btn-outline">{__('Contact Us', 'shois-chat-button')}</a>
                            </div>
                        </div>
                    </div>
                </div>

                <div className="shcb-dash-col-right">
                    <h3 className="shcb-dash-section-title">{__('Our Other Plugins', 'shois-chat-button')}</h3>
                    <div className="shcb-dash-grid-3">
                        {RECOMMENDED_PLUGINS.map((plugin) => {
                            const status = pluginStatus[plugin.id] || { installed: false, active: false };
                            const isLoading = actionLoading === plugin.id;

                            return (
                                <div key={plugin.id} className="shcb-dash-card shcb-dash-card-plugin group">
                                    <div className={`shcb-dash-icon-square ${plugin.colorClass} text-white mb-3`}>
                                        {plugin.icon}
                                    </div>
                                    <h4 className="shcb-dash-card-title-sm">{plugin.title}</h4>
                                    <p className="shcb-dash-card-desc-xs mb-4">{plugin.desc}</p>
                                    
                                    <div className="mt-auto">
                                        {status.active ? (
                                            <span className="shcb-plugin-status-active">
                                                <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><polyline points="20 6 9 17 4 12"></polyline></svg>
                                                {__('Active', 'shois-chat-button')}
                                            </span>
                                        ) : status.installed ? (
                                            <button 
                                                className="shcb-plugin-action-btn shcb-plugin-activate"
                                                onClick={() => handlePluginAction(plugin.id, 'activate')}
                                                disabled={isLoading}
                                            >
                                                {isLoading ? __('Activating...', 'shois-chat-button') : __('Activate', 'shois-chat-button')}
                                            </button>
                                        ) : (
                                            <button 
                                                className="shcb-plugin-action-btn shcb-plugin-install"
                                                onClick={() => handlePluginAction(plugin.id, 'install')}
                                                disabled={isLoading}
                                            >
                                                {isLoading ? __('Installing...', 'shois-chat-button') : __('Install Now', 'shois-chat-button')}
                                            </button>
                                        )}
                                    </div>
                                </div>
                            );
                        })}
                    </div>
                </div>
            </div>

            {/* Premium CTA */}
            <section className="shcb-dash-premium-banner" style={{marginTop: '32px'}}>
                <div className="shcb-dash-banner-inner">
                    <div className="shcb-dash-banner-content">
                        <div className="shcb-dash-banner-text">
                            <h2 className="shcb-dash-banner-title">{__('Unlock Premium Features', 'shois-chat-button')}</h2>
                            <p className="shcb-dash-banner-subtitle">{__('Scale your customer support with advanced tools.', 'shois-chat-button')}</p>
                        </div>
                        <div className="shcb-dash-banner-features">
                            <div className="shcb-dash-feature">
                                <svg width="14" height="14" 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 2zm-2 15l-5-5 1.41-1.41L10 14.17l7.59-7.59L19 8l-9 9z"></path></svg>
                                {__('Multi-agent', 'shois-chat-button')}
                            </div>
                            <div className="shcb-dash-feature">
                                <svg width="14" height="14" 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 2zm-2 15l-5-5 1.41-1.41L10 14.17l7.59-7.59L19 8l-9 9z"></path></svg>
                                {__('Analytics', 'shois-chat-button')}
                            </div>
                            <div className="shcb-dash-feature">
                                <svg width="14" height="14" 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 2zm-2 15l-5-5 1.41-1.41L10 14.17l7.59-7.59L19 8l-9 9z"></path></svg>
                                {__('Rules', 'shois-chat-button')}
                            </div>

                        </div>
                    </div>
                    <div className="shcb-dash-banner-action">
                        <a href={window.shcbAdmin?.upgradeUrl || '#'} className="shcb-dash-btn-white" style={{ display: 'inline-block', textDecoration: 'none' }}>
                            {__('Upgrade Now', 'shois-chat-button')}
                        </a>
                    </div>
                </div>
                <div className="shcb-dash-banner-glow"></div>
            </section>
        </div>
    );
}

/**
 * Main App component.
 *
 * @return {JSX.Element} The admin application.
 */
export default function App() {
    const [activeTab, setActiveTab] = useState(getTabFromHash);
    const [widgetActive, setWidgetActive] = useState(false);
    const [saving, setSaving] = useState(false);
    const [editingTemplate, setEditingTemplate] = useState(null);
    const [showProToast, setShowProToast] = useState(false);

    // Listen for PRO feature clicks to show toast.
    useEffect(() => {
        let timeout;
        const handleProAlert = () => {
            setShowProToast(true);
            if (timeout) clearTimeout(timeout);
            timeout = setTimeout(() => setShowProToast(false), 5000);
        };
        window.addEventListener('shcb-pro-alert', handleProAlert);
        return () => {
            window.removeEventListener('shcb-pro-alert', handleProAlert);
            if (timeout) clearTimeout(timeout);
        };
    }, []);

    // Load initial widget state from settings.
    useEffect(() => {
        apiFetch({ path: '/shois-chat/v1/settings' })
            .then((settings) => {
                if (settings && typeof settings.active !== 'undefined') {
                    setWidgetActive(!!settings.active);
                }
            })
            .catch(() => {});
    }, []);

    // Listen for hash changes.
    useEffect(() => {
        const handleHashChange = () => {
            setActiveTab(getTabFromHash());
        };
        window.addEventListener('hashchange', handleHashChange);
        return () => window.removeEventListener('hashchange', handleHashChange);
    }, []);

    /**
     * Change the active tab.
     *
     * @param {string} tabId The tab to navigate to.
     */
    const handleTabChange = (tabId) => {
        window.location.hash = '#/' + tabId;
        setActiveTab(tabId);
        setEditingTemplate(null);
    };

    /**
     * Toggle widget active state and persist to server.
     */
    const handleWidgetToggle = useCallback(() => {
        const newState = !widgetActive;
        setWidgetActive(newState);
        setSaving(true);

        apiFetch({
            path: '/shois-chat/v1/settings',
            method: 'POST',
            data: { active: newState },
        })
            .catch(() => {
                setWidgetActive(!newState); // Revert on error.
            })
            .finally(() => {
                setSaving(false);
            });
    }, [widgetActive]);

    /**
     * Get the page title for the current tab.
     *
     * @return {string} The page title.
     */
    const getPageTitle = () => {
        const tab = TABS.find((t) => t.id === activeTab);
        if (activeTab === 'templates' && editingTemplate) {
            return __('Template Editor', 'shois-chat-button');
        }
        return tab ? tab.label : __('Dashboard', 'shois-chat-button');
    };

    /**
     * Render the active tab content.
     *
     * @return {JSX.Element} Tab content.
     */
    const renderTabContent = () => {
        // Template editor sub-view.
        if (activeTab === 'templates' && editingTemplate) {
            return (
                <TemplateEditor
                    template={editingTemplate}
                    onBack={() => setEditingTemplate(null)}
                />
            );
        }

        switch (activeTab) {
            case 'dashboard':
                return <DashboardPage onTabChange={handleTabChange} />;
            case 'templates':
                return <TemplatesPage onEditTemplate={(tpl) => setEditingTemplate(tpl)} />;
            case 'agents':
                return <AgentsPage />;
            case 'analytics':
                return <AnalyticsPage />;
            case 'settings':
                return <SettingsPage widgetActive={widgetActive} onWidgetToggle={handleWidgetToggle} />;
            default:
                return <DashboardPage onTabChange={handleTabChange} />;
        }
    };

    return (
        <div className="shcb-admin-app">
            <Sidebar
                activeTab={activeTab}
                onTabChange={handleTabChange}
            />
            <div className="shcb-main-column">
                <TopBar
                    pageTitle={getPageTitle()}
                    active={widgetActive}
                    onToggle={handleWidgetToggle}
                    saving={saving}
                />
                <div className="shcb-admin-content">
                    {renderTabContent()}
                </div>
            </div>

            {/* Pro Upgrade Toast Notification */}
            <div 
                className={`shcb-pro-toast ${showProToast ? 'shcb-pro-toast-visible' : ''}`}
                style={{
                    position: 'fixed',
                    bottom: showProToast ? '24px' : '-100px',
                    right: '24px',
                    background: '#1e293b',
                    color: '#fff',
                    padding: '16px 20px',
                    borderRadius: '8px',
                    boxShadow: '0 10px 25px -5px rgba(0, 0, 0, 0.3)',
                    display: 'flex',
                    alignItems: 'center',
                    gap: '16px',
                    transition: 'bottom 0.4s cubic-bezier(0.175, 0.885, 0.32, 1.275), opacity 0.4s ease',
                    opacity: showProToast ? 1 : 0,
                    zIndex: 9999,
                    maxWidth: '400px'
                }}
            >
                <div style={{
                    width: '32px',
                    height: '32px',
                    background: 'rgba(255, 255, 255, 0.1)',
                    borderRadius: '50%',
                    display: 'flex',
                    alignItems: 'center',
                    justifyContent: 'center',
                    flexShrink: 0
                }}>
                    <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="#facc15" strokeWidth="2">
                        <path d="M12 2l3.09 6.26L22 9.27l-5 4.87 1.18 6.88L12 17.77l-6.18 3.25L7 14.14 2 9.27l6.91-1.01L12 2z" fill="#facc15"/>
                    </svg>
                </div>
                <div style={{ flex: 1 }}>
                    <h4 style={{ margin: '0 0 4px 0', fontSize: '14px', fontWeight: '600', color: '#fff' }}>
                        {__('Premium Feature', 'shois-chat-button')}
                    </h4>
                    <p style={{ margin: 0, fontSize: '13px', color: '#94a3b8', lineHeight: '1.4' }}>
                        {__('Upgrade to PRO to unlock this setting and scale your support.', 'shois-chat-button')}
                    </p>
                </div>
                <a 
                    href={window.shcbAdmin?.upgradeUrl || '#'}
                    style={{
                        background: '#5170ff',
                        color: '#fff',
                        textDecoration: 'none',
                        padding: '8px 16px',
                        borderRadius: '6px',
                        fontSize: '13px',
                        fontWeight: '500',
                        whiteSpace: 'nowrap',
                        transition: '0.2s'
                    }}
                    onMouseEnter={(e) => e.target.style.background = '#4338ca'}
                    onMouseLeave={(e) => e.target.style.background = '#5170ff'}
                >
                    {__('Upgrade Now', 'shois-chat-button')}
                </a>
            </div>
        </div>
    );
}
