<script lang="ts">
    import { ae_loc, ae_api, ae_sess } from '$lib/stores/ae_stores';
    import { events_loc, events_sess } from '$lib/stores/ae_events_stores';
    import * as native from '$lib/electron/electron_relay';
    import Launcher_Cfg_Section from './launcher_cfg_section.svelte';

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

    let test_cmd_result = $state('');
    let remote_app: 'powerpoint' | 'keynote' = $state('powerpoint');
    let remote_status = $state('');
    let system_status = $state('');

    async function handle_remote_control(
        action: 'next' | 'prev' | 'start' | 'stop'
    ) {
        remote_status = `Sending ${action}...`;
        const res = await native.control_presentation({
            app: remote_app,
            action
        });
        if (res.success) {
            remote_status = `Success: ${action}`;
        } else {
            remote_status = `Error: ${res.error}`;
        }
        setTimeout(() => (remote_status = ''), 3000);
    }

    async function handle_system_action(promise: Promise<any>, label: string) {
        system_status = `Executing ${label}...`;
        const res = await promise;
        if (res.success) {
            system_status = `Success: ${label}`;
        } else {
            system_status = `Error: ${res.error || 'Unknown error'}`;
        }
        setTimeout(() => (system_status = ''), 3000);
    }

    // Modal state for dangerous actions
    let show_power_confirm = $state<{ action: string; label: string } | null>(
        null
    );
</script>

<Launcher_Cfg_Section
    title="Native OS Management"
    icon="fa-laptop-code"
    bind:state={$events_loc.launcher.section_state__native_os}
    {on_expand}
    description="OS: {$ae_loc.native_device?.meta_json?.platform ||
        '...'} | Kiosk & Apps"
