<script lang="ts">
    import { onMount } from 'svelte';
    import { goto } from '$app/navigation';
    import { X } from 'lucide-svelte';
    import { ae_loc, ae_sess, slct, ae_api } from '$lib/stores/ae_stores';
    import { core_func } from '$lib/ae_core/ae_core_functions';
    import { Users, Plus, ListFilter } from 'lucide-svelte';
    import Comp_person_search from './ae_comp__person_search.svelte';
    import Comp_person_obj_tbl from '../ae_comp__person_obj_tbl.svelte';
    import Person_form from './ae_comp__person_form.svelte';

    let person_id_random_li: string[] = $state([]);
    let show_add_form = $state(false);

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

    {#if show_add_form}
        <div class="animate-fade-in">
            <Person_form
                onSave={(new_person) => {
                    show_add_form = false;
                    goto(`/core/people/${new_person.person_id_random}`);
                }}
                onCancel={() => show_add_form = false}
            />
        </div>
    {/if}

    <Comp_person_search on_results={(results) => {
        person_id_random_li = results.map(p => p.person_id_random);
        $ae_sess.person.show_report__person_li = true;
    }} />

    {#if $ae_sess.person.show_report__person_li}
        <div class="card p-6 variant-glass-surface shadow-xl space-y-4 border border-surface-500/10">
            <h3 class="h4 font-bold border-b border-surface-500/30 pb-2 flex items-center gap-2">
                <ListFilter size={18} class="text-secondary-500" />
                Search Results 
                <span class="badge variant-soft-secondary ml-auto">{person_id_random_li.length} found</span>
            </h3>
            <div class="overflow-x-auto">
                <Comp_person_obj_tbl
                    bind:person_id_random_li
                    show_user_fields={$ae_loc.administrator_access}
                ></Comp_person_obj_tbl>
            </div>
        </div>
    {/if}
</div>
