<script lang="ts">
    import { onMount } from 'svelte';
    import { ae_loc, ae_api, slct } from '$lib/stores/ae_stores';
    import { goto } from '$app/navigation';
    import { Phone, Plus, Search, Mail, User, ExternalLink, X, ListFilter, Contact, ShieldCheck, Activity } from 'lucide-svelte';
    import { load_ae_obj_li__contact, create_ae_obj__contact } from '$lib/ae_core/ae_core__contact';
    import Contact_form from './ae_comp__contact_form.svelte';

    let contact_li: any[] = $state([]);
    let qry_str = $state('');
    let filtered_li: any[] = $derived(
        qry_str
            ? contact_li.filter(c =>
                c.name?.toLowerCase().includes(qry_str.toLowerCase()) ||
                c.title?.toLowerCase().includes(qry_str.toLowerCase()) ||
                c.email?.toLowerCase().includes(qry_str.toLowerCase()) ||
                c.phone_office?.toLowerCase().includes(qry_str.toLowerCase())
              )
            : contact_li
    );
    let loading = $state(true);
    let show_add_form = $state(false);

    async function load_contacts() {
        if (!$ae_loc.account_id) return;
        loading = true;
        contact_li = await load_ae_obj_li__contact({
            api_cfg: $ae_api,
            for_obj_id: $ae_loc.account_id,
            enabled: 'all',
            hidden: 'all',
            log_lvl: 1
        });
        loading = false;
    }

    onMount(() => {
        if (!$ae_loc.manager_access) {
            goto('/core');
            return;
        }
        load_contacts();
    });
</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-2">
            <div class="p-2 bg-primary-500/10 rounded-lg">
                <Phone size={24} class="text-primary-500" />
            </div>
            <h1 class="h2 font-black tracking-tight">Contact Management</h1>
        </div>
        <button
            class="btn btn-sm variant-filled-primary font-bold shadow-lg"
            onclick={() => show_add_form = !show_add_form}
        >
            {#if show_add_form}
                <X size={16} class="mr-2" /> Cancel
            {:else}
                <Plus size={16} class="mr-2" /> Add Contact
            {/if}
        </button>
    </header>

    {#if show_add_form}
        <div class="animate-fade-in">
            <Contact_form
                onSave={(new_con) => {
                    show_add_form = false;
                    load_contacts();
                    if (new_con.contact_id_random) {
                        goto(`/core/contacts/${new_con.contact_id_random}`);
                    }
                }}
                onCancel={() => show_add_form = false}
            />
        </div>
    {/if}

    <div class="card p-6 shadow-xl variant-glass-surface border border-surface-500/10">
        <div class="max-w-2xl space-y-1">
            <span class="label block text-xs font-bold opacity-75 uppercase tracking-wider ml-1">Search Directory</span>
            <div class="flex bg-surface-200-700-token rounded-lg overflow-hidden border border-surface-500/20 shadow-inner group focus-within:ring-2 focus-within:ring-primary-500/50 transition-all">
                <div class="flex items-center justify-center px-4 bg-surface-300-600-token border-r border-surface-500/20">
                    <Search size={18} class="opacity-50" />
                </div>
                <input
                    class="bg-transparent border-0 ring-0 focus:ring-0 p-3 grow placeholder:opacity-50"
                    type="search"
                    bind:value={qry_str}
                    placeholder="Search by name, title, email, or phone..."
                />
                <button class="variant-filled-primary font-bold px-10 py-3 hover:brightness-110 transition-all border-l border-surface-500/20 flex items-center justify-center min-w-[100px]" onclick={load_contacts} disabled={loading}>
                    {#if loading}
                        <span class="animate-spin text-xl">⏳</span>
                    {:else}
                        <span class="whitespace-nowrap tracking-wide">Refresh</span>
                    {/if}
                </button>
            </div>
        </div>
    </div>

    {#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 filtered_li.length === 0}
        <div class="card p-12 text-center variant-glass-surface border-2 border-dashed border-surface-500/20 rounded-2xl">
            <Contact size={48} class="mx-auto mb-4 opacity-20" />
            <h3 class="h3 font-bold opacity-50">No Contacts Found</h3>
            <p class="opacity-60 max-w-xs mx-auto mt-2">Business and support contacts will appear here.</p>
        </div>
    {:else}
        <div class="card p-6 variant-glass-surface shadow-xl border border-surface-500/10">
            <h3 class="h4 font-bold border-b border-surface-500/30 pb-2 mb-6 flex items-center gap-2">
                <ListFilter size={18} class="text-secondary-500" />
                Directory Results
                <span class="badge variant-soft-secondary ml-auto">{filtered_li.length} entries</span>
            </h3>

            <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
                {#each filtered_li as con (con.contact_id_random)}
                    <div class="card p-5 space-y-4 variant-soft-surface shadow-md border border-surface-500/10 hover:border-primary-500/30 transition-all group relative">
                        <div class="absolute top-4 right-4">
                            <span class="badge {con.enable ? 'variant-filled-success' : 'variant-filled-error'} text-[8px] uppercase font-bold shadow-sm">
                                {con.enable ? 'Active' : 'Disabled'}
                            </span>
                        </div>

                        <header class="flex items-center gap-3">
                            <div class="avatar variant-filled-primary w-12 h-12 flex items-center justify-center rounded-full shadow-inner group-hover:scale-110 transition-transform">
                                <User size={24} />
                            </div>
                            <div class="pr-12">
                                <p class="font-black tracking-tight truncate">{con.name || con.title || '--'}</p>
                                <p class="text-[10px] uppercase font-bold opacity-50 truncate">{con.title || 'Support Contact'}</p>
                            </div>
                        </header>

                        <div class="space-y-2 text-xs opacity-70">
                            <div class="flex items-center gap-2 bg-black/5 p-2 rounded-lg">
                                <Mail size={14} class="text-primary-500 shrink-0" />
                                <span class="truncate">{con.email || 'No Email'}</span>
                            </div>
                            <div class="flex items-center gap-2 bg-black/5 p-2 rounded-lg">
                                <Phone size={14} class="text-secondary-500 shrink-0" />
                                <span class="truncate">{con.phone_office || con.phone_mobile || '--'}</span>
                            </div>
                        </div>

                        <a class="btn btn-sm variant-filled-primary font-bold w-full shadow-lg group-hover:brightness-110 transition-all" href="/core/contacts/{con.contact_id_random}">
                            Manage Contact
                        </a>
                    </div>
                {/each}
            </div>
        </div>
    {/if}
</div>
