<script lang="ts">
    /**
     * JournalEntry_SettingsMenu.svelte
     * Extracted 2026-01-08 to modularize the Journal Entry Header.
     * Manages Category, Flags, Copy/Clone, History, and Sort Order.
     */
    import { 
        Plus, Minus, ArrowDown10, Flag, FlagOff, 
        Eye, EyeOff, ShieldCheck, ShieldMinus, 
        Clock, X, Trash2, Settings, Shapes,
        Copy, RemoveFormatting, CodeXml, TypeOutline,
        History, Pencil, PenLine, FileX, SquareLibrary,
        ArrowUpToLine, ArrowDownToLine
    } from '@lucide/svelte';
    import { ae_loc, ae_api } from '$lib/stores/ae_stores';
    import { journals_slct, journals_loc, journals_sess } from '$lib/ae_journals/ae_journals_stores';
    import { journals_func } from '$lib/ae_journals/ae_journals_functions';
    import { goto } from '$app/navigation';
    import AE_ObjectFlags from '$lib/ae_elements/AE_ObjectFlags.svelte';
    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
        onSave: () => void;
        onDecryptHistory: () => void;
        onChangeJournal: () => void;
        onAppend?: () => void;
        onPrepend?: () => void;
        log_lvl?: number;
    }

    let { 
        entry, 
        journal, 
        journals_li = [],
        tmp_entry_obj = $bindable(), 
        onSave,
        onDecryptHistory,
        onChangeJournal,
        onAppend,
        onPrepend,
        log_lvl = 0 
    }: Props = $props();

    async function delete_entry() {
        if (confirm(`Are you sure you want to delete this journal entry?`)) {
            let delete_method: "delete" | "disable" | "hide" = "disable";
            if ($ae_loc.administrator_access && $ae_loc.edit_mode) {
                delete_method = 'delete';
            }
            try {
                await journals_func.delete_ae_obj_id__journal_entry({
                    api_cfg: $ae_api,
                    journal_entry_id: entry.journal_entry_id,
                    method: delete_method,
                    log_lvl
                });
                alert('Journal entry deleted successfully!');
                goto(`/journals/${$journals_slct.journal_id}`);
            } catch (error) {
                console.error('Error deleting journal entry:', error);
                alert('Failed to delete journal entry.');
            }
        }
    }

    function copyToClipboard(text: string, msg: string) {
        navigator.clipboard.writeText(text)
            .then(() => alert(msg))
            .catch(err => console.error('Copy failed:', err));
    }

    async function copyRichText() {
        const element = document.getElementById(`rendered_journal_entry_content_${entry.journal_entry_id}`);
        if (!element) return;
        try {
            await navigator.clipboard.write([
                new ClipboardItem({ 'text/html': new Blob([element.innerHTML], { type: 'text/html' }) })
            ]);
            alert('Rich text copied!');
        } catch (err) {
            console.error('Rich copy failed:', err);
        }
    }
</script>

