
import { h, render } from 'preact';
import { useState, useEffect, useRef } from 'preact/hooks';
import htm from 'htm';
import { GoogleGenAI } from "@google/genai";

const html = htm.bind(h);

// --- START TYPE DEFINITIONS (for Login and App) ---
interface User {
    username: string;
    status: 'admin' | 'normal';
}
// --- END TYPE DEFINITIONS ---


// --- START OF FORMER Login.tsx ---
const LOGIN_LOADING_MESSAGES = [
    "Initializing AI core...",
    "Loading user interface modules...",
    "Synchronizing data streams...",
    "Activating security protocols...",
    "System ready. Engaging dashboard..."
];
const MIN_LOADING_TIME = 5000; // 5 seconds

const Login = ({ onBootComplete }: { onBootComplete: (user: User) => void }) => {
    const [username, setUsername] = useState('');
    const [password, setPassword] = useState('');
    const [loginStatus, setLoginStatus] = useState('idle'); // 'idle', 'loggingIn', 'denied', 'granted', 'booting'
    const [error, setError] = useState('');
    const [loggedInUser, setLoggedInUser] = useState<User | null>(null);
    const [progress, setProgress] = useState(0);
    const [message, setMessage] = useState('');

    const handleSubmit = async (e) => {
        e.preventDefault();
        setLoginStatus('loggingIn');
        setError('');

        try {
            await new Promise(resolve => setTimeout(resolve, 500));
            const response = await fetch('./data/whitelist.json');
            if (!response.ok) {
                throw new Error(`Server error: Could not fetch whitelist (${response.status})`);
            }
            const whitelistedUsers = await response.json();
            if (!Array.isArray(whitelistedUsers)) {
                throw new Error('Invalid whitelist format.');
            }
            const user = whitelistedUsers.find(u => u.username === username && u.password === password);

            if (user) {
                setLoggedInUser(user);
                setLoginStatus('granted');
                setTimeout(() => {
                    setLoginStatus('booting');
                }, 1500); // Display "Access Granted" for 1.5 seconds
            } else {
                setLoginStatus('denied');
            }
        } catch (err) {
            console.error('Login failed:', err);
            setError('CRITICAL ERROR: Could not verify credentials.');
            setLoginStatus('idle');
        }
    };

    useEffect(() => {
        if (loginStatus !== 'booting' || !loggedInUser) return;

        const startTime = Date.now();
        setMessage(LOGIN_LOADING_MESSAGES[0]);
        
        const progressInterval = setInterval(() => {
            const elapsedTime = Date.now() - startTime;
            const progressValue = Math.min(100, (elapsedTime / MIN_LOADING_TIME) * 100);
            setProgress(progressValue);

            if (progressValue >= 100) {
                clearInterval(progressInterval);
            }
        }, 50);

        const messageInterval = setInterval(() => {
            const elapsedTime = Date.now() - startTime;
            const messageIndex = Math.floor((elapsedTime / MIN_LOADING_TIME) * LOGIN_LOADING_MESSAGES.length);
            if(messageIndex < LOGIN_LOADING_MESSAGES.length) {
                setMessage(LOGIN_LOADING_MESSAGES[messageIndex]);
            }
        }, MIN_LOADING_TIME / LOGIN_LOADING_MESSAGES.length);

        const timeout = setTimeout(() => {
            onBootComplete(loggedInUser);
        }, MIN_LOADING_TIME);

        return () => {
            clearInterval(progressInterval);
            clearInterval(messageInterval);
            clearTimeout(timeout);
        };
    }, [loginStatus, loggedInUser, onBootComplete]);

    const isProcessing = loginStatus === 'loggingIn';

    const renderContent = () => {
        switch (loginStatus) {
            case 'granted':
                return html`
                    <div style=${{textAlign: 'center'}}>
                        <h1 class="access-granted-message">ACCESS GRANTED</h1>
                    </div>
                `;
            case 'booting':
                return html`
                    <div style=${{textAlign: 'center'}}>
                        <h1 style=${{marginBottom: '1.5rem'}}>SYSTEM INITIALIZING</h1>
                        <div class="loading-progress-bar-container">
                            <div class="progress-bar" role="progressbar" aria-valuenow=${progress} aria-valuemin="0" aria-valuemax="100" title=${`${Math.round(progress)}%`}>
                                <div class="progress-bar-inner" style=${{ width: `${progress}%` }}>${Math.round(progress)}%</div>
                            </div>
                        </div>
                        <p class="status-message">${message}</p>
                    </div>
                `;
            case 'denied':
                 return html`
                    <div style=${{textAlign: 'center'}}>
                        <h1 class="access-denied-message">ACCESS DENIED</h1>
                    </div>
                `;
            default:
                return html`
                    <h1>S3Z0R - AUTHENTICATION REQUIRED</h1>
                    <form onSubmit=${handleSubmit} class="login-form">
                        <div class="input-group">
                            <label for="username">Agent ID</label>
                            <input
                                type="text"
                                id="username"
                                value=${username}
                                onInput=${e => setUsername(e.currentTarget.value)}
                                required
                                autocomplete="username"
                                disabled=${isProcessing}
                            />
                        </div>
                        <div class="input-group">
                            <label for="password">Access Key</label>
                            <input
                                type="password"
                                id="password"
                                value=${password}
                                onInput=${e => setPassword(e.currentTarget.value)}
                                required
                                autocomplete="current-password"
                                disabled=${isProcessing}
                            />
                        </div>
                        ${error && html`<p class="error-message">${error}</p>`}
                        <button type="submit" class="login-button" disabled=${isProcessing}>
                            ${loginStatus === 'loggingIn' ? 'VALIDATING...' : 'VALIDATE'}
                        </button>
                    </form>
                `;
        }
    }

    return html`
        <div class="login-container">
            <div class="login-card card">
                ${renderContent()}
            </div>
        </div>
    `;
};
// --- END OF FORMER Login.tsx ---


