/**
 * 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 }) {
    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 ChatWidget Pro, 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 ChatWidget Pro.', 'shois-chat-button')}</p>
                                <a href="#" 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="#" 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">
                        {/* Plugin 1 */}
                        <div className="shcb-dash-card shcb-dash-card-plugin group">
                            <div className="shcb-dash-icon-square bg-indigo text-white mb-3">
                                <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><line x1="8" y1="6" x2="21" y2="6"></line><line x1="8" y1="12" x2="21" y2="12"></line><line x1="8" y1="18" x2="21" y2="18"></line><line x1="3" y1="6" x2="3.01" y2="6"></line><line x1="3" y1="12" x2="3.01" y2="12"></line><line x1="3" y1="18" x2="3.01" y2="18"></line></svg>
                            </div>
                            <h4 className="shcb-dash-card-title-sm">{__('FormBuilder Pro', 'shois-chat-button')}</h4>
                            <p className="shcb-dash-card-desc-xs mb-4">{__('Powerful drag & drop forms for WordPress.', 'shois-chat-button')}</p>
                            <a href="#" className="shcb-dash-link-btn-sm group-hover-underline mt-auto">{__('Explore →', 'shois-chat-button')}</a>
                        </div>
                        {/* Plugin 2 */}
                        <div className="shcb-dash-card shcb-dash-card-plugin group">
                            <div className="shcb-dash-icon-square bg-red-500 text-white mb-3">
                                <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>
                            </div>
                            <h4 className="shcb-dash-card-title-sm">{__('Security Shield', 'shois-chat-button')}</h4>
                            <p className="shcb-dash-card-desc-xs mb-4">{__('Enterprise-grade protection for your site.', 'shois-chat-button')}</p>
                            <a href="#" className="shcb-dash-link-btn-sm group-hover-underline mt-auto">{__('Explore →', 'shois-chat-button')}</a>
                        </div>
                        {/* Plugin 3 */}
                        <div className="shcb-dash-card shcb-dash-card-plugin group">
                            <div className="shcb-dash-icon-square bg-amber-500 text-white mb-3">
                                <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><circle cx="11" cy="11" r="8"></circle><line x1="21" y1="21" x2="16.65" y2="16.65"></line></svg>
                            </div>
                            <h4 className="shcb-dash-card-title-sm">{__('SEO Master', 'shois-chat-button')}</h4>
                            <p className="shcb-dash-card-desc-xs mb-4">{__('Boost your search rankings automatically.', 'shois-chat-button')}</p>
                            <a href="#" className="shcb-dash-link-btn-sm group-hover-underline mt-auto">{__('Explore →', 'shois-chat-button')}</a>
                        </div>
                    </div>
                </div>
            </div>

            {/* Premium CTA */}
            <section className="shcb-dash-premium-banner">
                <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">
                        <button className="shcb-dash-btn-white">{__('Upgrade Now', 'shois-chat-button')}</button>
                    </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);

    // 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 />;
            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>
        </div>
    );
}
