<script lang="ts">
import { ae_loc, ae_api, ae_sess } 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 * as native from '$lib/electron/electron_relay';
import Launcher_Cfg_Section from './launcher_cfg_section.svelte';
import {
    Code,
    Columns2,
    Copy,
    FlaskConical,
    FolderOpen,
    Image,
    Maximize2,
    Monitor,
    Play,
    Power,
    RefreshCw,
    SkipBack,
    SkipForward,
    Square,
    XCircle
} from '@lucide/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('');
let display_mode = $state<'extend' | 'mirror'>('extend');

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);
}

async function handle_display_mode(mode: 'extend' | 'mirror') {
    system_status = `Setting display: ${mode}...`;
    const res = await native.set_display_layout({ mode });
    if (res?.success) {
        display_mode = mode;
        system_status = `Display: ${mode}`;
    } else {
        system_status = `Display error: ${res?.error || 'No external display?'}`;
    }
    setTimeout(() => (system_status = ''), 4000);
}

// Process names sent to kill_processes() when the operator hits "Kill Apps".
// Covers the standard conference presentation app set — PowerPoint, Keynote, Acrobat, VLC, LibreOffice.
// Override per device via event_device.other_json.launcher.kill_process_li.
const DEFAULT_KILL_LIST = [
    'Microsoft PowerPoint',
    'Keynote',
    'Adobe Acrobat Reader DC',
    'VLC',
    'soffice'
];

async function handle_kill_apps() {
    const native_device = ($ae_loc as any).native_device ?? null;
    const process_name_li: string[] =
        native_device?.other_json?.launcher?.kill_process_li ?? DEFAULT_KILL_LIST;
    system_status = `Killing: ${process_name_li.join(', ')}...`;
    await native.kill_processes({ process_name_li });
    system_status = 'Kill signal sent';
    setTimeout(() => (system_status = ''), 4000);
}

