import { salesforceApplicationAPI } from '../infrastructure/api/salesforce-application';
import { resolveAppLaunchDestination } from '../core/navigation/appLaunch';
import { apiClient } from '../infrastructure/api/client';
import React, { useState, useEffect, useCallback, useRef } from 'react';
import { useParams, useNavigate, useSearchParams } from 'react-router-dom';
import { ArrowLeft, Box, ExternalLink } from 'lucide-react';
import { applicationNavigationAPI, fromNavigationEntry, toNavigationEntry, type NavigationDocument, type NavigationSave } from '../infrastructure/api/application-navigation';
import { getStandardPageTab, standardPageTabKeys } from '../core/navigation/standardPageTabs';
import { metadataAPI } from '../infrastructure/api/metadata';
import type { AppConfig, SObjectDescribe, NavigationItem } from '../types';
import { registerHostSessionLifecycleListener, generateUUID } from '@nexuscrm/host-sdk';
import { StudioSidebar } from '../features/studio/components/StudioSidebar';
import { StudioObjectEditor } from '../features/studio/components/StudioObjectEditor';
import { StudioPermissions } from '../features/studio/components/StudioPermissions';
import { StudioDashboardEditor } from '../features/studio/components/StudioDashboardEditor';
import type { DashboardWidgetInspectorRenderer } from '../features/studio/components/dashboard/DashboardInspector';
import { AppSettingsEditor } from '../features/studio/components/AppSettingsEditor';
import { getColorClasses } from '../core/utils/colorClasses';
import { useErrorToast } from '@nexuscrm/salesforce-crm-standard-frontend/platform/components/ui';
import { Logger } from '../core/services/Logger';
import type { DashboardWidgetRegistryHandle } from '../features/dashboard/dashboardWidgetRegistry';
import { buildNewDashboardConfig } from '../features/studio/dashboardConfigFactory';
import { tryGetSetupCapabilityPagePath } from '../core/navigation/setupPagePaths';
import { useApp } from '@nexuscrm/host-sdk';

type EditorMode = 'object' | 'dashboard' | 'settings' | 'permissions' | 'navigation' | null;

interface EditorState {
    mode: EditorMode;
    itemId?: string;
    objectApiName?: string;
    dashboardId?: string;
}

interface AppStudioProps {
    dashboardWidgets: DashboardWidgetRegistryHandle;
    renderDashboardWidgetInspector?: DashboardWidgetInspectorRenderer;
}

