<script lang="ts">
// *** Import Svelte core
import { onMount } from 'svelte';
import * as Lucide from '@lucide/svelte';

// *** Import Aether core variables and functions
import type { key_val } from '$lib/stores/ae_stores';
import { ae_util } from '$lib/ae_utils/ae_utils';
import { core_func } from '$lib/ae_core/ae_core_functions';
import { liveQuery } from 'dexie';
import { db_lookups } from '$lib/ae_core/db_lookups';
import {
    ae_snip,
    ae_loc,
    ae_sess,
    ae_api,
    ae_trig,
    slct,
    slct_trigger
} from '$lib/stores/ae_stores';
import { idaa_loc, idaa_sess, idaa_slct } from '$lib/stores/ae_idaa_stores';
import { archives_func } from '$lib/ae_archives/ae_archives_functions';

import AE_Comp_Editor_TipTap from '$lib/elements/element_editor_tiptap.svelte';
import Comp_hosted_files_upload from '$lib/elements/ae_comp__hosted_files_upload.svelte';
import Element_manage_hosted_file_li_wrap from '$lib/elements/element_manage_hosted_file_li_all.svelte';

interface Props {
    log_lvl?: number;
    lq__archive_content_obj: any;
    obj_changed?: boolean;
}

let { log_lvl = 0, lq__archive_content_obj, obj_changed = $bindable(false) }: Props = $props();

let create_archive_content_obj_promise: any;
let delete_archive_content_obj_promise: any;
let update_archive_content_obj_promise: any;
let upload__hosted_file_obj_promise: any;
let prom_api__archive_content_obj: any = $state();
let prom_api__archive_content_obj__hosted_file: any = $state();

let description_new_html = $state(
    $idaa_slct.archive_content_obj?.description ?? ''
);
let notes_new_html = $state($idaa_slct.archive_content_obj?.notes ?? '');
let disable_submit_btn = $state(false);

let slct_hosted_file_kv: key_val = $state({});

// Local $state for upload bind targets — Svelte 4 store mutations don't trigger $effect,
// so we can't bind directly to $idaa_slct.archive_content_obj.* for reactivity.
let upload_complete_local: boolean = $state(false);
let hosted_file_id_li_local: string[] = $state([]);
let hosted_file_obj_li_local: key_val[] = $state([]);

if ($idaa_slct.archive_content_id) {
    console.log(
        `Archive Content ID selected: ${$idaa_slct.archive_content_id}`
    );
    console.log(
        `Archive Content Object selected: ${$idaa_slct.archive_content_obj}`
    );
    if (
        $idaa_slct.archive_content_obj &&
        $idaa_slct.archive_content_obj.upload_complete === undefined
    ) {
        $idaa_slct.archive_content_obj.upload_complete = false;
    }
    if (
        $idaa_slct.archive_content_obj &&
        !Array.isArray($idaa_slct.archive_content_obj.hosted_file_id_li)
    ) {
        $idaa_slct.archive_content_obj.hosted_file_id_li = [];
    }
    if (
        $idaa_slct.archive_content_obj &&
        !Array.isArray($idaa_slct.archive_content_obj.hosted_file_obj_li)
    ) {
        $idaa_slct.archive_content_obj.hosted_file_obj_li = [];
    }
} else {
    $idaa_slct.archive_content_id = null;
    $idaa_slct.archive_content_obj = {
        archive_id: null,
        // archive_content_id_random: null,
        archive_content_type: 'hosted_file',
        name: null,
        description: null,
        content_html: null,
        // hosted_file_id_random: null,
        // file_path: null, // file_path is no longer used, but need to be aware of it.
        filename: null,
        file_extension: null,
        original_datetime: null,
        original_timezone: null,
        original_location: null,
        // original_url: null,
        // original_url_text: null,
        // access_key: null, // or passcode?

        enable: true,
        hide: false,
        priority: null,
        sort: null,
        notes: null,
        upload_complete: false,
        hosted_file_id_li: [],
        hosted_file_obj_li: []
    };
    console.log(
        `Archive Content Object started: ${$idaa_slct.archive_content_obj}`
    );
}

// Form shape for controlled inputs — enables dirty detection via snapshot comparison.
// Initialized AFTER the init block above so new-item defaults are in place.
interface ArchiveContentForm {
    name: string;
    code: string;
    archive_content_type: string;
    filename: string;
    file_extension: string;
    original_datetime_date: string;
    original_datetime_time: string;
    original_timezone: string;
    original_location: string;
    hide: boolean;
    priority: boolean | null;
    enable: boolean;
    sort: number | null;
    group: string;
}

