import { useState, useEffect } from '@wordpress/element';
import { __ } from '@wordpress/i18n';
import Dashboard from './pages/Dashboard';
import Bookings from './pages/Bookings';
import BookingDetail from './pages/BookingDetail';
import Services from './pages/Services';
import ServiceEditor from './pages/ServiceEditor';
import Settings from './pages/Settings';

/**
 * Merge Pro-registered nav items into the built-in list.
 *
 * Appointly Pro (the separate companion plugin) can register additional
 * navigation items by setting `window.appointlyAdmin.proNavItems` before our
 * React app mounts. Each Pro item may specify an `after` key to position
 * itself directly after a built-in item; items without `after` append at
 * the end. If the `after` target is missing, the item appends at the end.
 *
 * Pro items get an `isPro: true` flag so the nav can render a Pro badge.
 *
 * @param {Array} builtIn - Free's built-in nav items (canonical order).
 * @param {Array} proItems - Pro-registered items (may be undefined).
 * @returns {Array} Merged nav item list.
 */
const mergeNavItems = (builtIn, proItems) => {
    if (!Array.isArray(proItems) || proItems.length === 0) {
        return builtIn;
    }
    const result = [...builtIn];
    proItems.forEach((item) => {
        if (!item || !item.path || !item.label) return;
        const afterIdx = item.after
            ? result.findIndex((i) => i.path === item.after)
            : -1;
        const entry = { ...item, isPro: true };
        if (afterIdx >= 0) {
            result.splice(afterIdx + 1, 0, entry);
        } else {
            result.push(entry);
        }
    });
    return result;
};

export default function App() {
    const [currentPath, setCurrentPath] = useState(window.location.hash.slice(1) || '/');

    useEffect(() => {
        const handleHashChange = () => {
            setCurrentPath(window.location.hash.slice(1) || '/');
        };
        window.addEventListener('hashchange', handleHashChange);
        return () => window.removeEventListener('hashchange', handleHashChange);
    }, []);

    const navigate = (path) => {
        window.location.hash = path;
    };

    // -------------------------------------------------------------
    // Free built-in nav items (canonical order)
    // -------------------------------------------------------------
    const builtInNavItems = [
        { path: '/dashboard', label: __('Dashboard', 'appointly'), icon: 'dashboard' },
        { path: '/bookings',  label: __('Bookings', 'appointly'),  icon: 'calendar' },
        { path: '/services',  label: __('Services', 'appointly'),  icon: 'admin-generic' },
        { path: '/settings',  label: __('Settings', 'appointly'),  icon: 'admin-settings' },
    ];

    // -------------------------------------------------------------
    // Appointly Pro extension points
    //
    // If Appointly Pro (the separate companion plugin) is installed
    // and active, it will populate these globals BEFORE our React app
    // mounts. Free reads them safely: if Pro is not present, both are
    // empty / falsy and nothing changes.
    //
    // Pro is expected to:
    //   window.appointlyAdmin.proNavItems = [
    //     { path: '/recurring', label: 'Recurring', icon: 'update', after: '/services' },
    //     ...
    //   ];
    //   window.appointlyAdmin.proRoutes = {
    //     '/recurring': ProRecurringPage,
    //     ...
    //   };
    //
    // See docs/plans/... for the full Pro architecture.
    // -------------------------------------------------------------
    const proNavItems = window.appointlyAdmin?.proNavItems || [];
    const proRoutes   = window.appointlyAdmin?.proRoutes || {};

    const navItems = mergeNavItems(builtInNavItems, proNavItems);

    // Simple route matching
    const getPage = () => {
        // Pro routes take precedence for their own registered paths.
        if (proRoutes[currentPath]) {
            const ProComponent = proRoutes[currentPath];
            return <ProComponent navigate={navigate} />;
        }

        if (currentPath === '/' || currentPath === '/dashboard') return <Dashboard />;
        if (currentPath === '/bookings') return <Bookings navigate={navigate} />;
        if (currentPath.startsWith('/bookings/')) {
            const id = currentPath.split('/')[2];
            return <BookingDetail id={id} navigate={navigate} />;
        }
        if (currentPath === '/services') return <Services navigate={navigate} />;
        if (currentPath.startsWith('/services/')) {
            const serviceId = currentPath.split('/')[2];
            return <ServiceEditor id={serviceId} navigate={navigate} />;
        }
        if (currentPath === '/settings') return <Settings />;
        return <Dashboard />;
    };

    return (
        <div className="appointly-admin">
            <div className="appointly-admin__header">
                <h1>{__('Appointly', 'appointly')}</h1>
                <nav className="appointly-admin__nav">
                    {navItems.map((item) => {
                        const isActive = currentPath === item.path
                            || (item.path !== '/dashboard' && currentPath.startsWith(item.path + '/'));
                        return (
                            <a
                                key={item.path}
                                href={'#' + item.path}
                                className={
                                    'appointly-admin__nav-item'
                                    + (isActive ? ' is-active' : '')
                                    + (item.isPro ? ' appointly-admin__nav-item--pro' : '')
                                }
                                onClick={(e) => { e.preventDefault(); navigate(item.path); }}
                            >
                                <span className={`dashicons dashicons-${item.icon}`}></span>
                                {item.label}
                                {item.isPro && (
                                    <span className="appointly-admin__nav-pro-badge">{__('Pro', 'appointly')}</span>
                                )}
                            </a>
                        );
                    })}
                </nav>
            </div>
            <div className="appointly-admin__content">
                {getPage()}
            </div>
        </div>
    );
}