export const AppStudio: React.FC<AppStudioProps> = ({
    dashboardWidgets,
    renderDashboardWidgetInspector,
}) => {
    const errorToast = useErrorToast();
    const { appId } = useParams<{ appId: string }>();
    const navigate = useNavigate();
    const { currentFrontendAppId, refreshApps, visibleApps, setCurrentAppId } = useApp();
    const isNewApp = appId === 'new';
    const externalSalesforce = apiClient.getSessionConnectionKind() === 'external';

    const [servingIdentity, setServingIdentity] = useState<{ routeId: string; id: string } | null>(null);
    const [launchError, setLaunchError] = useState<string | null>(null);
    const launchCandidates = visibleApps?.filter(candidate => externalSalesforce
        ? servingIdentity?.routeId === appId && candidate.id.split(':')[0] === servingIdentity.id
        : candidate.id === appId);
    const launchApp = launchCandidates?.length === 1 ? launchCandidates[0] : undefined;
    const launchDestination = resolveAppLaunchDestination(launchApp, currentFrontendAppId);

    const [searchParams] = useSearchParams();

    // App state
    const [app, setApp] = useState<AppConfig>({
        id: '',
        label: '',
        description: '',
        icon: 'Layers',
        color: 'blue',
        navigationItems: [],
    });
    const [loading, setLoading] = useState(!isNewApp);
    const [saving, setSaving] = useState(false);

    const [navigationBaseline, setNavigationBaseline] = useState<NavigationDocument | null>(null);
    const [navigationDirty, setNavigationDirty] = useState(false);
    const [loadError, setLoadError] = useState<string | null>(null);
    const [navigationLoadError, setNavigationLoadError] = useState<string | null>(null);
    const [refreshFailed, setRefreshFailed] = useState(false);
    const [navigationConflict, setNavigationConflict] = useState(false);
    const routeGeneration = useRef(0);
    const sessionActive = useRef(true);
    const [sessionRevision, setSessionRevision] = useState(0);
    const sessionEpoch = useRef(0);
    const ownsSession = useCallback(() => sessionActive.current && sessionEpoch.current === sessionRevision, [sessionRevision]);
    const saveInFlight = useRef(false);
    const pendingSave = useRef<{ id: string; request: NavigationSave } | null>(null);

    // Available objects and dashboards for adding to nav
    const [availableObjects, setAvailableObjects] = useState<SObjectDescribe[]>([]);
    const [availableDashboards, setAvailableDashboards] = useState<{ Id: string; Label: string; Description?: string }[]>([]);

    // Editor state - what's currently being edited in the right panel
    // For new apps, open settings first so user can fill in required App ID
    const [editor, setEditor] = useState<EditorState>({ mode: isNewApp ? 'settings' : null });



    const resetDraft = useCallback(() => {
        setLoading(sessionActive.current && !isNewApp);
        setApp({ id: '', label: '', description: '', icon: 'Layers', color: 'blue', navigationItems: [] });
        setAvailableObjects([]);
        setAvailableDashboards([]);
        setLoadError(null);
        setServingIdentity(null);
        setLaunchError(null);
        setNavigationLoadError(null);
        setNavigationBaseline(null);
        setNavigationDirty(false);
        setRefreshFailed(false);
        setNavigationConflict(false);
        pendingSave.current = null;
        saveInFlight.current = false;
        setSaving(false);
        setEditor({ mode: isNewApp ? 'settings' : externalSalesforce ? 'settings' : null });
    }, [isNewApp, externalSalesforce]);

    useEffect(() => {
        const transition = (authenticated: boolean) => {
            // Invalidate immediately, before React runs the next load effect.
            ++routeGeneration.current;
            sessionActive.current = authenticated;
            // Clear render state in this notification, not in a later effect.
            // The epoch also rejects old callbacks before React commits it.
            resetDraft();
            setSessionRevision(++sessionEpoch.current);
        };
        return registerHostSessionLifecycleListener({
            onCleared: () => transition(false), onAuthenticated: () => transition(true),
        });
    }, [resetDraft]);

    const shouldOpenAddModal = searchParams.get('action') === 'add_page';

    const loadApp = useCallback(async (id: string, generation: number) => {
        try {
            const foundApp = await metadataAPI.getApplicationDefinition(id);
            if (routeGeneration.current !== generation) return;
            // App settings do not depend on navigation authoring permission or
            // availability. The serving projection remains read-only until a
            // complete authoring document has been loaded.
            setApp(foundApp);
            setLoading(false);
            if (apiClient.getSessionConnectionKind() === 'external') {
                try {
                    const servingId = await salesforceApplicationAPI.resolveServingId(id);
                    if (routeGeneration.current === generation) setServingIdentity({ routeId: id, id: servingId });
                } catch {
                    if (routeGeneration.current === generation) setLaunchError('Unable to resolve the application launch target.');
                }
                return;
            }
            try {
                const document = await applicationNavigationAPI.read(id);
                if (routeGeneration.current !== generation) return;
                setApp(prev => ({ ...prev, navigationItems: document.items.map(fromNavigationEntry) }));
                setNavigationBaseline(document);
            } catch (error: unknown) {
                if (routeGeneration.current === generation) setNavigationLoadError(error instanceof Error ? error.message : 'Unable to load navigation');
            }
        } catch (error: unknown) {
            if (routeGeneration.current === generation) setLoadError(error instanceof Error ? error.message : 'Unable to load navigation');
        } finally {
            if (routeGeneration.current === generation) setLoading(false);
        }
    }, []);

    const loadMetadata = useCallback(async (generation = routeGeneration.current) => {
        try {
            const [schemasRes, dashboardsRes] = await Promise.all([
                metadataAPI.getSchemas(),
                metadataAPI.getDashboards()
            ]);
            if (routeGeneration.current !== generation) return;
            setAvailableObjects(schemasRes.schemas || []);
            setAvailableDashboards((dashboardsRes.dashboards || []).map(d => ({
                Id: d.id,
                Label: d.label,
                Description: d.description
            })));
        } catch (error: unknown) {
            if (routeGeneration.current !== generation) return;
            // Loading failure - log for debugging
            Logger.warn('AppStudio: Failed to load metadata:', error instanceof Error ? error.message : error);
        }
    }, []);

    useEffect(() => {
        const generation = ++routeGeneration.current;
        resetDraft();
        if (!sessionActive.current) {
            setLoadError('Sign in to load this application.');
            return () => { ++routeGeneration.current; };
        }
        if (!isNewApp && appId) void loadApp(appId, generation);
        void loadMetadata(generation);
        return () => { ++routeGeneration.current; };
    }, [appId, isNewApp, loadApp, loadMetadata, externalSalesforce, sessionRevision, resetDraft]);

    // Apply route intent after initialization resets the previous editor. A
    // query-only change selects its editor without discarding navigation edits.
    useEffect(() => {
        if (!sessionActive.current || externalSalesforce || isNewApp) return;
        const dashboardId = searchParams.get('dashboardId');
        if (dashboardId) setEditor({ mode: 'dashboard', dashboardId });
    }, [appId, searchParams, sessionRevision, externalSalesforce, isNewApp]);

    const refreshNavigation = async (generation: number) => {
        try {
            await refreshApps({ throwOnError: true, notifyOtherTabs: true });
            if (routeGeneration.current === generation) setRefreshFailed(false);
        } catch {
            if (routeGeneration.current === generation) setRefreshFailed(true);
        }
    };

    const handleSaveNavigation = async () => {
        if (!ownsSession() || saveInFlight.current || !navigationBaseline || navigationConflict) return;
        saveInFlight.current = true;
        setSaving(true);
        const generation = routeGeneration.current;
        try {
            // Keep the exact key and payload after an uncertain response. A retry
            // must reconcile that commit before accepting more draft edits.
            pendingSave.current ??= { id: app.id, request: {
                expected_revision: navigationBaseline.revision,
                idempotency_key: generateUUID(),
                items: (app.navigationItems ?? []).map(toNavigationEntry),
            } };
            const attempt = pendingSave.current;
            const document = await applicationNavigationAPI.save(attempt.id, attempt.request);
            if (routeGeneration.current !== generation) return;
            pendingSave.current = null;
            setNavigationBaseline(document);
            setApp(prev => ({ ...prev, navigationItems: document.items.map(fromNavigationEntry) }));
            setNavigationDirty(false);
            await refreshNavigation(generation);
        } catch (error: unknown) {
            if (routeGeneration.current === generation) {
                // Definite rejection did not commit. Keep the draft available for
                // review; a conflict requires reading the new revision explicitly.
                if (typeof error === 'object' && error !== null && 'status' in error &&
                    typeof error.status === 'number' && error.status >= 400 && error.status < 500 && error.status !== 408) {
                    pendingSave.current = null;
                    if (error.status === 409) setNavigationConflict(true);
                }
                errorToast(error instanceof Error ? error.message : 'Unable to save navigation');
            }
        } finally {
            if (routeGeneration.current === generation) { saveInFlight.current = false; setSaving(false); }
        }
    };

    const reloadLatestNavigation = async () => {
        if (!ownsSession() || saveInFlight.current || !appId || pendingSave.current) return;
        const generation = routeGeneration.current;
        saveInFlight.current = true;
        setSaving(true);
        try {
            const document = await applicationNavigationAPI.read(appId);
            if (routeGeneration.current !== generation) return;
            setNavigationBaseline(document);
            setApp(prev => ({ ...prev, navigationItems: document.items.map(fromNavigationEntry) }));
            setNavigationDirty(false);
            setNavigationConflict(false);
        } catch (error: unknown) {
            if (routeGeneration.current === generation) errorToast(error instanceof Error ? error.message : 'Unable to load latest navigation');
        } finally {
            if (routeGeneration.current === generation) { saveInFlight.current = false; setSaving(false); }
        }
    };

    const updateApp = useCallback((updates: Partial<AppConfig>) => {
        if (!ownsSession() || saveInFlight.current || pendingSave.current || ('navigationItems' in updates && !navigationBaseline)) return;
        setApp(prev => ({ ...prev, ...updates }));
        if ('navigationItems' in updates) setNavigationDirty(true);
    }, [navigationBaseline, ownsSession]);

    const handleNavItemSelect = (item: NavigationItem) => {
        if (!ownsSession()) return false;
        if (item.type === 'object' && item.objectApiName) {
            setEditor({ mode: 'object', objectApiName: item.objectApiName });
        } else if (item.type === 'dashboard' && item.dashboardId) {
            setEditor({ mode: 'dashboard', dashboardId: item.dashboardId });
        } else {
            setEditor({ mode: 'navigation', itemId: item.id });
        }
    };

    const handleAddExistingObject = (objectDef: SObjectDescribe) => {
        if (!ownsSession()) return false;
        const newNavItem: NavigationItem = {
            id: `nav-${objectDef.name}-${Date.now()}`,
            type: 'object',
            objectApiName: objectDef.name,
            label: objectDef.labelPlural || objectDef.label + 's',
            icon: objectDef.icon || 'Box', // Default icon
        };
        const updatedNavItems = [...(app.navigationItems || []), newNavItem];
        updateApp({ navigationItems: updatedNavItems });
        setEditor({ mode: 'object', objectApiName: objectDef.name });
    };

    const handleAddExistingDashboard = (dashboardDef: { Id: string; Label: string }) => {
        if (!ownsSession()) return false;
        const newNavItem: NavigationItem = {
            id: `nav-dash-${dashboardDef.Id}-${Date.now()}`,
            type: 'dashboard',
            dashboardId: dashboardDef.Id,
            label: dashboardDef.Label,
            icon: 'LayoutDashboard',
        };
        const updatedNavItems = [...(app.navigationItems || []), newNavItem];
        updateApp({ navigationItems: updatedNavItems });
        setEditor({ mode: 'dashboard', dashboardId: dashboardDef.Id });
    };

    const handleCreateNewObject = async (objectDef: { label: string; apiName: string; icon: string }) => {
        if (!ownsSession()) return false;
        const generation = routeGeneration.current;
        // Create the object via API
        await metadataAPI.createSchema({
            name: objectDef.apiName,
            label: objectDef.label,
            labelPlural: objectDef.label + 's',
            icon: objectDef.icon,
            description: `Custom object: ${objectDef.label}`,
        });
        if (routeGeneration.current !== generation) return false;

        updateApp({ navigationItems: [...(app.navigationItems ?? []), {
            id: generateUUID(), type: 'object', objectApiName: objectDef.apiName,
            label: objectDef.label + 's', icon: objectDef.icon,
        }] });

        // Refresh objects list and select the new object
        await loadMetadata(generation);
        if (routeGeneration.current !== generation) return false;
        setEditor({ mode: 'object', objectApiName: objectDef.apiName });

        return true;
    };

    const handleCreateNewDashboard = async (dashboardDef: { label: string; icon: string }) => {
        if (!ownsSession()) return false;
        const generation = routeGeneration.current;
        const newDashboard = buildNewDashboardConfig({ label: dashboardDef.label });

        const createResult = await metadataAPI.createDashboard(newDashboard, dashboardWidgets);
        if (routeGeneration.current !== generation) return false;
        const dashboardId = createResult.dashboard.id || newDashboard.id;

        // Add to navigation
        const newNavItem: NavigationItem = {
            id: `nav-dash-${dashboardId}-${Date.now()}`,
            type: 'dashboard',
            dashboardId,
            label: dashboardDef.label,
            icon: dashboardDef.icon,
        };

        const updatedNavItems = [...(app.navigationItems || []), newNavItem];
        updateApp({ navigationItems: updatedNavItems });

        await loadMetadata(generation);
        if (routeGeneration.current !== generation) return false;
        setEditor({ mode: 'dashboard', dashboardId });

        return true;
    };




    const handleAddWebLink = async (def: { label: string; url: string; icon: string }) => {
        if (!ownsSession()) return false;
        const item: NavigationItem = { id: generateUUID(), type: 'web', label: def.label, pageUrl: def.url, icon: def.icon };
        updateApp({ navigationItems: [...(app.navigationItems ?? []), item] });
        setEditor({ mode: 'navigation', itemId: item.id });
        return true;
    };

    const handleAddStandard = (key: string) => {
        if (!ownsSession()) return false;
        const page = getStandardPageTab(app.frontendAppId ?? currentFrontendAppId, key);
        if (!page) { errorToast('This page is not registered for this app'); return; }
        const item: NavigationItem = { id: generateUUID(), type: 'page', objectApiName: key, label: page.label, icon: page.icon };
        updateApp({ navigationItems: [...(app.navigationItems ?? []), item] });
        setEditor({ mode: 'navigation', itemId: item.id });
    };

    const handleReorderNavItems = (items: NavigationItem[]) => updateApp({ navigationItems: items });

    const handleRemoveNavItem = (itemId: string) => {
        if (!ownsSession()) return false;
        updateApp({ navigationItems: (app.navigationItems ?? []).filter(item => item.id !== itemId) });
        if (editor.itemId === itemId) setEditor({ mode: null });

        // Clear editor if removed item was selected
        if (editor.mode === 'object') {
            const removedItem = app.navigationItems?.find(item => item.id === itemId);
            if (removedItem?.objectApiName === editor.objectApiName) {
                setEditor({ mode: null });
            }
        } else if (editor.mode === 'dashboard') {
            const removedItem = app.navigationItems?.find(item => item.id === itemId);
            if (removedItem?.dashboardId === editor.dashboardId) {
                setEditor({ mode: null });
            }
        }
    };

    if (loading) {
        return (
            <div className="h-screen flex items-center justify-center bg-slate-50">
                <div className="animate-spin rounded-full h-8 w-8 border-b-2 border-blue-600"></div>
            </div>
        );
    }

    if (loadError || isNewApp) {
        return (
            <div className="h-screen flex items-center justify-center bg-slate-50">
                <div className="text-slate-500">{loadError || (externalSalesforce ? 'External Salesforce application editing is not supported. Manage applications in Salesforce Setup.' : 'Applications are supplied by the installed application release.')}</div>
            </div>
        );
    }

    return (
        <div className="h-screen flex flex-col bg-slate-50 overflow-hidden">
            {/* Top Bar */}
            <header className="bg-white border-b border-slate-200 h-14 flex items-center justify-between px-4 flex-shrink-0 z-10">
                <div className="flex items-center gap-4">
                    <button onClick={() => navigate(tryGetSetupCapabilityPagePath(currentFrontendAppId, 'appManager') ?? '/')} className="p-2 hover:bg-slate-100 rounded-lg text-slate-500">
                        <ArrowLeft size={20} />
                    </button>
                    <div className="flex items-center gap-3">
                        <div className={`w-8 h-8 rounded-lg flex items-center justify-center ${getColorClasses(app.color)}`}>
                            <Box size={18} />
                        </div>
                        <div>
                            <h1 className="font-semibold text-slate-800">{app.label || 'New App'}</h1>
                            <div className="text-xs text-slate-500">App Studio</div>
                        </div>
                    </div>
                </div>
                <div className="flex items-center gap-2">
                    {navigationDirty && (
                        <span className="text-xs text-amber-600 bg-amber-50 px-2 py-1 rounded border border-amber-200">
                            Unsaved changes
                        </span>
                    )}
                    {!isNewApp && (
                        <button
                            disabled={!launchDestination}
                            title={launchDestination ? undefined : launchError ?? 'No accessible navigation is available for this application'}
                            onClick={() => {
                                if (!ownsSession() || !launchDestination || !launchApp) return;
                                setCurrentAppId(launchApp.id);
                                window.open(launchDestination.href, '_blank', 'noopener,noreferrer');
                            }}
                            className="flex items-center gap-2 px-3 py-1.5 text-slate-600 hover:bg-slate-100 rounded-lg text-sm font-medium transition-colors"
                        >
                            <ExternalLink size={16} />
                            Launch App
                        </button>
                    )}
                    {!isNewApp && !externalSalesforce && <>
                        <button disabled={saving || !navigationBaseline || !navigationDirty || !!pendingSave.current} onClick={() => {
                            if (!ownsSession()) return;
                            if (navigationBaseline) {
                                setApp(prev => ({ ...prev, navigationItems: navigationBaseline.items.map(fromNavigationEntry) }));
                                if (editor.itemId && !navigationBaseline.items.some(item => item.id === editor.itemId)) {
                                    setEditor({ mode: null });
                                }
                            }
                            setNavigationDirty(false);
                        }} className="px-3 py-1.5 text-sm disabled:opacity-50">Cancel navigation changes</button>
                        <button disabled={saving || !navigationBaseline || !navigationDirty || navigationConflict} onClick={handleSaveNavigation} className="px-3 py-1.5 bg-blue-600 text-white rounded-lg text-sm disabled:opacity-50">
                            {pendingSave.current ? 'Retry navigation save' : 'Save navigation'}
                        </button>
                    </>}

                </div>
            </header>

            {navigationLoadError && <div role="alert" className="p-3 bg-amber-50 text-amber-900">
                Navigation editing is unavailable: {navigationLoadError}. Application settings remain available.
            </div>}
            {navigationConflict && <div role="alert" className="p-3 bg-amber-50 text-amber-900">
                Navigation changed elsewhere. Your draft is still here. Loading the latest navigation will replace it.
                <button disabled={saving} className="ml-3 underline disabled:opacity-50" onClick={reloadLatestNavigation}>Load latest navigation</button>
            </div>}
            {refreshFailed && <div role="alert" className="p-3 bg-amber-50 text-amber-900">
                Navigation was saved, but the menu could not be refreshed.
                <button className="ml-3 underline" onClick={() => refreshNavigation(routeGeneration.current)}>Retry menu refresh</button>
            </div>}
            {!!pendingSave.current && !saving && <div role="alert" className="p-3 bg-amber-50">The save result is uncertain. Retry navigation save to reconcile it before editing.</div>}
            {/* Every child draft belongs to this host session, even when a deep
                link selects the same resource again after authentication. */}
            <div key={sessionRevision} className="flex-1 flex overflow-hidden">
                {/* Left Sidebar */}
                <div className="flex flex-col">

                <StudioSidebar
                    app={app}
                    disabled={saving || !!pendingSave.current}
                    navigationDisabled={externalSalesforce || isNewApp || !navigationBaseline}
                    onAddStandard={handleAddStandard}
                    openAddModal={shouldOpenAddModal}
                    selectedObjectApiName={editor.mode === 'object' ? editor.objectApiName : (editor.mode === 'dashboard' ? editor.dashboardId : undefined)}
                    selectedNavigationItemId={editor.itemId}
                    onSelectNavItem={handleNavItemSelect}
                    availableObjects={availableObjects}
                    availableDashboards={availableDashboards}
                    onAddObject={handleCreateNewObject}
                    onAddDashboard={handleCreateNewDashboard}
                    onAddExistingObject={handleAddExistingObject}
                    onAddExistingDashboard={handleAddExistingDashboard}
                    onAddWebLink={handleAddWebLink}
                    onReorderNavItems={handleReorderNavItems}
                    onRemoveNavItem={handleRemoveNavItem}
                    onOpenSettings={() => setEditor({ mode: 'settings' })}
                    onOpenPermissions={() => setEditor({ mode: 'permissions' })}
                />
                </div>

                {/* Main Content Area */}
                <main className="flex-1 p-6 overflow-y-auto relative">

                    {/* Editor Panels */}
                    {editor.mode === 'object' && editor.objectApiName && (
                        <div className="h-full">
                            <StudioObjectEditor
                                key={editor.objectApiName} // Force remount on change
                                objectApiName={editor.objectApiName}
                                onObjectUpdated={() => { if (ownsSession()) void loadMetadata(); }}
                            />
                        </div>
                    )}

                    {editor.mode === 'dashboard' && editor.dashboardId && (
                        <div className="h-full">
                            <StudioDashboardEditor
                                key={editor.dashboardId}
                                dashboardId={editor.dashboardId}
                                dashboardWidgets={dashboardWidgets}
                                renderWidgetInspector={renderDashboardWidgetInspector}
                                onDashboardUpdated={() => { if (ownsSession()) void loadMetadata(); }}
                            />
                        </div>
                    )}

                    {editor.mode === 'settings' && (
                        <AppSettingsEditor
                            app={app}
                            isNewApp={isNewApp}
                            readOnly
                            readOnlyReason={externalSalesforce ? "External Salesforce application editing is not supported. Manage applications in Salesforce Setup." : undefined}
                            onChange={updateApp}
                        />
                    )}

                    {editor.mode === 'permissions' && (
                        <div className="h-full">
                            <StudioPermissions appObjects={availableObjects} />
                        </div>
                    )}

                    {editor.mode === 'navigation' && (() => {
                        const item = app.navigationItems?.find(value => value.id === editor.itemId);
                        if (!item) return null;
                        const pageAvailable = item.type !== 'page' || !!getStandardPageTab(app.frontendAppId ?? currentFrontendAppId, item.objectApiName);
                        const edit = (updates: Partial<NavigationItem>) => updateApp({ navigationItems: app.navigationItems?.map(value => value.id === item.id ? { ...value, ...updates } : value) });
                        return <fieldset disabled={saving || !!pendingSave.current || !navigationBaseline} className="max-w-xl space-y-4">
                            <legend className="text-lg font-semibold">Navigation item</legend>
                            <label className="block">Label<input className="block border rounded p-2 w-full" value={item.label} onChange={event => edit({ label: event.target.value })} /></label>
                            <label className="block">Icon<input className="block border rounded p-2 w-full" value={item.icon} onChange={event => edit({ icon: event.target.value })} /></label>
                            {item.type === 'web' ? <label className="block">URL<input className="block border rounded p-2 w-full" value={item.pageUrl ?? ''} onChange={event => edit({ pageUrl: event.target.value })} /></label>
                                : <label className="block">Page<select className="block border rounded p-2 w-full" value={item.objectApiName} onChange={event => {
                                    const page = getStandardPageTab(app.frontendAppId ?? currentFrontendAppId, event.target.value);
                                    if (page) edit({ objectApiName: event.target.value });
                                }}>
                                    {!pageAvailable && <option value={item.objectApiName}>{item.objectApiName} (unavailable)</option>}
                                    {standardPageTabKeys(app.frontendAppId ?? currentFrontendAppId).map(key => <option key={key} value={key}>{getStandardPageTab(app.frontendAppId ?? currentFrontendAppId, key)?.label ?? key}</option>)}
                                </select></label>}
                            {!pageAvailable && <p role="status" className="text-amber-700">This page is unavailable in the current app. Its saved reference is preserved. Choose another page or remove this item to restore a working menu entry.</p>}
                        </fieldset>;
                    })()}
                    {/* Empty State */}
                    {!editor.mode && (
                        <div className="h-full flex flex-col items-center justify-center text-slate-400">
                            <Box size={64} className="mb-4 text-slate-300" />
                            <h3 className="text-lg font-medium text-slate-600">Welcome to App Studio</h3>
                            <p>Select an item from the sidebar to edit</p>
                        </div>
                    )}
                </main>
            </div>
        </div>
    );
};