function create_archive_content_form(obj: any, current_timezone = ''): ArchiveContentForm {
    return {
        name: obj?.name ?? '',
        code: obj?.code ?? '',
        archive_content_type: obj?.archive_content_type ?? 'hosted_file',
        filename: obj?.filename ?? '',
        file_extension: obj?.file_extension ?? '',
        original_datetime_date: obj?.original_datetime
            ? ae_util.iso_datetime_formatter(obj.original_datetime, 'date_iso')
            : '',
        original_datetime_time: obj?.original_datetime
            ? ae_util.iso_datetime_formatter(obj.original_datetime, 'time_iso')
            : '',
        original_timezone: obj?.original_timezone ?? current_timezone,
        original_location: obj?.original_location ?? '',
        hide: obj?.hide ?? false,
        priority: obj?.priority ?? null,
        enable: obj?.enable ?? true,
        sort: obj?.sort ?? null,
        group: obj?.group ?? ''
    };
}

let archive_content_form = $state(
    create_archive_content_form($idaa_slct.archive_content_obj, $ae_loc.current_timezone)
);
let orig_archive_content_form = $state(
    create_archive_content_form($idaa_slct.archive_content_obj, $ae_loc.current_timezone)
);
// Plain (non-reactive) snapshots for TipTap content comparison
let orig_description_html = $idaa_slct.archive_content_obj?.description ?? '';
let orig_notes_html = $idaa_slct.archive_content_obj?.notes ?? '';

// Timezone lookup — reactive IDB query; background refresh handled by liveQuery + TTL
// Sort: sort DESC (higher = first, NULL=0 last), then name ASC — matches Aether backend convention.
const lq__lu_time_zone = liveQuery(() =>
    db_lookups.lu_time_zone.toArray().then((arr) =>
        arr.sort((a, b) => {
            const s_diff = Number(b['sort'] ?? 0) - Number(a['sort'] ?? 0);
            if (s_diff !== 0) return s_diff;
            return (a.name ?? '').localeCompare(b.name ?? '');
        })
    )
);

onMount(() => {
    // Trigger background IDB refresh if stale/empty; liveQuery reacts automatically
    core_func.load_ae_obj_li__time_zone({ api_cfg: $ae_api, log_lvl });
});

function prevent_default<T extends Event>(fn: (event: T) => void) {
    return function (event: T) {
        event.preventDefault();
        fn(event);
    };
}

function mark_archive_content_form_saved() {
    orig_archive_content_form = JSON.parse(JSON.stringify(archive_content_form));
    orig_description_html = description_new_html;
    orig_notes_html = notes_new_html;
    obj_changed = false;
}

