/**
 * @docs ARCHITECTURE:Interface
 * @docs OPERATIONS_MANUAL:Navigation
 * 
 * ### AI Assist Note
 * **Root Layout**: Orchestrates the primary dashboard container, sidebar, and tabbed navigation interface. 
 * Manages the high-fidelity backdrop blur effects and Z-index layering for global components (Terminal, Detached Windows). 
 * Integrates `tab_store` for multi-tab state persistence and sidebar_store for layout responsiveness.
 * 
 * ### 🔍 Debugging & Observability
 * - **Failure Path**: Viewport overflow (if sidebar is pinned on mobile), tab sync mismatch (BroadcastChannel data collision), or layout layout flickering during page transitions.
 * - **Telemetry Link**: Watch for `tab_store` mutations or search `[DashboardLayout]` in UI traces.
 */

import React, { useState, Suspense, lazy } from 'react';
import clsx from 'clsx';
import { Sidebar } from '../components/layout/Sidebar';
import { Portal_Window } from '../components/ui';
import { Tab_Bar } from '../components/layout/Tab_Bar';
import { Ticker_Header } from '../components/layout/Ticker_Header';
import { use_tab_store } from '../stores/tab_store';
import { get_route_by_path } from '../constants/routes';
import Error_Boundary from '../components/Error_Boundary';
import { ExternalLink } from 'lucide-react';
import { i18n } from '../i18n';
import { use_sovereign_store } from '../stores/sovereign_store';
import { useLayoutNavigation } from '../hooks/layout/useLayoutNavigation';
import { useLayoutServices } from '../hooks/layout/useLayoutServices';

const SovereignChat = lazy(() => import('../components/SovereignChat').then(module => ({ default: module.SovereignChat })));
const Lineage_Stream = lazy(() => import('../components/Lineage_Stream').then(module => ({ default: module.Lineage_Stream })));
const Neural_Waterfall = lazy(() => import('../components/Neural_Waterfall').then(module => ({ default: module.Neural_Waterfall })));
const Command_Palette = lazy(() => import('../components/Command_Palette').then(module => ({ default: module.Command_Palette })));
const System_Log = lazy(() => import('../components/dashboard/System_Log').then(module => ({ default: module.System_Log })));
const Observability_Sidebar = lazy(() => import('../components/layout/Observability_Sidebar').then(module => ({ default: module.Observability_Sidebar })));
const Toast_Center = lazy(() => import('../components/ui/Toast_Center').then(module => ({ default: module.Toast_Center })));

/**
 * Dashboard_Layout
 * The primary architectural shell for the Tadpole OS frontend.
 * Orchestrates global services, navigation, and multi-window workspace synchronization.
 */