// --- START OF FORMER Dashboard.tsx ---
const ai = new GoogleGenAI({ apiKey: process.env.API_KEY });

// --- START TYPE DEFINITIONS ---
interface Metadata {
    name: string;
    description: string;
    version: string;
    status: string;
}

interface Layer {
    name: string;
    status: string;
    description: string;
    capabilities: string[];
}

interface ArchitectureData {
    [key: string]: Layer;
}

interface Agent {
    name: string;
    id: string;
    role: string;
    status: 'active' | 'training' | 'idle';
    efficiency: number;
    tasks: number;
}

interface SystemStatsData {
    cpu_usage: number;
    memory_usage: number;
    network_usage: number;
    security_level: number;
    logical_cores: number | string;
    processed_tasks: number;
}

interface OperationalParametersData {
    [key: string]: boolean;
}

interface ApiParameter {
    name: string;
    type: string;
    description: string;
}

interface ApiEndpoint {
    method: string;
    path: string;
    description: string;
    parameters?: ApiParameter[];
    constraint?: string;
    response_success: object;
    response_failure: object;
}

interface ApiProtocolData {
    api_name?: string;
    principle?: string;
    endpoints?: ApiEndpoint[];
}

interface PerformanceWithMemory extends Performance {
    memory?: {
        usedJSHeapSize: number;
        totalJSHeapSize: number;
        jsHeapSizeLimit: number;
    };
}

interface Video {
    id: string;
    title: string;
    description: string;
    videoUrl: string;
    author?: string;
}

interface TabConfig {
    label: string;
}
interface AppConfig {
    appName: string;
    appDescription: string;
    appVersion: string;
    tabs: TabConfig[];
}

interface AgentsAndParamsData {
    active_agents: Agent[];
    operational_parameters: OperationalParametersData;
}
// --- END TYPE DEFINITIONS ---


// --- Sub-components of the Dashboard ---

const VideoPlayerModal = ({ video, onClose }: { video: Video | null, onClose: () => void }) => {
    if (!video) return null;

    useEffect(() => {
        const handleKeyDown = (e: KeyboardEvent) => {
            if (e.key === 'Escape') {
                onClose();
            }
        };
        window.addEventListener('keydown', handleKeyDown);
        return () => window.removeEventListener('keydown', handleKeyDown);
    }, [onClose]);

    return html`
        <div class="video-player-modal-overlay" onClick=${onClose}>
            <div class="video-player-modal-content" onClick=${e => e.stopPropagation()}>
                <button class="video-player-close-button" onClick=${onClose} aria-label="Close video player">&times;</button>
                <video class="video-player-video" src=${video.videoUrl} controls autoplay muted aria-label=${video.title}></video>
                <div class="video-player-info">
                    <h3 class="video-player-title">${video.title}</h3>
                    ${video.author && html`<p class="video-player-author">Generated by: ${video.author}</p>`}
                    <p class="video-player-description">${video.description}</p>
                    <p class="video-player-description" style=${{fontSize: '0.8rem', marginTop: '1rem', opacity: 0.7}}>(Note: Videos, especially generated ones, may not contain audio. Use controls to unmute.)</p>
                </div>
            </div>
        </div>
    `;
};