async function handle_submit_form(event: SubmitEvent) {
    if (log_lvl > 1) {
        console.log('*** handle_submit_form() ***');
        console.log(event.currentTarget);
    }

    disable_submit_btn = true;

    let form_data = new FormData(event.currentTarget as HTMLFormElement);
    if (log_lvl) {
        console.log(form_data);
    }

    let archive_content_di = ae_util.extract_prefixed_form_data({
        prefix: null,
        form_data: form_data,
        trim_values: true,
        bool_tf_str: true,
        log_lvl: 0
    });
    console.log(archive_content_di);

    let archive_content_do: key_val = {};

    if (!$idaa_slct.archive_content_id) {
        archive_content_do['archive_id'] = $idaa_slct.archive_id;
    }

    archive_content_do['name'] = archive_content_di.name;
    archive_content_do['code'] = archive_content_di?.code?.trim() || null;

    // Check if the description_new_html exists and is a string
    if (typeof description_new_html === 'string') {
        console.log('New description is a string');
        archive_content_do['description'] = description_new_html;
    } else {
        console.log('New description is not a string. Do nothing.');
        // archive_content_do['description'] = event_meeting_fd.description;
    }

    if (archive_content_di.archive_content_type) {
        archive_content_do['archive_content_type'] =
            archive_content_di.archive_content_type;
    } else {
        archive_content_do['archive_content_type'] = null;
    }

    // archive_content_do['enable_for_public'] = !!!archive_content_di.enable_for_public;

    // archive_content_do['file_path'] = archive_content_di.file_path;
    archive_content_do['filename'] =
        archive_content_di?.filename?.trim() ?? null;
    archive_content_do['file_extension'] =
        archive_content_di?.file_extension?.trim() ?? null;

    let date_time_str = null;
    let date_part = archive_content_di.original_datetime_date.trim();
    let time_part = archive_content_di.original_datetime_time.trim();
    if (date_part && time_part) {
        date_time_str = `${date_part} ${time_part}`;
    } else if (date_part) {
        date_time_str = `${date_part}T00:00:00`;
    } else if (time_part) {
        // date_time_str = `${time_part}`;
        date_time_str = false;
    }
    archive_content_do['original_datetime'] = date_time_str;

    archive_content_do['original_timezone'] =
        archive_content_di.original_timezone;

    archive_content_do['original_location'] =
        archive_content_di.original_location;

    archive_content_do['hide'] = archive_content_di.hide;
    archive_content_do['priority'] = archive_content_di.priority;
    if (archive_content_di.sort) {
        archive_content_do['sort'] = Number(archive_content_di.sort);
    } else {
        archive_content_do['sort'] = null;
    }
    if (archive_content_di.group) {
        archive_content_do['group'] = archive_content_di.group;
    } else {
        archive_content_do['group'] = null;
    }

    // console.log(`archive_content_di.enable = ${archive_content_di.enable}`);
    archive_content_do['enable'] = !!archive_content_di.enable;

    // Check if the notes_new_html exists and is a string
    if (typeof notes_new_html === 'string') {
        console.log('New notes is a string');
        archive_content_do['notes'] = notes_new_html;
    } else {
        console.log('New notes is not a string. Do nothing.');
        // archive_content_do['notes'] = event_meeting_fd.notes;
    }

    console.log(archive_content_do);

    if (!$idaa_slct.archive_content_id) {
        prom_api__archive_content_obj = archives_func
            .create_ae_obj__archive_content({
                api_cfg: $ae_api,
                archive_id: $idaa_slct.archive_id,
                data_kv: archive_content_do,
                log_lvl: log_lvl
            })
            .then(async function (archive_content_obj_create_result) {
                if (!archive_content_obj_create_result) {
                    console.log('The result was null or false.');
                    return false;
                }

                $idaa_slct.archive_content_id =
                    archive_content_obj_create_result.archive_content_id;

                $idaa_slct.archive_content_obj =
                    archive_content_obj_create_result;
                $idaa_slct.archive_content_obj.upload_complete = false;
                $idaa_slct.archive_content_obj.hosted_file_id_li = [];
                $idaa_slct.archive_content_obj.hosted_file_obj_li = [];

                mark_archive_content_form_saved();

                return archive_content_obj_create_result;
            })
            .catch(function (error: any) {
                console.log('Something went wrong.');
                console.log(error);
                return false;
            })
            .finally(() => {
                disable_submit_btn = false;
            });

        return create_archive_content_obj_promise;
    } else {
        prom_api__archive_content_obj = archives_func
            .update_ae_obj__archive_content({
                api_cfg: $ae_api,
                archive_content_id: $idaa_slct.archive_content_id,
                data_kv: archive_content_do,
                log_lvl: log_lvl
            })
            .then(function (archive_content_obj_update_result) {
                if (!archive_content_obj_update_result) {
                    console.log('The result was null or false.');
                    return false;
                }

                return archive_content_obj_update_result;
            })
            .catch(function (error: any) {
                console.log('Something went wrong.');
                console.log(error);
                return false;
            })
            .finally(() => {
                // We need to do all of this since the DB object has changed and the SLCT object does automatically update (yet...??? Svelte 5?).
                // $idaa_slct.archive_content_obj = await $lq__archive_content_obj;

                mark_archive_content_form_saved();
                $idaa_slct.archive_content_id = null;
                $idaa_slct.archive_content_obj = {};
                $idaa_sess.archives.show__modal_edit__archive_content_id = false;
            });

        return prom_api__archive_content_obj;
    }
}

async function handle_hosted_files_uploaded(
    hosted_file_id_li: string[],
    hosted_file_obj_li: any[]
) {
    console.log(`*** handle_hosted_files_uploaded() *** ${hosted_file_id_li}`);

    // We need to update the archive_content_obj with the new file (for now just the first one).
    prom_api__archive_content_obj = archives_func
        .update_ae_obj__archive_content({
            api_cfg: $ae_api,
            archive_content_id: $idaa_slct.archive_content_id,
            data_kv: {
                hosted_file_id: hosted_file_obj_li[0].hosted_file_id,
                // file_path: hosted_file_obj_li[0].file_path,
                filename: hosted_file_obj_li[0].filename,
                file_extension: hosted_file_obj_li[0].extension,
                archive_content_type: 'hosted_file'
            },
            log_lvl: log_lvl
        })
        .then(function (archive_content_obj_update_result) {
            // $idaa_slct.archive_content_obj = $lq__archive_content_obj;
            $idaa_slct.archive_content_obj = archive_content_obj_update_result;
            $idaa_slct.archive_content_obj.upload_complete = true;
            if (
                !Array.isArray($idaa_slct.archive_content_obj.hosted_file_id_li)
            ) {
                $idaa_slct.archive_content_obj.hosted_file_id_li = [];
            }
            if (
                !Array.isArray(
                    $idaa_slct.archive_content_obj.hosted_file_obj_li
                )
            ) {
                $idaa_slct.archive_content_obj.hosted_file_obj_li = [];
            }

            // Sync form and snapshot so a successful upload doesn't mark the form as dirty.
            archive_content_form.filename = archive_content_obj_update_result?.filename ?? '';
            archive_content_form.file_extension = archive_content_obj_update_result?.file_extension ?? '';
            archive_content_form.archive_content_type = 'hosted_file';
            orig_archive_content_form = JSON.parse(JSON.stringify(archive_content_form));
        })
        .catch(function (error: any) {
            console.log('Something went wrong.');
            console.log(error);
            return false;
        });
}

