<script lang="ts">
    import { ae_loc } from '$lib/stores/ae_stores';
    import { events_loc, events_sess } from '$lib/stores/ae_events_stores';
    import Launcher_Cfg_Section from './launcher_cfg_section.svelte';

    interface Props {
        on_expand?: () => void;
    }
    let { on_expand }: Props = $props();

    // Derived Usage Percentage for Visuals
    let cpu_load_pct = $derived.by(() => {
        const meta = $ae_loc.native_device?.meta_json;
        // loadavg is [1m, 5m, 15m] - use 1m load
        if (!meta?.loadavg || !Array.isArray(meta.loadavg)) return 15;

        // Load average is usually 0.0 to N (cores). Normalize to 0-100 based on cores if available.
        const load = meta.loadavg[0];
        const cores = (meta.cpus || []).length || 1;
        const pct = Math.round((load / cores) * 100);
        return Math.min(Math.max(pct, 5), 100); // Clamp 5-100
    });

    let ram_usage_pct = $derived.by(() => {
        const meta = $ae_loc.native_device?.meta_json;
        if (!meta?.total_mem || !meta?.free_mem) return 0;

        // Parse "16384MB" strings
        const total = parseInt(meta.total_mem);
        const free = parseInt(meta.free_mem);
        if (isNaN(total) || isNaN(free)) return 0;

        return Math.round(((total - free) / total) * 100);
    });

    // Helper for usage color
    function get_usage_color(pct: number) {
        if (pct > 90) return 'bg-error-500';
        if (pct > 70) return 'bg-warning-500';
        return 'bg-success-500';
    }
</script>

<Launcher_Cfg_Section
    title="System & Sync Health"
    icon="fa-heartbeat"
    bind:state={$events_loc.launcher.section_state__health}
    {on_expand}
    description="Heartbeat: {$events_sess.launcher.heartbeat_info
        .last_timestamp || 'Pending'}"
>
    <!-- Content omitted for brevity in instruction, but preserved in file -->
    <!-- Telemetry Dashboard -->
    <div
        class="col-span-full flex flex-col gap-3 bg-surface-500/5 p-3 rounded-lg border border-surface-500/10"
    >
        <!-- CPU Usage (Mock Logic if load not available yet) -->
        <div class="flex flex-col gap-1">
            <div
                class="flex justify-between text-[9px] uppercase font-bold opacity-60"
            >
                <span
                    >CPU Architecture: {$ae_loc.native_device?.meta_json
                        ?.arch || '...'}</span
                >
                <span>Load: {cpu_load_pct}%</span>
            </div>
            <div
                class="w-full h-1.5 bg-surface-500/20 rounded-full overflow-hidden"
            >
                <div
                    class="h-full transition-all duration-1000 {get_usage_color(cpu_load_pct)}"
                    style="width: {cpu_load_pct}%"
                ></div>
            </div>
        </div>

        <!-- RAM Usage -->
        <div class="flex flex-col gap-1">
            <div
                class="flex justify-between text-[9px] uppercase font-bold opacity-60"
            >
                <span>Memory (RAM)</span>
                <span>{ram_usage_pct}% Used</span>
            </div>
            <div
                class="w-full h-1.5 bg-surface-500/20 rounded-full overflow-hidden"
            >
                <div
                    class="h-full transition-all duration-1000 {get_usage_color(
                        ram_usage_pct
                    )}"
                    style="width: {ram_usage_pct}%"
                ></div>
            </div>
            <div class="text-[8px] opacity-40 text-right italic">
                Free: {$ae_loc.native_device?.meta_json?.free_mem || '...'} / {$ae_loc
                    .native_device?.meta_json?.total_mem || '...'}
            </div>
        </div>
    </div>

    <!-- Heartbeat & Sync Info -->
    <div class="grid grid-cols-2 gap-x-2 gap-y-2 w-full text-[10px] p-1">
        <div class="flex flex-col">
            <span class="opacity-50 text-[8px] uppercase font-bold"
                >Last Heartbeat</span
            >
            <span
                class="font-mono {$events_sess.launcher.heartbeat_info
                    .status === 'success'
                    ? 'text-success-500'
                    : 'text-error-500'}"
            >
                {$events_sess.launcher.heartbeat_info.last_timestamp ||
                    'Pending...'}
            </span>
        </div>

        <div class="flex flex-col text-right">
            <span class="opacity-50 text-[8px] uppercase font-bold"
                >Local File Cache</span
            >
            <span class="font-mono">
                {$events_sess.launcher.sync_stats.cached} / {$events_sess
                    .launcher.sync_stats.total}
            </span>
        </div>

        {#if $events_sess.launcher.sync_stats.currently_syncing}
            <div
                class="col-span-full bg-primary-500/10 p-2 rounded border border-primary-500/20 animate-pulse mt-1"
            >
                <div class="flex items-center gap-2">
                    <span class="fas fa-sync fa-spin text-primary-500"></span>
                    <div class="flex flex-col truncate">
                        <span
                            class="text-[8px] uppercase font-bold text-primary-500"
                            >Syncing File...</span
                        >
                        <span class="truncate italic opacity-80"
                            >{$events_sess.launcher.sync_stats
                                .currently_syncing}</span
                        >
                    </div>
                </div>
            </div>
        {/if}
    </div>

    <!-- Device Metadata (Edit Mode Only) -->
    {#if $ae_loc.edit_mode}
        <div
            class="col-span-full mt-1 pt-2 border-t border-surface-500/10 flex flex-col gap-1 text-[9px] opacity-60 px-1"
        >
            <div class="flex justify-between">
                <span>Hostname:</span>
                <span class="font-mono"
                    >{$ae_loc.native_device.info_hostname || '...'}</span
                >
            </div>
            <div class="flex justify-between gap-4">
                <span>IP Addresses:</span>
                <span class="font-mono truncate"
                    >{$ae_loc.native_device.info_ip_list || '...'}</span
                >
            </div>
            <div class="mt-2 opacity-40">
                <span class="text-[8px] uppercase font-bold"
                    >Raw Device JSON</span
                >
                <pre
                    class="text-[7px] max-h-32 overflow-y-auto bg-black/20 p-1 rounded mt-1">
                    {JSON.stringify($ae_loc.native_device, null, 2)}
                </pre>
            </div>
        </div>
    {/if}
</Launcher_Cfg_Section>