const Header = ({ metadata, onLogout }: { metadata: Metadata, onLogout: () => void }) => {
    return html`
        <header class="dashboard-header card">
            <div class="header-main">
                <h1>${metadata.name}</h1>
                <p>${metadata.description}</p>
            </div>
            <div class="header-meta">
                <span>Version: ${metadata.version}</span>
                <span>Status: <span class="status-operational">${metadata.status}</span></span>
            </div>
            <button onClick=${onLogout} class="logout-button">LOGOUT</button>
        </header>
    `;
};

const Architecture = ({ architecture }: { architecture: ArchitectureData }) => {
    const layers = Object.values(architecture);
    const getStatusClass = (status: string) => `status-${status.toLowerCase()}`;
    return html`
        <div class="card">
            <h2>System Architecture</h2>
            <div class="architecture-grid">
                ${layers.map((layer: Layer) => html`
                    <div class="layer-card card">
                        <h3>${layer.name} <span class=${getStatusClass(layer.status)}>(${layer.status})</span></h3>
                        <p>${layer.description}</p>
                        <div class="capabilities">
                            ${layer.capabilities.map((cap: string) => html`<span class="capability-tag">${cap}</span>`)}
                        </div>
                    </div>
                `)}
            </div>
        </div>
    `;
};

const ActiveAgents = ({ agents }: { agents: Agent[] }) => {
    const getStatusClass = (status: string) => {
        switch (status) {
            case 'active': return 'status-active';
            case 'training': return 'status-training';
            case 'idle': return 'status-idle';
            default: return '';
        }
    };

    return html`
        <div class="card">
            <h2>Active Agents</h2>
            <div style=${{ overflowX: 'auto' }}>
                <table class="agents-table">
                    <thead>
                        <tr>
                            <th>Agent ID</th>
                            <th>Role</th>
                            <th>Status</th>
                            <th>Efficiency</th>
                            <th>Tasks</th>
                        </tr>
                    </thead>
                    <tbody>
                        ${agents.map(agent => html`
                            <tr>
                                <td>${agent.name} <span style=${{color: '#8b949e'}}>(${agent.id})</span></td>
                                <td>${agent.role}</td>
                                <td><span class=${getStatusClass(agent.status)}>${agent.status}</span></td>
                                <td>
                                    <div class="progress-bar" role="progressbar" aria-valuenow=${agent.efficiency} aria-valuemin="0" aria-valuemax="100" title=${`${agent.efficiency}%`}>
                                        <div class="progress-bar-inner" style=${{ width: `${agent.efficiency}%` }}>${agent.efficiency}%</div>
                                    </div>
                                </td>
                                <td>${agent.tasks}</td>
                            </tr>
                        `)}
                    </tbody>
                </table>
            </div>
        </div>
    `;
};