>
    <!-- Content omitted for brevity, preserved in file -->
    {#if system_status}
        <div
            class="col-span-full text-[10px] text-center italic bg-surface-500/10 py-1 rounded animate-pulse text-primary-500 border border-primary-500/20"
        >
            {system_status}
        </div>
    {/if}

    <!-- 1. Window & Folders (Common) -->
    <div class="flex flex-col gap-2">
        <label class="text-[9px] font-bold uppercase opacity-50 ml-1"
            >Folders & View</label
        >
        <div class="grid grid-cols-2 gap-1">
            <button
                type="button"
                onclick={() =>
                    native.open_folder($ae_loc.local_file_cache_path)}
                class="btn btn-xs preset-tonal-primary hover:preset-filled-primary-500 justify-start"
            >
                <span class="fas fa-folder-open mr-2 w-3"></span> Cache
            </button>
            <button
                type="button"
                onclick={() => native.open_folder($ae_loc.host_file_temp_path)}
                class="btn btn-xs preset-tonal-primary hover:preset-filled-primary-500 justify-start"
            >
                <span class="fas fa-folder-open mr-2 w-3"></span> Temp
            </button>
            <button
                type="button"
                onclick={() => native.window_control({ action: 'maximize' })}
                class="btn btn-xs preset-tonal-surface hover:preset-filled-primary-500"
            >
                <span class="fas fa-expand mr-1"></span> Maximize
            </button>
            <button
                type="button"
                onclick={() =>
                    handle_system_action(
                        native.window_control({ action: 'kiosk', value: true }),
                        'Kiosk Mode'
                    )}
                class="btn btn-xs preset-tonal-surface hover:preset-filled-primary-500"
            >
                <span class="fas fa-desktop mr-1"></span> Kiosk
            </button>
        </div>
    </div>

    <!-- 2. Presentation Remote Control (Common) -->
    <div class="flex flex-col gap-2">
        <div class="flex flex-row justify-between items-center px-1">
            <label class="text-[9px] font-bold uppercase opacity-50"
                >Remote Control</label
            >
            <select
                bind:value={remote_app}
                class="select select-sm py-0 h-5 text-[9px] w-24 preset-tonal-surface"
            >
                <option value="powerpoint">PowerPoint</option>
                <option value="keynote">Keynote</option>
            </select>
        </div>

        <div class="grid grid-cols-4 gap-1">
            <button
                type="button"
                onclick={() => handle_remote_control('prev')}
                class="btn btn-sm preset-tonal-secondary"
                title="Previous Slide"
            >
                <span class="fas fa-step-backward"></span>
            </button>
            <button
                type="button"
                onclick={() => handle_remote_control('start')}
                class="btn btn-sm preset-tonal-success"
                title="Start/Resume Slideshow"
            >
                <span class="fas fa-play"></span>
            </button>
            <button
                type="button"
                onclick={() => handle_remote_control('stop')}
                class="btn btn-sm preset-tonal-error"
                title="Stop Slideshow"
            >
                <span class="fas fa-stop"></span>
            </button>
            <button
                type="button"
                onclick={() => handle_remote_control('next')}
                class="btn btn-sm preset-tonal-secondary"
                title="Next Slide"
            >
                <span class="fas fa-step-forward"></span>
            </button>
        </div>
        {#if remote_status}
            <div
                class="text-[9px] text-center italic animate-pulse text-primary-500"
            >
                {remote_status}
            </div>
        {/if}
    </div>

    <!-- 3. Technical Management (Edit Mode Only) -->
    {#if $ae_loc.edit_mode}
        <div
            class="col-span-full border-t border-surface-500/20 pt-3 mt-1 flex flex-col gap-3"
        >
            <div class="grid grid-cols-2 gap-2">
                <div class="flex flex-col gap-1">
                    <label class="text-[9px] font-bold uppercase opacity-50"
                        >System Actions</label
                    >
                    <div class="grid grid-cols-1 gap-1">
                        <button
                            type="button"
                            onclick={() =>
                                handle_system_action(
                                    native.set_display_layout({
                                        mode: 'extend'
                                    }),
                                    'Extend Display'
                                )}
                            class="btn btn-xs preset-tonal-surface hover:preset-filled-primary-500 justify-start"
                        >
                            <span class="fas fa-columns mr-2 w-3"></span> Extend Mode
                        </button>
                        <button
                            type="button"
                            onclick={() =>
                                handle_system_action(
                                    native.set_wallpaper({
                                        path: $ae_loc.site_header_image_path
                                    }),
                                    'Wallpaper'
                                )}
                            class="btn btn-xs preset-tonal-surface hover:preset-filled-primary-500 justify-start"
                            disabled={!$ae_loc.site_header_image_path}
                        >
                            <span class="fas fa-image mr-2 w-3"></span> Reset Wallpaper
                        </button>
                    </div>
                </div>
                <div class="flex flex-col gap-1">
                    <label
                        class="text-[9px] font-bold uppercase opacity-50 text-error-500"
                        >Power</label
                    >
                    <div class="grid grid-cols-1 gap-1">
                        <button
                            type="button"
                            onclick={() =>
                                (show_power_confirm = {
                                    action: 'reboot',
                                    label: 'Reboot Laptop'
                                })}
                            class="btn btn-xs preset-tonal-warning hover:preset-filled-warning-500 justify-start"
                        >
                            <span class="fas fa-sync-alt mr-2 w-3"></span> Reboot
                        </button>
                        <button
                            type="button"
                            onclick={() =>
                                (show_power_confirm = {
                                    action: 'shutdown',
                                    label: 'Shutdown Laptop'
                                })}
                            class="btn btn-xs preset-tonal-error hover:preset-filled-error-500 justify-start"
                        >
                            <span class="fas fa-power-off mr-2 w-3"></span> Shutdown
                        </button>
                    </div>
                </div>
            </div>

            <div class="flex flex-col gap-1">
                <label class="text-[9px] font-bold uppercase opacity-50 ml-1"
                    >Terminal Access</label
                >
                <div class="flex gap-1">
                    <input
                        type="text"
                        bind:value={$events_sess.launcher.manual_cmd}
                        placeholder="ls -la"
                        class="input input-sm grow text-[10px] preset-tonal-surface h-7"
                    />
                    <button
                        type="button"
                        onclick={async () => {
                            test_cmd_result = 'Running...';
                            const res = await native.run_cmd({
                                cmd:
                                    $events_sess.launcher.manual_cmd || 'uptime'
                            });
                            test_cmd_result =
                                (res as any).stdout ||
                                (res as any).error ||
                                'No Output';
                        }}
                        class="btn btn-sm preset-filled-secondary hover:preset-filled-primary-500 text-[10px] h-7"
                        >Run</button
                    >
                </div>
                {#if test_cmd_result}
                    <pre
                        class="text-[8px] bg-black text-green-500 p-2 mt-1 overflow-x-auto rounded border border-surface-500/50 max-h-24 shadow-inner">{test_cmd_result}</pre>
                {/if}
            </div>
        </div>
    {/if}
</Launcher_Cfg_Section>

<!-- Power Confirmation Modal -->
{#if show_power_confirm}
    <div
        class="fixed inset-0 z-[1000] flex items-center justify-center bg-black/50 backdrop-blur-sm p-4"
    >
        <div
            class="card p-6 w-full max-w-sm preset-filled-surface-100-900 border border-error-500 shadow-2xl animate-in zoom-in-95 duration-200"
        >
            <h4 class="h4 text-error-500 font-bold mb-2">
                Confirm System Action
            </h4>
            <p class="text-sm opacity-80 mb-6">
                Are you sure you want to <strong
                    >{show_power_confirm.action}</strong
                > this host machine?
            </p>
            <div class="flex justify-end gap-2">
                <button
                    type="button"
                    onclick={() => (show_power_confirm = null)}
                    class="btn btn-sm preset-tonal-surface">Cancel</button
                >
                <button
                    type="button"
                    onclick={() => {
                        const action = show_power_confirm?.action;
                        show_power_confirm = null;
                        if (action)
                            handle_system_action(
                                native.power_control({ action: action as any }),
                                action
                            );
                    }}
                    class="btn btn-sm preset-filled-error"
                >
                    Confirm {show_power_confirm.action}
                </button>
            </div>
        </div>
    </div>
{/if}