// 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={Code}
    bind:state={launcher_loc.current.section_state__native_os}
    {on_expand}
    description="OS: {$ae_loc.native_device?.meta_json?.platform ||
        '...'} | Kiosk & Apps">
    <!-- Dev preview banner: shown when edit_mode is on but not running in Electron.
         electron_relay functions all return null when native is absent — no errors. -->
    {#if $ae_loc.edit_mode && !$ae_loc.is_native}
        <div
            class="bg-warning-500/10 border-warning-500/30 mb-1 flex items-center gap-2 rounded-lg border px-2 py-1.5">
            <FlaskConical size="0.75em" class="text-warning-500" />
            <span
                class="text-warning-500 text-[9px] font-bold tracking-wide uppercase"
                >Dev Preview — controls visible but non-functional without
                Electron</span>
        </div>
    {/if}

    {#if system_status}
        <div
            class="bg-surface-500/10 text-primary-500 border-primary-500/20 col-span-full animate-pulse rounded border py-1 text-center text-[10px] italic">
            {system_status}
        </div>
    {/if}

    <!-- 1. Window & Folders (Common) -->
    <div class="flex flex-col gap-2">
        <p class="ml-1 text-[9px] font-bold uppercase opacity-50">
            Folders & View
        </p>
        <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">
                <FolderOpen size="0.85em" class="mr-1 shrink-0" /> 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">
                <FolderOpen size="0.85em" class="mr-1 shrink-0" /> Temp
            </button>
            <button
                type="button"
                onclick={() => native.window_control({ action: 'maximize' })}
                class="btn btn-xs preset-tonal-surface hover:preset-filled-primary-500">
                <Maximize2 size="0.85em" class="mr-1" /> 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">
                <Monitor size="0.85em" class="mr-1" /> Kiosk
            </button>
        </div>
    </div>

    <!-- Display mode toggle: Extend = independent screens (default); Mirror = same content on both -->
    <div class="flex flex-col gap-2">
        <p class="ml-1 text-[9px] font-bold uppercase opacity-50">Display Mode</p>
        <div class="grid grid-cols-2 gap-1">
            <button
                type="button"
                onclick={() => handle_display_mode('extend')}
                class="btn btn-xs justify-start border-2"
                class:border-primary-500={display_mode === 'extend'}
                class:preset-tonal-primary={display_mode === 'extend'}
                class:border-surface-400={display_mode !== 'extend'}
                class:preset-tonal-surface={display_mode !== 'extend'}>
                <Columns2 size="0.85em" class="mr-1 shrink-0" /> Extend
            </button>
            <button
                type="button"
                onclick={() => handle_display_mode('mirror')}
                class="btn btn-xs justify-start border-2"
                class:border-warning-500={display_mode === 'mirror'}
                class:preset-tonal-warning={display_mode === 'mirror'}
                class:border-surface-400={display_mode !== 'mirror'}
                class:preset-tonal-surface={display_mode !== 'mirror'}>
                <Copy size="0.85em" class="mr-1 shrink-0" /> Mirror
            </button>
        </div>
    </div>

    <!-- 2. Presentation Remote Control (Common) -->
    <div class="flex flex-col gap-2">
        <div class="flex flex-row items-center justify-between px-1">
            <p class="text-[9px] font-bold uppercase opacity-50">
                Remote Control
            </p>
            <select
                bind:value={remote_app}
                class="select select-sm preset-tonal-surface h-5 w-24 py-0 text-[9px]">
                <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">
                <SkipBack size="1em" />
            </button>
            <button
                type="button"
                onclick={() => handle_remote_control('start')}
                class="btn btn-sm preset-tonal-success"
                title="Start/Resume Slideshow">
                <Play size="1em" />
            </button>
            <button
                type="button"
                onclick={() => handle_remote_control('stop')}
                class="btn btn-sm preset-tonal-error"
                title="Stop Slideshow">
                <Square size="1em" />
            </button>
            <button
                type="button"
                onclick={() => handle_remote_control('next')}
                class="btn btn-sm preset-tonal-secondary"
                title="Next Slide">
                <SkipForward size="1em" />
            </button>
        </div>
        {#if remote_status}
            <div
                class="text-primary-500 animate-pulse text-center text-[9px] italic">
                {remote_status}
            </div>
        {/if}
    </div>

    <!-- 3. Technical Management (Edit Mode Only) -->
    {#if $ae_loc.edit_mode}
        <div
            class="border-surface-500/20 col-span-full mt-1 flex flex-col gap-3 border-t pt-3">
            <div class="grid grid-cols-2 gap-2">
                <div class="flex flex-col gap-1">
                    <p class="text-[9px] font-bold uppercase opacity-50">
                        System Actions
                    </p>
                    <div class="grid grid-cols-1 gap-1">
                        <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}>
                            <Image size="0.85em" class="mr-1 shrink-0" /> Reset Wallpaper
                        </button>
                        <!-- Kill running presentation apps — PowerPoint, Keynote, Acrobat, VLC, LibreOffice.
                             Use between sessions to ensure a clean slate. List is overridable via
                             event_device.other_json.launcher.kill_process_li. -->
                        <button
                            type="button"
                            onclick={handle_kill_apps}
                            class="btn btn-xs preset-tonal-error hover:preset-filled-error-500 justify-start"
                            title="Kill presentation apps: {DEFAULT_KILL_LIST.join(', ')}">
                            <XCircle size="0.85em" class="mr-1 shrink-0" /> Kill Apps
                        </button>
                    </div>
                </div>
                <div class="flex flex-col gap-1">
                    <span
                        class="text-error-500 text-[9px] font-bold uppercase opacity-50"
                        >Power</span>
                    <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">
                            <RefreshCw size="0.85em" class="mr-1 shrink-0" /> 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">
                            <Power size="0.85em" class="mr-1 shrink-0" /> Shutdown
                        </button>
                    </div>
                </div>
            </div>

            <div class="flex flex-col gap-1">
                <p class="ml-1 text-[9px] font-bold uppercase opacity-50">
                    Terminal Access
                </p>
                <div class="flex gap-1">
                    <input
                        type="text"
                        bind:value={$events_sess.launcher.manual_cmd}
                        placeholder="ls -la"
                        class="input input-sm preset-tonal-surface h-7 grow text-[10px]" />
                    <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 h-7 text-[10px]"
                        >Run</button>
                </div>
                {#if test_cmd_result}
                    <pre
                        class="border-surface-500/50 mt-1 max-h-24 overflow-x-auto rounded border bg-black p-2 text-[8px] text-green-500 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 p-4 backdrop-blur-sm">
        <div
            class="card preset-filled-surface-100-900 border-error-500 animate-in zoom-in-95 w-full max-w-sm border p-6 shadow-2xl duration-200">
            <h4 class="h4 text-error-500 mb-2 font-bold">
                Confirm System Action
            </h4>
            <p class="mb-6 text-sm opacity-80">
                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}