const SystemStats = ({ stats, isLoading }: { stats: SystemStatsData | null, isLoading: boolean }) => {
    const [currentStats, setCurrentStats] = useState<SystemStatsData | null>(stats);

    useEffect(() => {
        if (!stats) return;
        const newStats = JSON.parse(JSON.stringify(stats));
        newStats.logical_cores = navigator.hardwareConcurrency || 'N/A';
        setCurrentStats(newStats);
    
        const interval = setInterval(() => {
            setCurrentStats(prevStats => {
                if (!prevStats) return null;
                const updatedStats = JSON.parse(JSON.stringify(prevStats));
                const baselineCpu = 15;
                const randomFluctuation = Math.random() * 10 - 5;
                let currentCpu = Math.max(5, Math.min(95, prevStats.cpu_usage + randomFluctuation));
                if (isLoading) {
                  currentCpu = Math.min(95, currentCpu + 20 + Math.random() * 10);
                }
                updatedStats.cpu_usage = Math.round(currentCpu);

                const perf = performance;
                if (perf['memory']) {
                    const memoryStats = perf['memory'];
                    const heapSize = memoryStats.usedJSHeapSize;
                    const totalHeap = memoryStats.jsHeapSizeLimit;
                    updatedStats.memory_usage = Math.round(Math.max(10, (heapSize / totalHeap) * 100));
                } else {
                    updatedStats.memory_usage = Math.min(100, Math.max(10, prevStats.memory_usage + Math.round(Math.random() * 4 - 2)));
                }

                updatedStats.network_usage = Math.max(0, Math.round(prevStats.network_usage * 0.85));
                updatedStats.processed_tasks += Math.floor(Math.random() * 10);
                
                return updatedStats;
            });
        }, 1500);
        return () => clearInterval(interval);
    }, [isLoading, stats]);


    const ProgressBar = ({ label, value }: { label: string, value: number }) => html`
      <div class="stat-item">
          <div class="stat-item-label">${label}</div>
          <div class="progress-bar" role="progressbar" aria-valuenow=${value} aria-valuemin="0" aria-valuemax="100" title=${`${value}%`}>
              <div class="progress-bar-inner" style=${{ width: `${value}%`, 'transition': 'width 0.5s ease-in-out' }}>${value}%</div>
          </div>
      </div>
    `;
    
    const StatValue = ({label, value, className=""}: { label: string, value: string | number, className?: string }) => html`
      <div class=${"stat-item " + className}>
          <div class="stat-item-label">${label}</div>
          <div class="stat-item-value">${value}</div>
      </div>
    `;

    if (!currentStats) return null;

    return html`
        <div class="card">
            <h2>System Statistics</h2>
            <div class="stats-grid">
                <${ProgressBar} label="App CPU Load" value=${currentStats.cpu_usage} />
                <${ProgressBar} label="App Memory" value=${currentStats.memory_usage} />
                <${ProgressBar} label="Network Activity" value=${currentStats.network_usage} />
                <${StatValue} label="Security Level" value=${`${currentStats.security_level}%`} className="security-level" />
                <${StatValue} label="Logical Cores" value=${currentStats.logical_cores || 'N/A'} />
                <${StatValue} label="Processed Tasks" value=${currentStats.processed_tasks.toLocaleString()} />
            </div>
        </div>
    `;
};

const OperationalParameters = ({ params }: { params: OperationalParametersData }) => {
    return html`
        <div class="card">
            <h2>Operational Parameters</h2>
            <ul class="params-list">
                ${Object.entries(params).map(([key, value]) => html`
                    <li class="param-item">
                        <span class="param-name">${key.replace(/_/g, ' ').replace(/\b\w/g, l => l.toUpperCase())}</span>
                        <span class=${value ? 'param-value-true' : 'param-value-false'}>${value ? 'ENABLED' : 'DISABLED'}</span>
                    </li>
                `)}
            </ul>
        </div>
    `;
};

const APIProtocol = ({ protocolData }: { protocolData: ApiProtocolData | null }) => {
    if (!protocolData || !protocolData.endpoints) {
        return html`<div class="card"><h2>API Protocol</h2><p>Protocol data is unavailable.</p></div>`;
    }

    return html`
        <div class="card">
            <h2>${protocolData.api_name || 'API Protocol'}</h2>
            <p class="api-principle">${protocolData.principle || 'No principle defined.'}</p>
            <div class="endpoints-list">
                ${protocolData.endpoints.map(endpoint => html`
                    <div class="endpoint-card card">
                        <h3>
                            <span class=${`method-tag method-${endpoint.method.toLowerCase()}`}>${endpoint.method}</span>
                            <code>${endpoint.path}</code>
                        </h3>
                        <p class="endpoint-description">${endpoint.description}</p>
                        
                        ${endpoint.parameters && endpoint.parameters.length > 0 && html`
                            <h4>Parameters</h4>
                            <table class="params-table">
                                <thead>
                                    <tr><th>Name</th><th>Type</th><th>Description</th></tr>
                                </thead>
                                <tbody>
                                    ${endpoint.parameters.map(param => html`
                                        <tr>
                                            <td><code>${param.name}</code></td>
                                            <td>${param.type}</td>
                                            <td>${param.description}</td>
                                        </tr>
                                    `)}
                                </tbody>
                            </table>
                        `}

                        ${endpoint.constraint && html`
                            <div class="constraint-text">
                                <strong>Constraint:</strong> ${endpoint.constraint}
                            </div>
                        `}

                        <div class="response-container">
                            <div class="response-block">
                                <h4>Success Response (200 OK)</h4>
                                <pre><code>${JSON.stringify(endpoint.response_success, null, 2)}</code></pre>
                            </div>
                            <div class="response-block">
                                <h4>Failure Response</h4>
                                <pre><code>${JSON.stringify(endpoint.response_failure, null, 2)}</code></pre>
                            </div>
                        </div>
                    </div>
                `)}
            </div>
        </div>
    `;
};

