<script lang="ts">
/**
 * ae_comp__journal_entry_header.svelte
 * Standardized Journal Entry Header.
 * Manages name, sync status, and triggers the modular config.
 */
import {
    ChevronLeft,
    CircleCheck,
    CircleX,
    Eye,
    // FingerprintPattern,
    LoaderCircle,
    LockKeyhole,
    LockKeyholeOpen,
    Pencil,
    RefreshCw,
    Save,
    Settings
} from '@lucide/svelte';
import { ae_util } from '$lib/ae_utils/ae_utils';
import { ae_loc } from '$lib/stores/ae_stores';
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 w-full flex-wrap items-center gap-3 rounded-xl
           border border-gray-200
           bg-gray-50 p-3 shadow-sm
           dark:border-gray-700 dark:bg-gray-800">
    <div class="flex min-w-48 flex-[1_1_0%] items-center gap-3">
        <a
            href="/journals/{journal.journal_id}"
            class="btn-icon btn-icon-sm preset-tonal-surface transition-colors duration-150"
            title="Back to Journal">
            <ChevronLeft size="1.2em" />
        </a>

        <div class="flex min-w-0 flex-1 items-center gap-2">
            <button
                type="button"
                onclick={toggle_edit_mode}
                title={$journals_loc.entry.edit_kv[entry.journal_entry_id] === 'current'
                    ? (has_changed ? 'Save & exit edit mode' : 'Exit edit mode')
                    : 'Edit entry'}
                class="btn-icon btn-icon-sm transition-colors duration-150 {has_changed &&
                $journals_loc.entry.edit_kv[entry.journal_entry_id] ===
                    'current'
                    ? 'preset-tonal-warning hover:preset-filled-warning-500'
                    : 'preset-tonal-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 focus:ring-primary-500 h-10 min-w-0 flex-1 border-none bg-transparent text-lg leading-none font-bold transition-colors duration-150 focus:ring-2"
                    placeholder="Entry Title..."
                    onchange={on_save} />
            {:else}
                <h2
                    class="flex h-10 min-w-0 flex-1 items-center truncate text-base leading-none font-bold md:text-lg">
                    {entry.name ||
                        ae_util.iso_datetime_formatter(
                            entry.created_on,
                            'datetime_iso_12_no_seconds'
                        )}
                </h2>
            {/if}
        </div>
    </div>

    <div
        class="ml-auto flex shrink-0 items-center gap-2 whitespace-nowrap transition-colors duration-150">
        <!-- Auto-Save indicator -->
        {#if $journals_loc.entry.edit_kv[entry.journal_entry_id] === 'current'}
            <div
                class="border-surface-500/20 mr-1 flex items-center gap-1 border-r px-2">
                <button
                    type="button"
                    class="btn-icon btn-icon-sm transition-colors duration-150 {$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'}<LoaderCircle
                            size="1em"
                            class="text-primary-500 animate-spin" />
                    {: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-colors duration-150 {is_decrypted
                    ? 'preset-filled-success shadow-success-500/20 shadow-lg'
                    : 'preset-tonal-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}

        <!-- Unified Config Button -->
        <button
            type="button"
            onclick={on_show_config}
            class:hidden={!$ae_loc.edit_mode}
            class="
                btn btn-sm preset-tonal-primary font-bold transition-colors duration-150
                "
            title="Entry Configuration"
            >
            <Settings size="1.1em" />Config
        </button>

        <!-- Explicit Save (Mobile/Backup) -->
        <!-- {#if has_changed && save_status !== 'saving'}
            <button
                type="button"
                onclick={on_save}
                class="
                    btn btn-sm
                    preset-filled-primary
                    transition-colors duration-150
                    md:hidden
                    "
                title="Save changes"
                >
                <Save size="1.1em" class="" />Save
            </button>
        {/if} -->
    </div>
</header>