// Dirty detection — edit mode only. Create mode Save is always available.
$effect(() => {
    if (!$idaa_slct.archive_content_id) return;

    const form_changed =
        JSON.stringify(archive_content_form) !== JSON.stringify(orig_archive_content_form);
    const has_changes =
        form_changed ||
        description_new_html !== orig_description_html ||
        notes_new_html !== orig_notes_html;

    if (!obj_changed && has_changes) {
        obj_changed = true;
    } else if (obj_changed && !has_changes) {
        obj_changed = false;
    }
});

$effect(() => {
    if (
        upload_complete_local &&
        hosted_file_id_li_local.length &&
        hosted_file_obj_li_local.length
    ) {
        handle_hosted_files_uploaded(
            hosted_file_id_li_local,
            hosted_file_obj_li_local
        );
        upload_complete_local = false;
        hosted_file_id_li_local = [];
        hosted_file_obj_li_local = [];
    }
});

let slct_hosted_file_id: any = $state(null);
let slct_hosted_file_obj: any = $state(null);
$effect(() => {
    if (slct_hosted_file_id && slct_hosted_file_obj) {
        console.log(
            `*** handle_hosted_file_selected() *** ${slct_hosted_file_id}`
        );
        // We need to update the archive_content_obj with the new file (for now just the first one).
        prom_api__archive_content_obj = archives_func
            .update_ae_obj__archive_content({
                api_cfg: $ae_api,
                archive_content_id: $idaa_slct.archive_content_id,
                data_kv: {
                    hosted_file_id: slct_hosted_file_id,
                    // file_path: hosted_file_obj_li[0].file_path,
                    filename: slct_hosted_file_obj.filename,
                    file_extension: slct_hosted_file_obj.extension,
                    archive_content_type: 'hosted_file'
                },
                log_lvl: log_lvl
            })
            .then(function (archive_content_obj_update_result) {
                // $idaa_slct.archive_content_obj = $lq__archive_content_obj;
                $idaa_slct.archive_content_obj =
                    archive_content_obj_update_result;
                $idaa_slct.archive_content_obj.upload_complete = false;
                if (
                    !Array.isArray(
                        $idaa_slct.archive_content_obj.hosted_file_id_li
                    )
                ) {
                    $idaa_slct.archive_content_obj.hosted_file_id_li = [];
                }
                if (
                    !Array.isArray(
                        $idaa_slct.archive_content_obj.hosted_file_obj_li
                    )
                ) {
                    $idaa_slct.archive_content_obj.hosted_file_obj_li = [];
                }

                // Sync form and snapshot so selecting an existing file doesn't mark form as dirty.
                archive_content_form.filename = archive_content_obj_update_result?.filename ?? '';
                archive_content_form.file_extension = archive_content_obj_update_result?.file_extension ?? '';
                archive_content_form.archive_content_type = 'hosted_file';
                orig_archive_content_form = JSON.parse(JSON.stringify(archive_content_form));
            })
            .catch(function (error: any) {
                console.log('Something went wrong.');
                console.log(error);
                return false;
            });

        slct_hosted_file_id = null;
        slct_hosted_file_obj = null;
    }
});
</script>

