<script lang="ts">
    import { onMount } from 'svelte';
    import { page } from '$app/stores';
    import {
        load_ae_obj_id__site,
        update_ae_obj__site,
        delete_ae_obj_id__site,
        load_ae_obj_li__site_domain,
        create_ae_obj__site_domain,
        update_ae_obj__site_domain,
        delete_ae_obj_id__site_domain
    } from '$lib/ae_core/ae_core__site';
    import { editable_fields__site } from '$lib/ae_core/ae_core__site.editable_fields';
    import { editable_fields__site_domain } from '$lib/ae_core/ae_core__site_domain.editable_fields';
    import { ae_api, ae_loc } from '$lib/stores/ae_stores';
    import { goto } from '$app/navigation';
    import { Save, Trash2, ArrowLeft, Globe, Plus, ExternalLink, Key, Settings, Activity, Info, Database } from 'lucide-svelte';
    import AE_Comp_Site_Config_Editor from '$lib/ae_core/ae_comp__site_config_editor.svelte';

    let site_id = $derived($page.params.site_id ?? '');
    let site: any = $state(null);
    let domain_li: any[] = $state([]);
    let loading = $state(true);
    let saving = $state(false);

    async function load_data() {
        loading = true;
        site = await load_ae_obj_id__site({
            api_cfg: $ae_api,
            site_id,
            log_lvl: 1
        });
        domain_li = await load_ae_obj_li__site_domain({
            api_cfg: $ae_api,
            site_id,
            enabled: 'all',
            hidden: 'all',
            log_lvl: 1
        });
        loading = false;
    }

    onMount(() => {
        if (!$ae_loc.manager_access) {
            goto('/core');
            return;
        }
        load_data();
    });

    async function handle_save_site() {
        saving = true;
        const data_kv: any = {};
        editable_fields__site.forEach(field => {
            if (site[field] !== undefined) {
                data_kv[field] = site[field];
            }
        });

        // Ensure cfg_json is included explicitly
        data_kv.cfg_json = site.cfg_json;

        await update_ae_obj__site({
            api_cfg: $ae_api,
            site_id,
            data_kv,
            log_lvl: 1
        });
        saving = false;
    }

    async function handle_add_domain() {
        const fqdn = prompt('Enter new domain (e.g. example.com):');
        if (!fqdn) return;

        await create_ae_obj__site_domain({
            api_cfg: $ae_api,
            site_id,
            data_kv: { fqdn, enable: true },
            log_lvl: 1
        });
        load_data();
    }

    async function handle_toggle_domain(dom: any) {
        await update_ae_obj__site_domain({
            api_cfg: $ae_api,
            site_id,
            site_domain_id: dom.site_domain_id_random,
            data_kv: { enable: !dom.enable },
            log_lvl: 1
        });
        load_data();
    }

    async function handle_delete_domain(dom: any) {
        if (!confirm(`Remove domain ${dom.fqdn}?`)) return;
        await delete_ae_obj_id__site_domain({
            api_cfg: $ae_api,
            site_id,
            site_domain_id: dom.site_domain_id_random,
            method: 'delete',
            log_lvl: 1
        });
        load_data();
    }
</script>

