<script lang="ts">
import { ae_loc } from '$lib/stores/ae_stores';
import { events_sess } from '$lib/stores/ae_events_stores';
import { launcher_loc } from '$lib/stores/ae_events_stores__launcher.svelte';
import Launcher_Cfg_Section from './launcher_cfg_section.svelte';
import { HeartPulse, RefreshCw } from '@lucide/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={HeartPulse}
    bind:state={launcher_loc.current.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="bg-surface-500/5 border-surface-500/10 col-span-full flex flex-col gap-3 rounded-lg border p-3">
        <!-- CPU Usage (Mock Logic if load not available yet) -->
        <div class="flex flex-col gap-1">
            <div
                class="flex justify-between text-[9px] font-bold uppercase opacity-60">
                <span
                    >CPU Architecture: {$ae_loc.native_device?.meta_json
                        ?.arch || '...'}</span>
                <span>Load: {cpu_load_pct}%</span>
            </div>
            <div
                class="bg-surface-500/20 h-1.5 w-full overflow-hidden rounded-full">
                <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] font-bold uppercase opacity-60">
                <span>Memory (RAM)</span>
                <span>{ram_usage_pct}% Used</span>
            </div>
            <div
                class="bg-surface-500/20 h-1.5 w-full overflow-hidden rounded-full">
                <div
                    class="h-full transition-all duration-1000 {get_usage_color(
                        ram_usage_pct
                    )}"
                    style="width: {ram_usage_pct}%">
                </div>
            </div>
            <div class="text-right text-[8px] italic opacity-40">
                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 w-full grid-cols-2 gap-x-2 gap-y-2 p-1 text-[10px]">
        <div class="flex flex-col">
            <span class="text-[8px] font-bold uppercase opacity-50"
                >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="text-[8px] font-bold uppercase opacity-50"
                >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="bg-primary-500/10 border-primary-500/20 col-span-full mt-1 animate-pulse rounded border p-2">
                <div class="flex items-center gap-2">
                    <RefreshCw
                        size="1em"
                        class="text-primary-500 animate-spin" />
                    <div class="flex flex-col truncate">
                        <span
                            class="text-primary-500 text-[8px] font-bold uppercase"
                            >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="border-surface-500/10 col-span-full mt-1 flex flex-col gap-1 border-t px-1 pt-2 text-[9px] opacity-60">
            <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="truncate font-mono"
                    >{$ae_loc.native_device?.info_ip_list || '...'}</span>
            </div>
            <div class="mt-2 opacity-40">
                <span class="text-[8px] font-bold uppercase"
                    >Raw Device JSON</span>
                <pre
                    class="mt-1 max-h-32 overflow-y-auto rounded bg-black/20 p-1 text-[7px]">
                    {JSON.stringify($ae_loc.native_device ?? {}, null, 2)}
                </pre>
            </div>
        </div>
    {/if}
</Launcher_Cfg_Section>