<div class="space-y-4 min-w-[280px]">
    <!-- Append/Prepend Actions -->
    <div class="grid grid-cols-2 gap-2">
         <button class="btn btn-sm variant-soft-secondary" onclick={onPrepend} title="Prepend to Note">
             <ArrowUpToLine size="1.2em" class="mr-1"/> Prepend
         </button>
         <button class="btn btn-sm variant-soft-secondary" onclick={onAppend} title="Append to Note">
             <ArrowDownToLine size="1.2em" class="mr-1"/> Append
         </button>
    </div>

    <!-- Category selection -->
    <div class="flex items-center gap-2">
        <Shapes size="1.1em" class="text-surface-500" />
        <select
            class="select select-sm preset-tonal-primary grow"
            bind:value={tmp_entry_obj.category_code}
            onchange={onSave}
        >
            <option value="">Select Category</option>
            <!-- @ts-ignore -->
            {#each journal?.cfg_json?.category_li ?? [] as category}
                <option value={category.code}>{category.name}</option>
            {/each}
        </select>
    </div>

    <!-- Flags (Standardized component) -->
    <AE_ObjectFlags 
        bind:obj={tmp_entry_obj} 
        onToggle={onSave}
        hideAlert={journal?.cfg_json?.hide_btn_alert}
        hidePrivate={journal?.cfg_json?.hide_btn_private}
        hidePublic={journal?.cfg_json?.hide_btn_public}
        hidePersonal={journal?.cfg_json?.hide_btn_personal}
        hideProfessional={journal?.cfg_json?.hide_btn_professional}
        hideTemplate={journal?.cfg_json?.hide_btn_template}
    />

    <!-- Copy Actions -->
    <div class="grid grid-cols-3 gap-1">
        <button class="btn btn-sm variant-soft-surface" onclick={() => copyToClipboard(tmp_entry_obj.content, 'Markdown copied!')} title="Copy Markdown">
            <RemoveFormatting size="1.2em" />
        </button>
        <button class="btn btn-sm variant-soft-surface" onclick={() => copyToClipboard(entry.content_md_html || '', 'HTML copied!')} title="Copy HTML">
            <CodeXml size="1.2em" />
        </button>
        <button class="btn btn-sm variant-soft-surface" onclick={copyRichText} title="Copy Rich Text">
            <TypeOutline size="1.2em" />
        </button>
    </div>

    <div class="divider !my-1"></div>

    <!-- History & Sort Section -->
    <div class="flex flex-col gap-2">
        <!-- History Toggle -->
        {#if entry.history || entry.history_encrypted}
            <button
                class="btn btn-sm w-full { $journals_loc.entry.edit_kv[entry.journal_entry_id] === 'history' ? 'variant-filled-secondary' : 'variant-soft-secondary'}"
                onclick={onDecryptHistory}
            >
                <History size="1.1em" class="mr-2" /> Review History
            </button>
        {/if}

        <!-- Cleaned Sort Controls -->
        <div class="flex items-center justify-between p-2 bg-surface-500/10 rounded-lg border border-surface-500/20">
            <span class="text-xs font-bold uppercase tracking-wider opacity-60">Sort Order</span>
            <div class="flex items-center gap-3">
                <button
                    class="btn-icon btn-icon-sm variant-filled-surface border border-surface-500/50"
                    onclick={() => { tmp_entry_obj.sort = (entry.sort ?? 0) + 1; onSave(); }}
                >
                    <Plus size="1em" />
                </button>
                <span class="font-mono font-bold text-sm w-6 text-center">{tmp_entry_obj.sort ?? entry.sort ?? 0}</span>
                <button
                    class="btn-icon btn-icon-sm variant-filled-surface border border-surface-500/50"
                    onclick={() => { tmp_entry_obj.sort = Math.max(0, (entry.sort ?? 0) - 1); onSave(); }}
                >
                    <Minus size="1em" />
                </button>
            </div>
        </div>
    </div>

    <!-- Archive Control -->
    <div class="flex items-center gap-2 p-1 bg-surface-500/5 rounded border border-surface-500/10">
        <Clock size="1.1em" class="opacity-50 ml-1" />
        <input type="datetime-local" bind:value={tmp_entry_obj.archive_on} onchange={onSave} class="input input-sm border-none bg-transparent text-xs grow" />
        {#if entry.archive_on}
            <button onclick={() => { tmp_entry_obj.archive_on = null; onSave(); }} class="btn-icon btn-icon-sm text-error-500"><X size="1em"/></button>
        {/if}
    </div>

    <!-- Move to Journal -->
    {#if $ae_loc.edit_mode && journals_li.length}
        <div class="p-2 border border-surface-500/20 rounded-lg space-y-1">
            <span class="text-[10px] uppercase font-bold opacity-50 flex items-center gap-1">
                <SquareLibrary size="1em" /> Move to Journal
            </span>
            <select
                class="select select-sm w-full text-xs"
                bind:value={tmp_entry_obj.journal_id}
                onchange={() => { if(confirm('Change parent journal?')) onChangeJournal(); }}
            >
                <option value="">Select Journal</option>
                {#each journals_li as j}
                    <option value={j.journal_id}>{j.name}</option>
                {/each}
            </select>
        </div>
    {/if}

    <!-- Deletion -->
    <button class="btn btn-sm variant-filled-error w-full mt-2" onclick={delete_entry}>
        <Trash2 size="1.1em" class="mr-2" /> Delete Entry
    </button>
</div>