<section
    class="
        svelte_component ae_section ae_edit archive_content_obj edit__archive_content_obj
        preset-filled-surface-50-950 preset-outlined-warning-400-600
        space-y-2
        rounded-md p-2
        "
    class:ae_create={!$idaa_slct.archive_content_id}>
    <!-- bind:clientHeight={ae_iframe_height} -->

    <form onsubmit={prevent_default(handle_submit_form)} class="space-y-1">
        <!-- <h3>Archive Content</h3> -->

        <div
            class="ae_section archive_content__general space-y-2 rounded border border-gray-200 p-2">
            <div>
                <label for="name" class="w-full">
                    <span class="text-sm font-semibold"> Name of Content </span>
                    <input
                        type="text"
                        id="name"
                        name="name"
                        required
                        max="200"
                        bind:value={archive_content_form.name}
                        autocomplete="off"
                        class="
                    input preset-tonal-surface
                    hover:preset-filled-surface-100-900 form-control
                    w-full
                    "
                        placeholder="Content name" />
                </label>

                <label for="description" class="ae_label w-full">
                    <span class="legend text-sm font-semibold">
                        Description
                    </span>
                    <AE_Comp_Editor_TipTap
                        bind:content={description_new_html}
                        class_li="preset-tonal-surface hover:preset-filled-surface-100-900"
                        placeholder="Your content description here..." />
                </label>
            </div>

            <label for="archive_content_type"
                >Type
                <select
                    id="archive_content_type"
                    name="archive_content_type"
                    bind:value={archive_content_form.archive_content_type}
                    class="select w-52">
                    <option value="">-- None --</option>
                    <option value="hosted_file">Hosted File in Æ</option>
                    <option value="html">Hosted HTML in Æ</option>
                    <option value="json">Hosted JSON in Æ</option>
                    <option value="url">External URL</option>
                    <option value="other">Other</option>
                </select>
            </label>
        </div>

        {#if $idaa_slct.archive_content_id}
            <div
                class="ae_section archive_content__hosted_file space-y-2 rounded border border-gray-200 p-2"
                class:hidden={$idaa_slct.archive_content_obj
                    .archive_content_type !== 'hosted_file' &&
                    !$idaa_slct.archive_content_id}>
                <h3 class="h3">Upload/Manage Hosted File</h3>

                {#if !$idaa_slct.archive_content_obj?.hosted_file_id}
                    No file uploaded yet.

                    {#if $ae_loc.trusted_access}
                        <button
                            type="button"
                            class="btn btn-sm preset-tonal-warning border-warning-500 hover:preset-filled-warning-500 float-right border"
                            title="Toggle between Upload and Select from Hosted Files"
                            onclick={() => {
                                if (
                                    $ae_sess.files.add_to_use_files_method ==
                                    'upload'
                                ) {
                                    $ae_sess.files.add_to_use_files_method =
                                        'select';
                                } else {
                                    $ae_sess.files.add_to_use_files_method =
                                        'upload';
                                }
                            }}>
                            <span class="fas fa-exchange-alt m-1"></span>
                            {#if $ae_sess.files.add_to_use_files_method ==
                                'upload'}
                                Switch to Select
                            {:else}
                                Switch to Upload
                            {/if}
                        </button>

                        <div
                            class:hidden={$ae_sess.files
                                .add_to_use_files_method != 'upload'}
                            class="upload">
                            <Comp_hosted_files_upload
                                class_li="border border-gray-300 rounded-md p-2 bg-gray-100 hover:bg-gray-200"
                                link_to_type="archive_content"
                                link_to_id={$idaa_slct.archive_content_obj
                                    .archive_content_id}
                                multiple={false}
                                bind:hosted_file_id_li={hosted_file_id_li_local}
                                bind:hosted_file_obj_li={hosted_file_obj_li_local}
                                bind:upload_complete={upload_complete_local}
                                log_lvl={1}>
                                {#snippet label()}
                                    <div
                                        class="flex flex-col items-center gap-2 py-2">
                                        <!-- <div
                                            class="bg-primary-500/10 text-primary-500 rounded-full p-3">
                                            <span class="fas fa-upload fa-lg"
                                            ></span>
                                        </div> -->
                                        <div class="text-center">
                                            <p
                                                class="text-primary-500 font-bold">
                                                <Lucide.Upload size="1.25em" class="inline-block mr-1" />
                                                Upload archive files
                                            </p>
                                            <p class="text-xs opacity-60">
                                                Recommended: pptx, key, pdf,
                                                mp3, mp4, docx
                                            </p>
                                        </div>
                                    </div>
                                {/snippet}
                            </Comp_hosted_files_upload>
                        </div>

                        <div
                            class:hidden={$ae_sess.files
                                .add_to_use_files_method != 'select'}
                            class="">
                            <Element_manage_hosted_file_li_wrap
                                link_to_type="account"
                                link_to_id={$ae_loc?.account_id}
                                allow_basic={true}
                                allow_moderator={true}
                                class_li=""
                                bind:slct_hosted_file_kv
                                bind:slct_hosted_file_id
                                bind:slct_hosted_file_obj />
                        </div>
                    {/if}
                {:else}
                    <button
                        type="button"
                        onclick={() => {
                            if (
                                confirm(
                                    'Are you sure you want to remove the file?'
                                )
                            ) {
                                // First - Attempt to delete the hosted file
                                prom_api__archive_content_obj__hosted_file =
                                    core_func
                                        .delete_ae_obj_id__hosted_file({
                                            api_cfg: $ae_api,
                                            hosted_file_id:
                                                $idaa_slct.archive_content_obj
                                                    .hosted_file_id,
                                            link_to_type: 'archive_content',
                                            link_to_id:
                                                $idaa_slct.archive_content_id,
                                            rm_orphan: true,
                                            fake_delete: false,
                                            log_lvl: log_lvl
                                        })
                                        .then(function () {
                                            // Second - If deleted, then update the archive_content_obj
                                            console.log(
                                                `File removed. Now update the archive_content_obj`
                                            );
                                            prom_api__archive_content_obj =
                                                archives_func
                                                    .update_ae_obj__archive_content(
                                                        {
                                                            api_cfg: $ae_api,
                                                            archive_content_id:
                                                                $idaa_slct.archive_content_id,
                                                            data_kv: {
                                                                hosted_file_id:
                                                                    null,
                                                                file_path: null,
                                                                filename: null,
                                                                file_extension:
                                                                    null,
                                                                archive_content_type:
                                                                    null
                                                            },
                                                            log_lvl: log_lvl
                                                        }
                                                    )
                                                    .then(function () {
                                                            // We need to do all of this since the DB object has changed and the SLCT object does automatically update (yet...??? Svelte 5?).
                                                            // $idaa_slct.archive_content_obj = $lq__archive_content_obj;
                                                        }
                                                    )
                                                    .catch(function (
                                                        error: any
                                                    ) {
                                                        console.log(
                                                            'Something went wrong.'
                                                        );
                                                        console.log(error);
                                                        return false;
                                                    });
                                        })
                                        .catch(function (error: any) {
                                            console.log(
                                                'Something went wrong.'
                                            );
                                            console.log(error);
                                            return false;
                                        })
                                        .finally(() => {
                                            // We need to do all of this since the DB object has changed and the SLCT object does automatically update (yet...??? Svelte 5?).
                                            $idaa_slct.archive_content_obj.hosted_file_id =
                                                null;
                                            $idaa_slct.archive_content_obj.file_path =
                                                null;
                                            $idaa_slct.archive_content_obj.filename =
                                                null;
                                            $idaa_slct.archive_content_obj.file_extension =
                                                null;

                                            $idaa_slct.archive_content_obj.upload_complete = false;
                                            $idaa_slct.archive_content_obj.hosted_file_id_li =
                                                [];
                                            $idaa_slct.archive_content_obj.hosted_file_obj_li =
                                                [];

                                            // Sync form snapshot after file removal
                                            archive_content_form.filename = '';
                                            archive_content_form.file_extension = '';
                                            orig_archive_content_form = JSON.parse(JSON.stringify(archive_content_form));
                                        });
                            }
                        }}
                        class="novi_btn btn btn-sm preset-tonal-error float-right">
                        {#await prom_api__archive_content_obj__hosted_file}
                            <span class="fas fa-spinner fa-spin m-1"></span>
                        {:then}
                            <span class="fas fa-trash-alt m-1"></span>
                            Remove File
                        {/await}
                    </button>

                    <label for="filename"
                        >Filename
                        <input
                            type="text"
                            id="filename"
                            name="filename"
                            bind:value={archive_content_form.filename}
                            class="input w-full" />
                    </label>

                    <label for="file_extension"
                        >File Extension
                        {#if !$ae_loc.administrator_access}
                            <span class="fas fa-lock" title="Field is locked"
                            ></span>
                        {:else}
                            <span
                                class="fas fa-unlock"
                                title="Field is unlocked"></span>
                        {/if}
                        <input
                            type="text"
                            id="file_extension"
                            name="file_extension"
                            bind:value={archive_content_form.file_extension}
                            readonly={!$ae_loc.administrator_access}
                            class="input w-24" />
                    </label>
                {/if}
            </div>
        {:else}
            <div
                class="ae_section archive_content__hosted_file space-y-2 rounded border border-gray-200 p-2">
                <span class="fas fa-exclamation-triangle text-red-500"></span>
                Save the form first before uploading a file.
            </div>
        {/if}

        <div
            class="ae_section archive_content__original space-y-2 rounded border border-gray-200 p-2">
            <h3 class="h3">Original</h3>

            <label for="original_datetime"
                >Original Date/Time
                <input
                    type="date"
                    id="original_datetime_date"
                    name="original_datetime_date"
                    bind:value={archive_content_form.original_datetime_date}
                    placeholder="YYYY-MM-DD"
                    class="input w-48" />
                <input
                    type="time"
                    id="original_datetime_time"
                    name="original_datetime_time"
                    bind:value={archive_content_form.original_datetime_time}
                    placeholder="HH:MM AM/PM"
                    class="input w-48" />
            </label>

            <fieldset class="flex_row flex_gap_md flex_justify_around">
                <label for="original_timezone"
                    >Original Timezone
                    {#if ($lq__lu_time_zone ?? []).length}
                        <select
                            id="original_timezone"
                            name="original_timezone"
                            bind:value={archive_content_form.original_timezone}
                            class="select w-56"
                            title="Select the original timezone">
                            <option value="">-- None --</option>
                            {#each $lq__lu_time_zone ?? [] as lu_timezone (lu_timezone.name)}
                                <option value={lu_timezone.name}>
                                    {lu_timezone.name}
                                </option>
                            {/each}
                        </select>
                    {:else}
                        <input
                            type="text"
                            name="timezone"
                            bind:value={archive_content_form.original_timezone}
                            class="input w-56" />
                    {/if}
                </label>
            </fieldset>

            <label for="original_location"
                >Original Location
                <input
                    type="text"
                    id="original_location"
                    name="original_location"
                    bind:value={archive_content_form.original_location}
                    class="input w-96" />
            </label>
        </div>

        {#if $ae_loc.trusted_access}
            <!-- BEGIN: section archive_content__admin_options -->
            <div
                class="bg-surface-100-900 border-error-400 space-y-3 rounded-md border p-3">
                <button
                    type="button"
                    class="flex w-full flex-row items-center gap-2 text-left"
                    onclick={() => {
                        $idaa_loc.archives.show__admin_options =
                            !$idaa_loc.archives.show__admin_options;
                    }}>
                    <span
                        class="fas fa-{$idaa_loc.archives.show__admin_options
                            ? 'caret-down'
                            : 'caret-right'} text-xs opacity-60"></span>
                    <h3
                        class="text-surface-600-400 flex w-full items-center gap-2 text-lg font-semibold">
                        <span class="fas fa-cogs"></span>
                        Admin Options
                    </h3>
                </button>

                <div
                    class="space-y-3"
                    class:hidden={!$idaa_loc.archives.show__admin_options}>
                    {#if $ae_loc.edit_mode}
                        <label class="text-sm font-semibold" for="code">
                            Code
                            <input
                                type="text"
                                id="code"
                                name="code"
                                bind:value={archive_content_form.code}
                                maxlength="100"
                                class="input preset-tonal-surface form-control w-48"
                                placeholder="short-code" />
                        </label>
                    {/if}
                    <span
                        class="flex w-full flex-col flex-wrap items-center justify-center gap-2 md:flex-row md:justify-stretch">
                        <span
                            class="flex grow flex-row flex-wrap items-center justify-evenly gap-1">
                            <fieldset
                                class="form-check flex flex-row items-center justify-center gap-1">
                                <legend
                                    class="legend form-check-label text-sm font-semibold"
                                    >Hide</legend>
                                <div>
                                    <input
                                        type="radio"
                                        id="hide_yes"
                                        name="hide"
                                        value={true}
                                        bind:group={archive_content_form.hide}
                                        class="radio form-check-input" />
                                    <label for="hide_yes">Yes</label>
                                </div>
                                <div>
                                    <input
                                        type="radio"
                                        id="hide_no"
                                        name="hide"
                                        value={false}
                                        bind:group={archive_content_form.hide}
                                        class="radio form-check-input" />
                                    <label for="hide_no">No</label>
                                </div>
                            </fieldset>

                            <fieldset
                                class="form-check flex flex-row items-center justify-center gap-1">
                                <legend
                                    class="legend form-check-label text-sm font-semibold"
                                    >Priority</legend>
                                <div>
                                    <input
                                        type="radio"
                                        id="priority_yes"
                                        name="priority"
                                        value={true}
                                        bind:group={archive_content_form.priority}
                                        class="radio form-check-input" />
                                    <label for="priority_yes">Yes</label>
                                </div>
                                <div>
                                    <input
                                        type="radio"
                                        id="priority_no"
                                        name="priority"
                                        value={false}
                                        bind:group={archive_content_form.priority}
                                        class="radio form-check-input" />
                                    <label for="priority_no">No</label>
                                </div>
                            </fieldset>
                        </span>

                        <span
                            class="
                    col-sm-1
                    flex grow flex-row flex-wrap items-center justify-evenly
                    gap-1
                    ">
                            <label
                                class="legend input-group text-sm font-semibold"
                                >Sort <input
                                    type="number"
                                    name="sort"
                                    bind:value={archive_content_form.sort}
                                    class="input preset-tonal-surface form-control w-24" /></label>

                            <label
                                class="legend input-group text-sm font-semibold"
                                >Group <input
                                    type="text"
                                    name="group"
                                    bind:value={archive_content_form.group}
                                    max="100"
                                    class="input preset-tonal-surface form-control w-40" /></label>
                        </span>

                        {#if $ae_loc.administrator_access}
                            <span
                                class="flex grow flex-row flex-wrap items-center justify-evenly gap-1">
                                <fieldset
                                    class="align-center form-check flex flex-row items-center gap-1">
                                    <legend
                                        class="legend form-check-label text-sm font-semibold"
                                        >Enable</legend>
                                    <div>
                                        <input
                                            type="radio"
                                            id="enable_yes"
                                            name="enable"
                                            value={true}
                                            bind:group={archive_content_form.enable}
                                            class="radio form-check-input" />
                                        <label for="enable_yes">Yes</label>
                                    </div>
                                    <div>
                                        <input
                                            type="radio"
                                            id="enable_no"
                                            name="enable"
                                            value={false}
                                            bind:group={archive_content_form.enable}
                                            class="radio form-check-input" />
                                        <label for="enable_no">No</label>
                                    </div>
                                </fieldset>
                            </span>
                        {:else}
                            <input
                                type="hidden"
                                name="enable"
                                value={archive_content_form.enable} />
                        {/if}
                    </span>

                    {#if $ae_loc.trusted_access}
                        <label for="notes" class="w-full">
                            <span
                                class="legend text-surface-600-400 text-sm font-semibold"
                                >Internal Staff Notes</span>
                            <AE_Comp_Editor_TipTap
                                bind:content={notes_new_html}
                                class_li="preset-tonal-surface preset-filled-surface-100-900"
                                placeholder="Internal notes for staff only. Not shown to the public." />
                        </label>
                    {/if}

                    <div class="text-sm text-gray-600 dark:text-gray-400">
                        {$lq__archive_content_obj?.updated_on
                            ? `DB Updated on: ${$lq__archive_content_obj?.updated_on}`
                            : ''}
                        {$idaa_slct.archive_content_obj?.updated_on
                            ? `SLCT Updated on: ${$idaa_slct.archive_content_obj?.updated_on}`
                            : ''}
                    </div>
                </div>
            </div>
            <!-- END: section archive_content__admin_options -->
        {/if}

        <div
            class="
            ae_section ae_options ae_row ae_actions post__options post__actions
            d-flex align-items-center justify-content-between flex w-full flex-row
            items-center justify-between gap-1
        ">
            {#if $idaa_slct.archive_content_id}
                <button
                    type="submit"
                    disabled={disable_submit_btn || !obj_changed}
                    class="
                    novi_btn
                    btn btn-md preset-tonal-primary preset-outlined-primary-800-200 hover:preset-filled-primary-200-800
                    transition
                    ">
                    {#await prom_api__archive_content_obj}
                        <span class="fas fa-spinner fa-spin m-1"></span> Saving
                    {:then}
                        <span class="fas fa-save m-1"></span> Save Changes
                    {/await}
                </button>
            {:else}
                <button
                    type="submit"
                    disabled={disable_submit_btn}
                    class="
                    novi_btn
                    btn btn-md preset-tonal-warning hover:preset-filled-warning-200-800
                    transition
                    ">
                    {#await prom_api__archive_content_obj}
                        <span class="fas fa-spinner fa-spin m-1"></span> Saving
                    {:then}
                        <span class="fas fa-save m-1"></span> Save New Content
                    {/await}
                </button>
            {/if}

            {#if $idaa_slct.archive_content_id && !$idaa_slct.archive_content_obj?.hosted_file_id}
                <button
                    type="button"
                    onclick={() => {
                        if (
                            !confirm(
                                'Are you sure you want to remove this archive content?'
                            )
                        ) {
                            return false;
                        }

                        let method = 'disable';

                        prom_api__archive_content_obj =
                            archives_func.delete_ae_obj_id__archive_content({
                                api_cfg: $ae_api,
                                archive_content_id:
                                    $idaa_slct.archive_content_id,
                                method: method as any,
                                log_lvl: log_lvl
                            });

                        $idaa_slct.archive_content_id = null;
                        $idaa_slct.archive_content_obj = {};
                        $idaa_sess.archives.show__modal_edit__archive_content_id = false;
                        $idaa_sess.archives.show__modal_view__archive_content_id = false;
                    }}
                    class="
                    novi_btn
                    btn btn-sm
                    preset-filled-warning-200-800 hover:preset-filled-error-200-800
                    transition
                    "
                    title="Disable this archive content">
                    <span class="fas fa-minus m-1"></span>
                    Remove
                    {#if $ae_loc.administrator_access}
                        (Disable)
                    {/if}
                </button>

                {#if $ae_loc.administrator_access && $ae_loc.edit_mode}
                    <button
                        type="button"
                        onclick={() => {
                            if (
                                !confirm(
                                    'Are you sure you want to delete this archive content?'
                                )
                            ) {
                                return false;
                            }

                            let method = 'delete';

                            prom_api__archive_content_obj =
                                archives_func.delete_ae_obj_id__archive_content(
                                    {
                                        api_cfg: $ae_api,
                                        archive_content_id:
                                            $idaa_slct.archive_content_id,
                                        method: method as any,
                                        log_lvl: log_lvl
                                    }
                                );

                            $idaa_slct.archive_content_id = null;
                            $idaa_slct.archive_content_obj = {};
                            $idaa_sess.archives.show__modal_edit__archive_content_id = false;
                            $idaa_sess.archives.show__modal_view__archive_content_id = false;
                        }}
                        class="
                    novi_btn
                    btn btn-sm
                    preset-filled-warning-200-800 hover:preset-filled-error-200-800
                    transition
                    "
                        title="Delete this archive content">
                        <span class="fas fa-minus m-1"></span>
                        Delete
                    </button>
                {/if}
            {:else if $idaa_slct.archive_content_obj.hosted_file_id}
                {#if $ae_loc.administrator_access}
                    Can not delete. Remove hosted file first.
                {/if}
            {/if}
        </div>
    </form>
</section>
<!-- END: section ae_edit archive_content_obj -->