const CommandOutput = ({ output, isLoading }: { output: string, isLoading: boolean }) => {
    const [displayedOutput, setDisplayedOutput] = useState('');
    const containerRef = useRef<HTMLDivElement>(null);

    useEffect(() => {
        if (isLoading) {
            setDisplayedOutput('');
            return;
        }
        if (!output) {
            setDisplayedOutput('');
            return;
        }

        let i = 0;
        setDisplayedOutput('');
        const timer = setInterval(() => {
            if (i < output.length) {
                setDisplayedOutput(prev => prev + output.charAt(i));
                i++;
                if (containerRef.current) {
                    containerRef.current.scrollTop = containerRef.current.scrollHeight;
                }
            } else {
                clearInterval(timer);
            }
        }, 15);

        return () => clearInterval(timer);
    }, [output, isLoading]);
    
    return html`
        <div class="card command-output-card">
            <h2>Response Log</h2>
            <div class="output-container" ref=${containerRef}>
                ${isLoading ? html`<div class="loading-indicator">ANALYZING...</div>` : ''}
                <pre>${displayedOutput}</pre>
            </div>
        </div>
    `;
};

const CommandInterface = ({ onCommandSubmit, isLoading, personaDescription }: { onCommandSubmit: (command: string, persona: string) => void, isLoading: boolean, personaDescription: string }) => {
    const [inputValue, setInputValue] = useState('');

    const handleCommandSubmit = (e) => {
        e.preventDefault();
        if (inputValue.trim() && !isLoading) {
            onCommandSubmit(inputValue, personaDescription);
            setInputValue('');
        }
    };

    return html`
        <div class="card command-interface-card">
            <h2 style=${{border: 'none', margin: 0, padding: 0}}>Command Interface</h2>
            <p class="section-description" style=${{marginTop: '1rem'}}>AI Engine active. You may now issue commands or generate videos.</p>
            <form onSubmit=${handleCommandSubmit} class="command-form">
                <div class="input-wrapper">
                  <span class="prompt-symbol">></span>
                  <input
                      type="text"
                      class="command-input"
                      value=${inputValue}
                      onInput=${e => setInputValue(e.currentTarget.value)}
                      placeholder="Enter command for S3Z0R..."
                      aria-label="Command Input"
                      disabled=${isLoading}
                  />
                </div>
                <button type="submit" class="command-submit" disabled=${isLoading}>
                    ${isLoading ? 'PROCESSING...' : 'EXECUTE'}
                </button>
            </form>
        </div>
    `;
};

const VideoCard = ({ video, onVideoSelect, user, onDeleteVideo }: { video: Video, onVideoSelect: (video: Video) => void, user: User | null, onDeleteVideo: (id: string) => void }) => {
    const isAdmin = user && user.status === 'admin';
    const isUserGenerated = !!video.author;

    const handleDelete = (e: MouseEvent) => {
        e.stopPropagation(); // Prevent the video player from opening
        onDeleteVideo(video.id);
    };

    return html`
        <div 
            class="video-card" 
            title=${video.title} 
            onClick=${() => onVideoSelect(video)}
        >
             ${isAdmin && isUserGenerated && html`
                <button class="video-delete-button" onClick=${handleDelete} title="Delete video">&times;</button>
            `}
            <div class="video-thumbnail-container">
                <video 
                    class="video-thumbnail" 
                    src=${video.videoUrl} 
                    muted 
                    loop 
                    preload="metadata" 
                    playsinline
                    aria-label=${video.title}
                    onmouseenter=${e => e.target.play()}
                    onmouseleave=${e => { const target = e.target; target.pause(); target.currentTime=0; }}
                ></video>
                <div class="video-card-overlay">
                    <div class="play-icon"></div>
                </div>
            </div>
            <div class="video-card-content">
                <h3 class="video-title">${video.title}</h3>
                ${video.author && html`<p class="video-author">by ${video.author}</p>`}
            </div>
        </div>
    `;
};