<div class="container mx-auto p-4 space-y-6">
    <header class="flex justify-between items-center bg-surface-50-900-token p-4 rounded-xl shadow-lg border border-surface-500/10">
        <div class="flex items-center gap-4">
            <a class="btn btn-sm variant-soft-surface shadow-sm" href="/core/sites">
                <ArrowLeft size={16} />
            </a>
            <div class="flex items-center gap-2">
                <div class="p-2 bg-primary-500/10 rounded-lg">
                    <Globe size={24} class="text-primary-500" />
                </div>
                <h1 class="h2 font-black tracking-tight">{site?.name ?? 'Loading...'}</h1>
            </div>
        </div>
        <button class="btn btn-sm variant-filled-primary font-bold shadow-lg" onclick={handle_save_site} disabled={loading || saving}>
            {#if saving}
                <span class="animate-spin mr-2">⏳</span>
            {:else}
                <Save size={16} class="mr-2" />
            {/if}
            Save Site Changes
        </button>
    </header>

    {#if loading}
        <div class="card p-8 flex justify-center items-center h-64">
            <div class="placeholder animate-pulse w-full h-full rounded-2xl"></div>
        </div>
    {:else if site}
        <div class="grid grid-cols-1 lg:grid-cols-3 gap-6">
            <!-- Site Config -->
            <div class="lg:col-span-2 space-y-6">
                <div class="card p-6 space-y-4 shadow-xl variant-glass-surface border border-surface-500/10">
                    <h3 class="h4 font-bold border-b border-surface-500/30 pb-2 flex items-center gap-2">
                        <Settings size={18} class="text-primary-500" /> Site Configuration
                    </h3>
                    <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
                        <div class="space-y-1">
                            <span class="label block text-xs font-bold opacity-75 uppercase tracking-wider ml-1">Site Name</span>
                            <input class="input variant-filled-surface rounded-lg p-3" type="text" bind:value={site.name} />
                        </div>
                        <div class="space-y-1">
                            <span class="label block text-xs font-bold opacity-75 uppercase tracking-wider ml-1">Site Code</span>
                            <input class="input variant-filled-surface rounded-lg font-mono p-3" type="text" bind:value={site.code} />
                        </div>
                        <div class="space-y-1 md:col-span-2">
                            <span class="label block text-xs font-bold opacity-75 uppercase tracking-wider ml-1">Tagline</span>
                            <input class="input variant-filled-surface rounded-lg p-3" type="text" bind:value={site.tagline} />
                        </div>
                        <div class="space-y-1 md:col-span-2">
                            <span class="label block text-xs font-bold opacity-75 uppercase tracking-wider ml-1">Description</span>
                            <textarea class="textarea variant-filled-surface rounded-lg p-3" rows="2" bind:value={site.description}></textarea>
                        </div>
                    </div>
                </div>

                <!-- Advanced Site JSON Config -->
                <div class="card p-6 space-y-4 shadow-xl variant-glass-surface border border-surface-500/10">
                    <h3 class="h4 font-bold border-b border-surface-500/30 pb-2 flex items-center gap-2">
                        <Database size={18} class="text-warning-500" /> Site Settings (cfg_json)
                    </h3>
                    <AE_Comp_Site_Config_Editor 
                        bind:cfg_json={site.cfg_json} 
                        on_save={handle_save_site} 
                    />
                </div>

                <div class="card p-6 space-y-4 shadow-xl variant-glass-surface border border-surface-500/10">
                    <h3 class="h4 font-bold border-b border-surface-500/30 pb-2 flex items-center gap-2">
                        <Key size={18} class="text-secondary-500" /> Access Control
                    </h3>
                    <div class="flex flex-col gap-4">
                        <label class="flex items-center space-x-2 cursor-pointer group">
                            <input class="checkbox" type="checkbox" bind:checked={site.restrict_access} />
                            <span class="text-sm font-bold opacity-70 group-hover:opacity-100 transition-opacity">Restrict Access</span>
                        </label>
                        {#if site.restrict_access}
                            <div class="space-y-1 max-w-md animate-fade-in">
                                <span class="label block text-xs font-bold opacity-75 uppercase tracking-wider ml-1">Access Key</span>
                                <input class="input variant-filled-surface rounded-lg font-mono p-3" type="text" bind:value={site.access_key} />
                            </div>
                        {/if}
                    </div>
                </div>
            </div>

            <!-- Domains Management -->
            <div class="space-y-6">
                <div class="card p-6 space-y-4 shadow-xl variant-glass-surface border border-surface-500/10">
                    <header class="flex justify-between items-center border-b border-surface-500/30 pb-2">
                        <h3 class="h4 font-bold flex items-center gap-2">
                            <Globe size={18} class="text-tertiary-500" /> Site Domains
                        </h3>
                        <button class="btn btn-icon btn-sm variant-filled-secondary shadow-md" onclick={handle_add_domain} title="Add Domain">
                            <Plus size={14} />
                        </button>
                    </header>

                    {#if domain_li.length === 0}
                        <p class="text-sm opacity-60 text-center py-8 bg-surface-500/5 rounded-lg border-2 border-dashed border-surface-500/20">No domains configured.</p>
                    {:else}
                        <div class="space-y-3">
                            {#each domain_li as dom}
                                <div class="card p-3 variant-soft shadow-sm border border-surface-500/10 flex justify-between items-center group">
                                    <div class="flex flex-col">
                                        <span class="font-bold text-sm flex items-center gap-1">
                                            {dom.fqdn}
                                            <a href="https://{dom.fqdn}" target="_blank" rel="noopener noreferrer" class="opacity-30 group-hover:opacity-100 transition-opacity">
                                                <ExternalLink size={12} />
                                            </a>
                                        </span>
                                        <span class="text-[10px] uppercase font-bold tracking-tighter opacity-50">
                                            Key: <code class="text-primary-500">{dom.access_key || '--'}</code> &bull; {dom.enable ? 'Active' : 'Disabled'}
                                        </span>
                                    </div>
                                    <div class="flex gap-1">
                                        <button class="btn btn-icon btn-sm {dom.enable ? 'variant-soft-success' : 'variant-soft-error'}" onclick={() => handle_toggle_domain(dom)} title="Toggle Active">
                                            <Save size={14} />
                                        </button>
                                        <button class="btn btn-icon btn-sm variant-soft-error" onclick={() => handle_delete_domain(dom)} title="Delete Domain">
                                            <Trash2 size={14} />
                                        </button>
                                    </div>
                                </div>
                            {/each}
                        </div>
                    {/if}
                </div>

                <div class="card p-6 space-y-4 shadow-xl variant-glass-surface border border-surface-500/10">
                    <h3 class="h4 font-bold border-b border-surface-500/30 pb-2 flex items-center gap-2">
                        <Activity size={18} class="text-error-500" /> System Status
                    </h3>
                    <div class="space-y-4 py-2">
                        <label class="flex items-center space-x-3 cursor-pointer group">
                            <input class="checkbox" type="checkbox" bind:checked={site.enable} />
                            <span class="text-sm font-bold opacity-70 group-hover:opacity-100 transition-opacity">Site Enabled</span>
                        </label>
                        <label class="flex items-center space-x-3 cursor-pointer group">
                            <input class="checkbox" type="checkbox" bind:checked={site.hide} />
                            <span class="text-sm font-bold opacity-70 group-hover:opacity-100 transition-opacity">Hidden from Public</span>
                        </label>
                    </div>
                </div>
            </div>
        </div>
    {/if}
</div>