export default function Dashboard_Layout() {
    const { 
        tabs, 
        active_tab_id, 
        is_system_log_detached, 
        toggle_system_log_detachment, 
        is_trace_stream_detached, 
        toggle_trace_stream_detachment, 
        is_lineage_stream_detached, 
        toggle_lineage_stream_detachment 
    } = use_tab_store();
    use_sovereign_store();
    const [is_command_palette_open, set_is_command_palette_open] = useState(false);

    // ── Extracted Infrastructure Hooks ───────────────────
    useLayoutNavigation(set_is_command_palette_open);
    useLayoutServices();

    const nav_item_class = ({ isActive: is_active }: { isActive: boolean }) => clsx(
        "flex items-center gap-3 p-2 rounded-md font-medium cursor-pointer transition-all duration-200 text-sm justify-center lg:justify-start",
        is_active
            ? "bg-zinc-800 text-zinc-100 shadow-inner border border-zinc-700/50"
            : "text-zinc-500 hover:bg-zinc-800/50 hover:text-zinc-300"
    );

    const shell_fallback = (
        <div className="p-3 text-zinc-600 font-mono text-[10px] uppercase tracking-widest animate-pulse">
            {i18n.t('common.loading')}
        </div>
    );


    return (
        <div className="flex h-screen bg-[color:var(--color-background)] text-zinc-100 overflow-hidden font-sans antialiased selection:bg-zinc-700/30">
            <a href="#main-content" className="sr-only focus:not-sr-only focus:absolute focus:top-4 focus:left-4 z-[9999] bg-green-600 text-white px-4 py-2 rounded shadow-lg">
                {i18n.t('layout.skip_to_content') || 'Skip to content'}
            </a>
            <Sidebar nav_item_class={nav_item_class} />

            <main id="main-content" className="flex-1 flex flex-col bg-[color:var(--color-background)] relative overflow-hidden">
                <Ticker_Header />

                <Tab_Bar />

                <div className="flex-1 flex overflow-hidden">
                    <div className="flex-1 relative">
                        {(tabs || []).map((tab) => {
                            const route = get_route_by_path(tab.path);
                            const Component = route.component;
                            const is_detached = tab.is_detached;
                            const is_active = tab.id === active_tab_id;
                            if (!is_active && !is_detached) {
                                return null;
                            }

                            // Content shared between portal and inline
                            const content = (
                                <Error_Boundary name={`Sector: ${tab.title}`}>
                                    <Suspense fallback={<div className="p-8 text-zinc-500 font-mono text-xs animate-pulse">{i18n.t('layout.initializing_sector')}</div>}>
                                        <Component />
                                    </Suspense>
                                </Error_Boundary>
                            );

                            if (is_detached) {
                                return (
                                    <React.Fragment key={tab.id}>
                                        {/* Render Portal Window (Native Browser Window) */}
                                        <Portal_Window 
                                            id={tab.id} 
                                            title={tab.title} 
                                            url={`/detached-view?type=tab&path=${encodeURIComponent(tab.path)}&id=${tab.id}`}
                                            on_close={() => use_tab_store.getState().toggle_tab_detachment(tab.id)}
                                            width={1280}
                                            height={850}
                                        >
                                            <div className="h-screen w-full bg-[color:var(--color-background)] p-4 sm:p-6 flex flex-col overflow-hidden">
                                                <div className="flex-1 relative overflow-auto custom-scrollbar w-full h-full">
                                                    {content}
                                                </div>
                                            </div>
                                        </Portal_Window>

                                        {/* Placeholder in Main Layout */}
                                        <div
                                            className={clsx(
                                                "absolute inset-0 flex items-center justify-center bg-[color:color-mix(in_srgb,var(--color-background)_80%,transparent)] backdrop-blur-sm z-20",
                                                is_active ? "visible opacity-100" : "invisible opacity-0"
                                            )}
                                        >
                                            <div className="text-center space-y-4">
                                                <div className="relative inline-block">
                                                    <ExternalLink size={48} className="text-zinc-800 animate-pulse" />
                                                    <div className="absolute inset-0 bg-green-500/10 blur-xl rounded-full" />
                                                </div>
                                                <div className="space-y-1">
                                                    <h3 className="text-lg font-bold tracking-tight text-zinc-200">{i18n.t('layout.sector_detached')}</h3>
                                                    <p className="text-sm text-zinc-500 font-mono">{i18n.t('layout.link_established')} :: {i18n.t('layout.monitor_label')}_{tab.id.toUpperCase()}</p>
                                                </div>
                                                <button 
                                                    onClick={() => use_tab_store.getState().toggle_tab_detachment(tab.id)}
                                                    className="px-4 py-2 bg-zinc-100 text-zinc-950 text-xs font-bold uppercase tracking-widest rounded-lg hover:bg-white transition-all shadow-lg active:scale-95"
                                                >
                                                    {i18n.t('layout.recall_sector')}
                                                </button>
                                            </div>
                                        </div>
                                    </React.Fragment>
                                );
                            }

                            return (
                                <div
                                    key={tab.id}
                                    className={clsx(
                                        "absolute inset-0 overflow-y-auto overflow-x-hidden p-0 custom-scrollbar",
                                        is_active ? "visible opacity-100 z-10" : "invisible opacity-0 z-0 pointer-events-none"
                                    )}
                                >
                                    {content}
                                </div>
                            );
                        })}
                    </div>

                    <Suspense fallback={shell_fallback}>
                        <Observability_Sidebar />
                    </Suspense>

                    <Suspense fallback={null}>
                        <SovereignChat />
                        <Command_Palette
                            is_open={is_command_palette_open}
                            on_close={() => set_is_command_palette_open(false)}
                        />
                    </Suspense>

                    {/* Global Detached System Log */}
                    {is_system_log_detached && (
                        <Portal_Window
                            id="system-log-detached"
                            title={i18n.t('system_log.title')}
                            url="/detached-view?type=system-log"
                            on_close={toggle_system_log_detachment}
                        >
                            <div className="h-screen bg-[color:var(--color-background)] p-6 flex flex-col">
                                <Suspense fallback={shell_fallback}>
                                    <System_Log is_detached_view />
                                </Suspense>
                            </div>
                        </Portal_Window>
                    )}

                    {/* Global Detached Trace Stream */}
                    {is_trace_stream_detached && (
                        <Portal_Window
                            id="trace-stream-detached"
                            title={i18n.t('trace_stream.title')}
                            url="/detached-view?type=trace-stream"
                            on_close={toggle_trace_stream_detachment}
                        >
                            <div className="h-screen bg-[color:var(--color-background)] p-0 flex flex-col">
                                <Suspense fallback={shell_fallback}>
                                    <Neural_Waterfall is_detached_view />
                                </Suspense>
                            </div>
                        </Portal_Window>
                    )}

                    {/* Global Detached Lineage Stream */}
                    {is_lineage_stream_detached && (
                        <Portal_Window
                            id="lineage-stream-detached"
                            title={i18n.t('trace.stream_title')}
                            url="/detached-view?type=lineage-stream"
                            on_close={toggle_lineage_stream_detachment}
                        >
                            <div className="h-screen bg-[color:var(--color-background)] p-0 flex flex-col">
                                <Suspense fallback={shell_fallback}>
                                    <Lineage_Stream is_detached_view />
                                </Suspense>
                            </div>
                        </Portal_Window>
                    )}
                </div>

                <Suspense fallback={null}>
                    <Toast_Center />
                </Suspense>
            </main>
        </div>
    )
}

// Metadata: [Dashboard_Layout]