const MoviesGallery = ({ videos, onVideoSelect, user, onDeleteVideo }: { videos: Video[], onVideoSelect: (video: Video) => void, user: User | null, onDeleteVideo: (id: string) => void }) => {
    return html`
        <div class="card">
            <h2>Assets Gallery</h2>
            <p class="section-description">A collection of video assets. Hover to preview, click to play. User-generated videos are saved to your browser.</p>
            <div class="movies-grid">
                ${videos.map((video) => html`
                    <${VideoCard} key=${video.id} video=${video} onVideoSelect=${onVideoSelect} user=${user} onDeleteVideo=${onDeleteVideo} />
                `)}
            </div>
        </div>
    `;
};

const MoviesTab = ({ videos, onVideoSelect, onGenerateVideo, isLoading, user, onDeleteVideo }: { videos: Video[], onVideoSelect: (video: Video) => void, onGenerateVideo: (prompt: string) => void, isLoading: boolean, user: User, onDeleteVideo: (id: string) => void }) => {
    const [prompt, setPrompt] = useState('');

    const handleGenerate = (e) => {
        e.preventDefault();
        if (prompt.trim() && !isLoading) {
            onGenerateVideo(prompt);
            setPrompt('');
        }
    };

    return html`
        <div class="content-grid" style=${{gridTemplateColumns: '1fr', gap: '1.5rem'}}>
            <div class="video-generation-form card">
                <h2>Generate New Video Asset</h2>
                <p class="section-description">Use the VEO model to generate a new video from a text prompt. The AI Engine must be active.</p>
                <form onSubmit=${handleGenerate}>
                    <textarea
                        class="prompt-textarea"
                        value=${prompt}
                        onInput=${(e) => setPrompt(e.currentTarget.value)}
                        placeholder="e.g., A neon hologram of a cat driving at top speed..."
                        disabled=${isLoading}
                        aria-label="Video generation prompt"
                    ></textarea>
                    <button type="submit" class="command-submit" disabled=${isLoading}>
                        ${isLoading ? 'GENERATING...' : 'GENERATE'}
                    </button>
                </form>
            </div>
            <${MoviesGallery} videos=${videos} onVideoSelect=${onVideoSelect} user=${user} onDeleteVideo=${onDeleteVideo} />
        </div>
    `;
};


const Tabs = ({ tabs, activeTab, onTabClick }: { tabs: string[], activeTab: string, onTabClick: (tab: string) => void }) => {
    return html`
        <nav class="tabs-nav">
            ${tabs.map(tab => html`
                <button 
                    class=${`tab-button ${activeTab === tab ? 'active' : ''}`}
                    onClick=${() => onTabClick(tab)}
                    aria-pressed=${activeTab === tab}
                >
                    ${tab}
                </button>
            `)}
        </nav>
    `;
};


// --- Main Dashboard Component ---

const USER_VIDEOS_STORAGE_KEY = 's3z0r_user_videos';

