<script lang="ts">
    /**
     * ae_comp__journal_entry_header.svelte
     * Standardized Journal Entry Header.
     * Manages name, sync status, and triggers the modular config.
     */
    import {
        Save,
        Eye,
        Pencil,
        Fingerprint,
        LockKeyhole,
        LockKeyholeOpen,
        Settings,
        ChevronLeft,
        CircleCheck,
        CircleX,
        Loader2,
        RefreshCw
    } from 'lucide-svelte';
    import { ae_util } from '$lib/ae_utils/ae_utils';
    import {
        journals_loc,
        journals_sess
    } from '$lib/ae_journals/ae_journals_stores';
    import type { ae_JournalEntry, ae_Journal } from '$lib/types/ae_types';

    interface Props {
        entry: ae_JournalEntry;
        journal: ae_Journal;
        journals_li?: ae_Journal[];
        tmp_entry_obj: any; // Bindable
        has_changed: boolean;
        save_status?: 'saved' | 'unsaved' | 'saving';
        on_save: () => void;
        on_decrypt: () => void;
        on_show_config: () => void;
        log_lvl?: number;
    }

    let {
        entry,
        journal,
        tmp_entry_obj = $bindable(),
        has_changed,
        save_status = 'saved',
        on_save,
        on_decrypt,
        on_show_config,
        log_lvl = 0
    }: Props = $props();

    const is_decrypted = $derived(
        $journals_sess?.journal_kv[journal?.id]?.journal_passcode_decrypted ===
            true
    );

    function toggle_edit_mode() {
        const isEditing =
            $journals_loc.entry.edit_kv[entry.journal_entry_id] === 'current';
        if (isEditing) {
            if (has_changed) on_save();
            else $journals_loc.entry.edit_kv[entry.journal_entry_id] = false;
        } else {
            $journals_loc.entry.edit_kv[entry.journal_entry_id] = 'current';
        }
    }
</script>

<header
    class="flex flex-col md:flex-row items-center justify-between gap-4 p-3 bg-surface-100/50 dark:bg-surface-900/50 rounded-xl border border-surface-500/20 backdrop-blur-md shadow-sm w-full"
>
    <div class="flex items-center gap-3 w-full md:w-auto">
        <a
            href="/journals/{journal.journal_id}"
            class="btn-icon btn-icon-sm variant-soft-surface"
            title="Back to Journal"
        >
            <ChevronLeft size="1.2em" />
        </a>

        <div class="flex items-center gap-2 grow">
            <button
                type="button"
                onclick={toggle_edit_mode}
                class="btn-icon btn-icon-sm transition-all {has_changed &&
                $journals_loc.entry.edit_kv[entry.journal_entry_id] ===
                    'current'
                    ? 'variant-filled-success'
                    : 'variant-soft-surface'}"
            >
                {#if $journals_loc.entry.edit_kv[entry.journal_entry_id] === 'current'}
                    {#if has_changed}<Save size="1.2em" />{:else}<Eye
                            size="1.2em"
                        />{/if}
                {:else}
                    <Pencil size="1.2em" />
                {/if}
            </button>

            {#if $journals_loc.entry.edit_kv[entry.journal_entry_id] == 'current'}
                <input
                    type="text"
                    bind:value={tmp_entry_obj.name}
                    class="input input-sm variant-form-material font-bold text-lg grow md:min-w-[300px] border-none bg-transparent focus:ring-0"
                    placeholder="Entry Title..."
                    onchange={on_save}
                />
            {:else}
                <h2 class="text-base md:text-lg font-bold truncate max-w-md">
                    {entry.name ||
                        ae_util.iso_datetime_formatter(
                            entry.created_on,
                            'datetime_iso_12_no_seconds'
                        )}
                </h2>
            {/if}
        </div>
    </div>

    <div class="flex items-center gap-2 w-full md:w-auto justify-end">
        <!-- Auto-Save indicator -->
        {#if $journals_loc.entry.edit_kv[entry.journal_entry_id] === 'current'}
            <div
                class="flex items-center gap-1 px-2 border-r border-surface-500/20 mr-1"
            >
                <button
                    type="button"
                    class="btn-icon btn-icon-sm {$journals_loc.entry.auto_save
                        ? 'text-primary-500'
                        : 'opacity-30'}"
                    onclick={() =>
                        ($journals_loc.entry.auto_save =
                            !$journals_loc.entry.auto_save)}
                    title="Toggle Auto Save"
                >
                    <RefreshCw size="1em" />
                </button>
                {#if $journals_loc.entry.auto_save}
                    {#if save_status === 'saving'}<Loader2
                            size="1em"
                            class="animate-spin text-primary-500"
                        />
                    {:else if save_status === 'saved'}<CircleCheck
                            size="1em"
                            class="text-success-500"
                        />
                    {:else}<CircleX size="1em" class="opacity-30" />{/if}
                {/if}
            </div>
        {/if}

        <!-- Decrypt Toggle (Lock) -->
        {#if entry.private}
            <button
                type="button"
                class="btn-icon btn-icon-sm transition-all {is_decrypted
                    ? 'variant-filled-success shadow-lg shadow-success-500/20'
                    : 'variant-soft-warning'}"
                onclick={on_decrypt}
                title={is_decrypted ? 'Lock Content' : 'Decrypt Content'}
            >
                {#if is_decrypted}<LockKeyholeOpen
                        size="1.2em"
                    />{:else}<LockKeyhole size="1.2em" />{/if}
            </button>
        {/if}

        <div class="w-[1px] h-6 bg-surface-500/20 mx-1"></div>

        <!-- Unified Config Button -->
        <button
            type="button"
            class="btn btn-sm variant-soft-primary font-bold"
            onclick={on_show_config}
        >
            <Settings size="1.1em" class="mr-2" /> Config
        </button>

        <!-- Explicit Save (Mobile/Backup) -->
        {#if has_changed && save_status !== 'saving'}
            <button
                type="button"
                class="btn btn-sm variant-filled-primary shadow-lg"
                onclick={on_save}
            >
                <Save size="1.1em" class="mr-2" /> Save
            </button>
        {/if}
    </div>
</header>