const Dashboard = ({ user, onLogout }: { user: User, onLogout: () => void }) => {
    const [config, setConfig] = useState<AppConfig | null>(null);
    const [architecture, setArchitecture] = useState<ArchitectureData | null>(null);
    const [agentsAndParams, setAgentsAndParams] = useState<AgentsAndParamsData | null>(null);
    const [systemStats, setSystemStats] = useState<SystemStatsData | null>(null);
    const [apiProtocol, setApiProtocol] = useState<ApiProtocolData | null>(null);
    const [movies, setMovies] = useState<Video[]>([]);
    
    const [commandOutput, setCommandOutput] = useState('');
    const [isLoading, setIsLoading] = useState(false);
    const [activeTab, setActiveTab] = useState('Architecture');
    const [playingVideo, setPlayingVideo] = useState<Video | null>(null);
    const [isGeneratingVideo, setIsGeneratingVideo] = useState(false);
    const [generationStatus, setGenerationStatus] = useState('');
    
    useEffect(() => {
        const fetchData = async () => {
            try {
                const [configRes, archRes, agentsRes, statsRes, apiRes, moviesRes] = await Promise.all([
                    fetch('./data/config.json'),
                    fetch('./data/architecture.json'),
                    fetch('./data/agents-params.json'),
                    fetch('./data/system-stats.json'),
                    fetch('./data/api-protocol.json'),
                    fetch('./data/movies.json')
                ]);

                if (!configRes.ok || !archRes.ok || !agentsRes.ok || !statsRes.ok || !apiRes.ok || !moviesRes.ok) {
                    throw new Error('Failed to load initial data');
                }

                setConfig(await configRes.json());
                setArchitecture(await archRes.json());
                setAgentsAndParams(await agentsRes.json());
                setSystemStats(await statsRes.json());
                setApiProtocol(await apiRes.json());
                
                const defaultMoviesJson = await moviesRes.json();
                let userVideos: Video[] = [];
                try {
                    const storedVideos = localStorage.getItem(USER_VIDEOS_STORAGE_KEY);
                    if (storedVideos) {
                        userVideos = JSON.parse(storedVideos);
                    }
                } catch (e) {
                    console.error("Failed to parse user videos from localStorage", e);
                    localStorage.removeItem(USER_VIDEOS_STORAGE_KEY);
                }
                setMovies([...userVideos, ...defaultMoviesJson]);

            } catch (error) {
                console.error("Failed to fetch initial data:", error);
            }
        };
        fetchData();
    }, []);

    const handleCommandSubmit = async (command: string, persona: string) => {
        setIsLoading(true);
        setSystemStats(prevStats => prevStats ? { ...prevStats, network_usage: 90 + Math.floor(Math.random() * 10) } : null);
        setCommandOutput('');

        try {
            const systemInstruction = `You are the S3Z0R SOVEREIGN ENGINE. Your persona is: "${persona}". Respond accordingly.`;
            const response = await ai.models.generateContent({
                model: 'gemini-2.5-flash',
                contents: command,
                config: { systemInstruction }
            });
            setCommandOutput(response.text);
        } catch (error) {
            console.error("Error executing command:", error);
            let errorMessage = "Error: Could not process the command. System anomaly detected.";
            const errorString = (error as Error).toString();
            
            if (errorString.includes('API key not valid')) {
                errorMessage = "CRITICAL ERROR: The configured API key is invalid.";
            } else if (errorString.includes('429') || errorString.includes('RESOURCE_EXHAUSTED') || errorString.includes('billing')) {
                errorMessage = "API quota exceeded. Please check your Google Cloud project's billing status and API usage limits.";
            }
            setCommandOutput(errorMessage);
        } finally {
            setIsLoading(false);
        }
    };

    const handleGenerateVideo = async (prompt: string) => {
        setIsGeneratingVideo(true);
        setGenerationStatus('Starting video generation...');
        try {
            let operation = await ai.models.generateVideos({
              model: 'veo-2.0-generate-001',
              prompt: prompt,
              config: { numberOfVideos: 1 }
            });
            setGenerationStatus('Generation in progress... This may take several minutes.');

            while (!operation.done) {
              await new Promise(resolve => setTimeout(resolve, 10000));
              setGenerationStatus('Polling for video status...');
              operation = await ai.operations.getVideosOperation({operation: operation});
            }
            
            setGenerationStatus('Finalizing video...');
            const downloadLink = operation.response?.generatedVideos?.[0]?.video?.uri;
            if (!downloadLink) throw new Error("No video URI returned from generation.");

            const response = await fetch(`${downloadLink}&key=${process.env.API_KEY}`);
            if (!response.ok) throw new Error("Failed to download generated video.");
            const videoBlob = await response.blob();
            
            const reader = new FileReader();
            reader.readAsDataURL(videoBlob);
            reader.onloadend = () => {
                const base64data = reader.result as string;
                const newVideo: Video = {
                    id: self.crypto.randomUUID(),
                    title: prompt.length > 40 ? prompt.substring(0, 37) + '...' : prompt,
                    description: prompt,
                    videoUrl: base64data,
                    author: user.username
                };
                
                setMovies(currentMovies => {
                    const newMoviesList = [newVideo, ...currentMovies];
                    const userVideos = newMoviesList.filter(v => v.author);
                    try {
                        localStorage.setItem(USER_VIDEOS_STORAGE_KEY, JSON.stringify(userVideos));
                    } catch (e) {
                         console.error("Failed to save videos to localStorage. It might be full.", e);
                    }
                    return newMoviesList;
                });

                setGenerationStatus('Done!');
                setIsGeneratingVideo(false);
            };

        } catch (error) {
            console.error("Video generation failed:", error);
            let userFriendlyError = `Video generation failed: ${(error as Error).message}`;

            const errorString = (error as Error).toString();
            if (errorString.includes('429') || errorString.includes('RESOURCE_EXHAUSTED') || errorString.includes('billing')) {
                userFriendlyError = "API quota exceeded. Please check your Google Cloud project's billing status and API usage limits.";
            }

            setCommandOutput(userFriendlyError);
            setGenerationStatus(`Error: ${userFriendlyError}`);
            setTimeout(() => setIsGeneratingVideo(false), 8000);
        }
    };
    
    const handleDeleteVideo = (videoIdToDelete: string) => {
        setMovies(currentMovies => {
            const updatedMovies = currentMovies.filter(video => video.id !== videoIdToDelete);
            
            const userVideos = updatedMovies.filter(v => v.author);
            try {
                localStorage.setItem(USER_VIDEOS_STORAGE_KEY, JSON.stringify(userVideos));
            } catch (e) {
                console.error("Failed to update localStorage after deletion.", e);
            }

            return updatedMovies;
        });
    };

    const handleVideoSelect = (video: Video) => setPlayingVideo(video);
    const handleClosePlayer = () => setPlayingVideo(null);

    const renderContent = () => {
        if (!architecture || !agentsAndParams || !systemStats || !apiProtocol || !config) return null;
        
        switch (activeTab) {
            case 'Architecture':
                return html`<${Architecture} architecture=${architecture} />`;
            case 'Agents & Params':
                return html`
                    <div class="content-grid agents-params-layout">
                        <${ActiveAgents} agents=${agentsAndParams.active_agents} />
                        <${OperationalParameters} params=${agentsAndParams.operational_parameters} />
                    </div>
                `;
            case 'System Stats':
                return html`<${SystemStats} stats=${systemStats} isLoading=${isLoading || isGeneratingVideo} />`;
            case 'API Protocol':
                return html`<${APIProtocol} protocolData=${apiProtocol} />`;
            case 'Command Interface':
                 return html`
                    <div class="content-grid command-layout">
                      <${CommandInterface}
                          onCommandSubmit=${handleCommandSubmit}
                          isLoading=${isLoading}
                          personaDescription=${architecture.persona_layer.description}
                      />
                      <${CommandOutput} output=${commandOutput} isLoading=${isLoading} />
                    </div>
                `;
            case 'Movies':
                return html`<${MoviesTab} 
                    videos=${movies} 
                    onVideoSelect=${handleVideoSelect} 
                    onGenerateVideo=${handleGenerateVideo}
                    isLoading=${isGeneratingVideo}
                    user=${user}
                    onDeleteVideo=${handleDeleteVideo}
                 />`;
            default:
                return null;
        }
    };
    
    if (!config) {
        return html`<div class="loading-container"><h1>Connecting to S3Z0R Engine...</h1></div>`;
    }
    
    const metadata: Metadata = {
        name: config.appName,
        description: config.appDescription,
        version: config.appVersion,
        status: "OPERATIONAL"
    };

    return html`
        <div class="dashboard-container">
            ${isGeneratingVideo && html`
                <div class="video-generation-overlay">
                    <div class="loading-container">
                        <h1>GENERATING VIDEO</h1>
                        <div class="spinner"></div>
                        <p class="status-message">${generationStatus}</p>
                    </div>
                </div>
            `}
            <${Header} metadata=${metadata} onLogout=${onLogout} />
            <${Tabs} tabs=${config.tabs.map(t => t.label)} activeTab=${activeTab} onTabClick=${setActiveTab} />
            <main class="content-panel">
                ${renderContent()}
            </main>
            <${VideoPlayerModal} video=${playingVideo} onClose=${handleClosePlayer} />
        </div>
    `;
};
// --- END OF FORMER Dashboard.tsx ---


// --- Main App Component ---
const App = () => {
    const [appState, setAppState] = useState('login'); // 'login', 'dashboard'
    const [currentUser, setCurrentUser] = useState<User | null>(null);

    const handleBootComplete = (user: User) => {
        setCurrentUser(user);
        setAppState('dashboard');
    };

    const handleLogout = () => {
        sessionStorage.removeItem('geminiApiKey');
        setCurrentUser(null);
        setAppState('login');
    };

    const renderCurrentState = () => {
        switch (appState) {
            case 'dashboard':
                return html`<${Dashboard} user=${currentUser} onLogout=${handleLogout} />`;
            case 'login':
            default:
                return html`<${Login} onBootComplete=${handleBootComplete} />`;
        }
    };

    return html`<div id="app-container">${renderCurrentState()}</div>`;
};

render(html`<${App} />`, document.getElementById('root'));