<script lang="ts">
interface Props {
    log_lvl?: number;
    obj_changed: boolean;
}

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

// *** Import Svelte specific
// import { onDestroy, onMount } from 'svelte';
import { fade } from 'svelte/transition';
import { browser } from '$app/environment';
import { goto } from '$app/navigation';

// *** Import other supporting libraries

// *** Import Aether specific 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 { api } from '$lib/ae_api/api';
import { ae_loc, ae_api } from '$lib/stores/ae_stores';
import { idaa_loc, idaa_sess, idaa_slct } from '$lib/stores/ae_idaa_stores';
import { posts_func } from '$lib/ae_posts/ae_posts_functions';
import {
    build_bb_post_payload,
    build_bb_post_staff_notification_email,
    create_bb_post_form,
    type BbPostIdentityDefaults,
    type BbPostObjectLike
} from '$lib/ae_idaa/ae_idaa__bb_post_helpers';
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 AE_Comp_Hosted_Files_Download_Button from '$lib/elements/ae_comp__hosted_files_download_button.svelte';

interface BbHostedFileObjLike {
    hosted_file_id?: string | null;
    id?: string | null;
    filename?: string | null;
    extension?: string | null;
    file_extension?: string | null;
    [key: string]: unknown;
}

// let obj_changed = $state(false);
// let orig_post_obj: any = $state(null);
// let orig_post_obj: any = $state({ ...$idaa_slct.post_obj }); // Create a copy of the post object
if (!$idaa_slct.post_obj) {
    $idaa_slct.post_obj = {};
}

const initial_post_obj: BbPostObjectLike = $idaa_slct.post_obj ?? {};

function get_current_identity_defaults(): BbPostIdentityDefaults {
    const identity_defaults: BbPostIdentityDefaults = {
        external_person_id: $idaa_loc.novi_uuid ?? null,
        full_name: $idaa_loc.novi_full_name ?? null,
        email: $idaa_loc.novi_email ?? null
    };

    if (!identity_defaults.external_person_id && typeof localStorage !== 'undefined') {
        try {
            const ls_val = localStorage.getItem('ae_idaa_loc');
            if (ls_val) {
                const ls_json = JSON.parse(ls_val);
                identity_defaults.external_person_id = ls_json.novi_uuid ?? null;
                identity_defaults.full_name =
                    identity_defaults.full_name || ls_json.novi_full_name || null;
                identity_defaults.email =
                    identity_defaults.email || ls_json.novi_email || null;
            }
        } catch {
            /* ignore */
        }
    }

    return identity_defaults;
}

const initial_identity_defaults = get_current_identity_defaults();

let post_form = $state(create_bb_post_form(initial_post_obj, initial_identity_defaults));
let orig_post_form = $state(create_bb_post_form(initial_post_obj, initial_identity_defaults));
let force_saveable_new_post = $state(false);

// Create a copy of the post object
let orig_post_obj: BbPostObjectLike = { ...initial_post_obj };
if (browser) {
    // console.log(`$lq__post_obj = `, $lq__post_obj);
    console.log(`$idaa_slct.post_obj = `, $idaa_slct.post_obj);
    // orig_post_obj = { ...$idaa_slct.post_obj }; // Create a copy of the post object
    console.log(`orig_post_obj = `, orig_post_obj);

    // JSON.stringify($idaa_slct.post_obj) !== JSON.stringify(orig_post_obj)
}

if ($idaa_loc.bb.edit__post_obj) {
    obj_changed = true; // This is an odd workaround to make new posts saveable.
    force_saveable_new_post = true;
    $idaa_sess.bb.edit__post_obj = $idaa_loc.bb.edit__post_obj;
    $idaa_loc.bb.edit__post_obj = false;
}

let ae_promises: key_val = $state({});
let prom_api__post_obj: Promise<unknown> | undefined = $state();
// let prom_api__post_obj__hosted_file: any;

let content_new_html = $state(initial_post_obj?.content ?? '');
let notes_new_html = $state(initial_post_obj?.notes ?? '');
let hosted_file_id_li = $state<string[]>([]); // Array of hosted file IDs
let hosted_file_obj_li = $state<BbHostedFileObjLike[]>([]); // Array of hosted file objects
let upload_complete = $state(false);
let disable_submit_btn = $state(false);

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

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

    const form = event.currentTarget;
    if (!(form instanceof HTMLFormElement)) {
        return false;
    }

    disable_submit_btn = true;

    const form_data = new FormData(form);
    if (log_lvl) {
        console.log(form_data);
    }

    const post_di = ae_util.extract_prefixed_form_data({
        prefix: null,
        form_data,
        trim_values: true,
        bool_tf_str: true,
        log_lvl
    });

    const is_new_post = !$idaa_slct.post_id;
    const post_do = build_bb_post_payload({
        post_di,
        content_html: content_new_html,
        notes_html: notes_new_html,
        original_post_obj: orig_post_obj,
        identity_defaults: get_current_identity_defaults(),
        is_new_post,
        account_id: $ae_loc.account_id
    });

    if (log_lvl) {
        console.log(post_do);
    }

    if (is_new_post) {
        prom_api__post_obj = posts_func
            .create_ae_obj__post({
                api_cfg: $ae_api,
                account_id: $ae_loc.account_id,
                data_kv: post_do,
                log_lvl
            })
            .then(function (post_obj_create_result) {
                if (!post_obj_create_result) {
                    console.log('The result was null or false.');
                    return false;
                }

                if (log_lvl) {
                    console.log('post_obj_create_result:', post_obj_create_result);
                }

                $idaa_slct.post_id = post_obj_create_result.post_id;
                $idaa_slct.post_obj = post_obj_create_result;

                if ($ae_loc.site_cfg_json?.bb_send_staff_new_email) {
                    send_staff_notification_email(post_obj_create_result);
                }

                mark_post_form_saved(post_obj_create_result);

                if (post_obj_create_result.post_id) {
                    goto(`/idaa/bb/${post_obj_create_result.post_id}`);
                }

                return post_obj_create_result;
            })
            .catch(function (error: unknown) {
                console.log('Something went wrong.');
                console.log(error);
                return false;
            })
            .finally(() => {
                disable_submit_btn = false;
                $idaa_sess.bb.edit__post_obj = false;
            });

        return prom_api__post_obj;
    }

    prom_api__post_obj = posts_func
        .update_ae_obj__post({
            api_cfg: $ae_api,
            post_id: $idaa_slct.post_id,
            data_kv: post_do,
            log_lvl
        })
        .then(function (post_obj_update_result) {
            if (!post_obj_update_result) {
                console.log('The result was null or false.');
                return false;
            }

            if (log_lvl) {
                console.log('post_obj_update_result:', post_obj_update_result);
            }

            $idaa_slct.post_obj = post_obj_update_result;

            if ($ae_loc.site_cfg_json?.bb_send_staff_update_email) {
                send_staff_notification_email(post_obj_update_result);
            }

            mark_post_form_saved(post_obj_update_result);

            return post_obj_update_result;
        })
        .catch(function (error: unknown) {
            console.log('Something went wrong.');
            console.log(error);
            return false;
        })
        .finally(() => {
            disable_submit_btn = false;
            $idaa_sess.bb.edit__post_obj = false;
        });

    console.log(`prom_api__post_obj = `, prom_api__post_obj);

    return prom_api__post_obj;
}

// Updated 2024-11-15
async function handle_delete_post_obj({
    post_id,
    method = 'disable'
}: {
    post_id: string;
    method?: 'delete' | 'soft_delete' | 'disable' | 'hide';
}) {
    if (log_lvl) {
        console.log('*** handle_delete_post_obj() ***');
    }

    prom_api__post_obj = posts_func
        .delete_ae_obj_id__post({
            api_cfg: $ae_api,
            post_id: post_id,
            method,
            log_lvl: log_lvl
        })
        .then(function () {
            // $idaa_sess.bb.show__modal_view__post_id = false;
            $idaa_sess.bb.edit__post_obj = false;
            // $idaa_sess.bb.show__inline_edit__post_comment_id = false;
        })
        .catch(function (error: unknown) {
            console.log(
                'The result was null or false when trying to delete.',
                error
            );
        })
        .finally(() => {
            // $idaa_sess.recovery_meetings.show__modal_edit = false;
            $idaa_slct.post_id = null;
            $idaa_slct.post_obj = null;
            $idaa_slct.post_comment_id = null;
            $idaa_slct.post_comment_obj = null;
            goto('/idaa/bb'); // Redirect to the BB page
        });

    return prom_api__post_obj;
}

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

    // NOTE: No longer directly updating the $idaa_slct.post_obj.hosted_file_obj_li. This will be updated when the PATCH API for Post update finishes.
    // We need to add the record to the $idaa_slct.post_obj.hosted_file_obj_li and then update the post_obj.linked_li_json with the new value.
    // let new_linked_li_json = [...$idaa_slct.post_obj.linked_li_json ?? {}]; // Initialize with existing linked_li_json or an empty array
    let new_linked_li_json = $idaa_slct.post_obj.linked_li_json ?? []; // Initialize with existing linked_li_json or an empty array
    if (!$idaa_slct.post_obj.linked_li_json) {
        // $idaa_slct.post_obj.linked_li_json = hosted_file_obj_li;
        new_linked_li_json = hosted_file_obj_li;
    } else {
        $idaa_slct.post_obj.linked_li_json.push(...hosted_file_obj_li);
        new_linked_li_json = [...new_linked_li_json];
        // new_linked_li_json.push(...hosted_file_obj_li);
        // new_linked_li_json = [...new_linked_li_json];
    }

    prom_api__post_obj = posts_func
        .update_ae_obj__post({
            api_cfg: $ae_api,
            post_id: $idaa_slct.post_id,
            data_kv: {
                // linked_li_json: JSON.stringify($idaa_slct.post_obj.linked_li_json),
                linked_li_json: JSON.stringify(new_linked_li_json)
            },
            log_lvl: log_lvl
        })
        .then(function () {
            // $idaa_slct.post_obj = $lq__post_obj;
            $idaa_slct.post_obj.linked_li_json = new_linked_li_json;
        })
        .catch(function (error: unknown) {
            console.log('Something went wrong.');
            console.log(error);
            return false;
        });
}

// Updated 2026-02-16
// The post_do (Post Data Out) should be the new form data
function send_staff_notification_email(post_do: key_val) {
    if (log_lvl) {
        console.log(
            `*** send_staff_notification_email() *** Post ID: ${post_do.post_id}`
        );
    }

    const email_args = build_bb_post_staff_notification_email({
        post_do,
        url_origin: $ae_loc.url_origin,
        site_cfg_json: $ae_loc.site_cfg_json
    });

    api.send_email({
        api_cfg: $ae_api,
        ...email_args
    });
}

function mark_post_form_saved(saved_post_obj: BbPostObjectLike) {
    orig_post_obj = {
        ...saved_post_obj,
        content: content_new_html,
        notes: notes_new_html
    };
    orig_post_form = JSON.parse(JSON.stringify(post_form));
    force_saveable_new_post = false;
    obj_changed = false;
}

$effect(() => {
    // Initialization Layer
    const current_post_id =
        $idaa_slct.post_obj?.post_id ?? $idaa_slct.post_obj?.id ?? null;
    const original_post_id =
        orig_post_obj?.post_id ?? orig_post_obj?.id ?? null;

    if (current_post_id && current_post_id !== original_post_id) {
        orig_post_obj = { ...$idaa_slct.post_obj };
        post_form = create_bb_post_form(
            $idaa_slct.post_obj,
            get_current_identity_defaults()
        );
        orig_post_form = create_bb_post_form(
            $idaa_slct.post_obj,
            get_current_identity_defaults()
        );
        content_new_html = $idaa_slct.post_obj?.content ?? '';
        notes_new_html = $idaa_slct.post_obj?.notes ?? '';
    }

    if (force_saveable_new_post) {
        obj_changed = true;
    } else if (
        !obj_changed &&
        orig_post_obj?.id &&
        (JSON.stringify(post_form) !== JSON.stringify(orig_post_form) ||
            content_new_html !== (orig_post_obj.content ?? '') ||
            notes_new_html !== (orig_post_obj.notes ?? ''))
    ) {
        // console.log('Post object has changed from original.', $inspect(orig_post_obj));
        if (log_lvl) {
            console.log(
                'Post object has changed from original.',
                orig_post_obj
            );
            console.log('Post object has changed.', $idaa_slct.post_obj);
        }
        obj_changed = true;
    } else if (
        obj_changed &&
        orig_post_obj?.id &&
        JSON.stringify(post_form) === JSON.stringify(orig_post_form) &&
        content_new_html === (orig_post_obj.content ?? '') &&
        notes_new_html === (orig_post_obj.notes ?? '')
    ) {
        obj_changed = false;
    }
});

$effect(() => {
    if (
        upload_complete &&
        hosted_file_id_li?.length &&
        hosted_file_obj_li?.length
    ) {
        handle_hosted_files_uploaded(hosted_file_id_li, hosted_file_obj_li);
        upload_complete = false; // Reset the upload complete flag
    }
});
</script>

<section
    class="
        svelte_component ae_section ae_edit post_obj edit__post_obj
        preset-filled-surface-50-950 preset-outlined-warning-400-600
        space-y-2
        rounded-md p-2
        "
    class:ae_create={!$idaa_slct.post_id}
    bind:clientHeight={$ae_loc.iframe_height_modal_body}>
    <form onsubmit={prevent_default(handle_submit_form)} class="space-y-1">
        {#await prom_api__post_obj}
            <div class="awaiting alert_msg_pulse" out:fade={{ duration: 2000 }}>
                Saving...
            </div>
        {:then}
            {#if prom_api__post_obj}
                <!-- <div class="awaiting" out:fade={{ duration: 2000 }}>Finished saving</div> -->
            {:else}
                <!-- <div class="awaiting" out:fade={{ duration: 2000 }}>Nothing here yet</div> -->
            {/if}
        {/await}

        <div class="text-center">
            <!-- BEGIN: section post__options -->
            <button
                type="button"
                onclick={() => {
                    if (obj_changed) {
                        if (
                            confirm(
                                'You have unsaved changes. Are you sure you want to cancel?'
                            )
                        ) {
                            $idaa_sess.bb.edit__post_obj = false;
                        }
                    } else {
                        $idaa_sess.bb.edit__post_obj = false;
                    }
                }}
                class="
                novi_btn
                btn btn-sm
                preset-filled-warning-200-800 hover:preset-filled-success-200-800
                transition
                "
                title="Cancel editing of post for {$idaa_slct.post_obj
                    .full_name} (ID: {$idaa_slct.post_obj.post_id}">
                <span class="fas fa-times m-1"></span>
                Cancel Edit
            </button>
        </div>
        <!-- END: section post__options -->

        <!-- <h3 class="h3">Post</h3> -->

        <input type="hidden" value={$idaa_slct.post_id} />

        <div
            class="ae_section post__general_information space-y-2 rounded border border-gray-200 p-2">
            <!-- BEGIN: section post__general_information -->

            <div>
                <label for="title" class="w-full">
                    <span class="text-surface-600-400 text-sm font-semibold">
                        Title of BB post:
                    </span>
                    <!-- svelte-ignore a11y_autofocus -->
                    <input
                        autofocus
                        type="text"
                        id="title"
                        name="title"
                        required
                        max="200"
                        bind:value={post_form.title}
                        autocomplete="off"
                        class="
                    input preset-tonal-surface
                    hover:preset-filled-surface-100-900 form-control
                    w-full
                    "
                        placeholder="Title of Post" />
                </label>
            </div>

            <label for="content" class="ae_label post__content w-full">
                <span class="legend text-surface-600-400 text-sm font-semibold">
                    Content (post body):
                </span>
                <!-- <textarea name="content" id="content" class="ae_value post__content tinymce_editor editor_basic textarea" rows="5" cols="70" bind:value={$idaa_slct.post_obj.content} ></textarea> -->

                <AE_Comp_Editor_TipTap
                    bind:content={content_new_html}
                    class_li="preset-tonal-surface hover:preset-filled-surface-100-900"
                    placeholder="Your post content here..." />
            </label>

            <div class="flex flex-col items-center justify-center gap-1">
                <button
                    type="button"
                    class="
                    novi_btn
                    btn btn-sm
                    "
                    class:preset-filled-success-200-800={$idaa_sess.bb
                        .show__inline_edit__file_upload}
                    class:preset-filled-tertiary-200-800={!$idaa_sess.bb
                        .show__inline_edit__file_upload}
                    onclick={() => {
                        $idaa_sess.bb.show__inline_edit__file_upload =
                            !$idaa_sess.bb.show__inline_edit__file_upload;
                    }}>
                    <span class="fas fa-upload m-1"></span>
                    {$idaa_sess.bb.show__inline_edit__file_upload
                        ? 'Hide'
                        : 'Show'} File Upload
                </button>

                <div
                    class:hidden={!$idaa_sess.bb
                        .show__inline_edit__file_upload}>
                    <div class="bg-warning-400 rounded p-2 text-sm">
                        <!-- This feature is currently only available to staff. -->
                        NOTE - This is intended for attaching something like a PDF
                        or image to a specific post. Images will be displayed in line.
                        PDFs will be shown with a download button.
                    </div>
                    {#if $ae_loc.authenticated_access}
                        <Comp_hosted_files_upload
                            accept="image/*, .docx, .pdf, .pptx, .key"
                            class_li="border border-gray-300 rounded-md p-2 bg-gray-100 hover:bg-gray-200"
                            link_to_type="post"
                            link_to_id={$idaa_slct.post_obj?.post_id}
                            bind:hosted_file_id_li
                            bind:hosted_file_obj_li
                            bind:upload_complete
                            {log_lvl}>
                            {#snippet label()}
                                <span>
                                    <div>
                                        <span class="fas fa-upload"></span>
                                        <strong class="bg-green-100 p-1"
                                            >Upload post files</strong>
                                    </div>
                                    <span
                                        class="text-surface-600-400 text-sm italic">
                                        <!-- <strong>Aether hosted files only</strong><br> -->
                                        Recommended: documents (PDF) and images (png,
                                        webp, jpg)
                                        <!-- , audio (mp3, m4a), and video (mp4, mkv) -->
                                        <!-- <br> -->
                                    </span>
                                </span>
                            {/snippet}
                        </Comp_hosted_files_upload>
                    {/if}
                </div>
            </div>

            {#if $idaa_slct.post_obj?.linked_li_json && $idaa_slct.post_obj.linked_li_json.length}
                <div
                    class="ae_section flex flex-row flex-wrap items-center justify-center gap-1">
                    <span class="fas fa-paperclip"></span>
                    <span class="text-surface-600-400 text-sm italic"
                        >Linked files:</span>
                    {#each $idaa_slct.post_obj.linked_li_json as linked_obj, index (linked_obj.hosted_file_id ?? index)}
                        <span
                            class="flex flex-col items-center gap-1 rounded-lg border bg-white/50 p-1">

                            {#if $ae_loc.authenticated_access}
                                {@const file_id =
                                    linked_obj?.hosted_file_id ||
                                    linked_obj?.id ||
                                    linked_obj?.hosted_file_id}
                                {#if file_id}
                                    {@const ext = (
                                        linked_obj.extension ||
                                        linked_obj.file_extension ||
                                        ae_util.guess_file_extension(
                                            linked_obj.filename
                                        ) ||
                                        ''
                                    ).toLowerCase()}
                                    {#if ['png', 'jpg', 'jpeg', 'gif', 'webp', 'svg'].includes(ext)}
                                        <div class="mb-1">
                                            <img
                                                src="{$ae_api.base_url}/v3/action/hosted_file/{file_id}/download?key={$ae_api.account_id}"
                                                alt={linked_obj.filename}
                                                class="border-surface-500/20 h-auto max-w-32 rounded border object-cover shadow-sm" />
                                        </div>
                                    {/if}

                                    <div
                                        class="flex flex-row items-center gap-1">
                                        <AE_Comp_Hosted_Files_Download_Button
                                            hosted_file_id={file_id}
                                            hosted_file_obj={linked_obj}
                                            color="tertiary"
                                            variant="tonal"
                                            classes="novi_btn btn-sm lg:btn-md min-w-48"
                                            max_filename={30} />

                                        <button
                                            type="button"
                                            disabled={!$ae_loc.trusted_access}
                                            onclick={async () => {
                                                if (
                                                    !confirm(
                                                        `Are you sure you want to delete this file?\n${linked_obj.filename} [${file_id}]`
                                                    )
                                                ) {
                                                    return false;
                                                }

                                                // First - Attempt to delete the hosted file
                                                ae_promises.delete__linked_obj =
                                                    await core_func
                                                        .delete_ae_obj_id__hosted_file(
                                                            {
                                                                api_cfg:
                                                                    $ae_api,
                                                                hosted_file_id:
                                                                    file_id,
                                                                link_to_type:
                                                                    'post',
                                                                link_to_id:
                                                                    $idaa_slct.post_id,
                                                                rm_orphan: true,
                                                                fake_delete: false,
                                                                log_lvl: log_lvl
                                                            }
                                                        )
                                                        .then(function () {
                                                                // Second - If deleted, then update the post_obj
                                                                console.log(
                                                                    `File removed. Now update the post_obj`
                                                                );

                                                                // We need to remove the record from the $idaa_slct.post_obj.hosted_file_obj_li and then update the post_obj.linked_li_json with the new value.
                                                                let delete_result_li =
                                                                    $idaa_slct.post_obj.linked_li_json.filter(
                                                                        function (
                                                                            hosted_file_obj: BbHostedFileObjLike
                                                                        ) {
                                                                            const current_id =
                                                                                hosted_file_obj?.hosted_file_id ||
                                                                                hosted_file_obj?.id ||
                                                                                hosted_file_obj?.hosted_file_id;
                                                                            console.log(
                                                                                `Comparing: ${current_id} vs ${file_id}`
                                                                            );
                                                                            return (
                                                                                current_id !==
                                                                                file_id
                                                                            );
                                                                        }
                                                                    );

                                                                $idaa_slct.post_obj.hosted_file_obj_li =
                                                                    delete_result_li;
                                                                $idaa_slct.post_obj.linked_li_json =
                                                                    delete_result_li;

                                                                prom_api__post_obj =
                                                                    posts_func
                                                                        .update_ae_obj__post(
                                                                            {
                                                                                api_cfg:
                                                                                    $ae_api,
                                                                                post_id:
                                                                                    $idaa_slct.post_id,
                                                                                data_kv:
                                                                                    {
                                                                                        linked_li_json:
                                                                                            JSON.stringify(
                                                                                                $idaa_slct
                                                                                                    .post_obj
                                                                                                    .linked_li_json
                                                                                            )
                                                                                    },
                                                                                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.post_obj = $lq__post_obj;
                                                                            }
                                                                        )
                                                                        .catch(function (
                                                                            error: unknown
                                                                        ) {
                                                                                console.log(
                                                                                    'Something went wrong.'
                                                                                );
                                                                                console.log(
                                                                                    error
                                                                                );
                                                                                return false;
                                                                            }
                                                                        );
                                                            }
                                                        )
                                                        .catch(function (
                                                            error: unknown
                                                        ) {
                                                            console.log(
                                                                'Something went wrong.'
                                                            );
                                                            console.log(error);
                                                            return false;
                                                        })
                                                        .finally(() => {});
                                            }}
                                            class="
                                        novi_btn
                                        btn btn-sm
                                        preset-tonal-warning preset-outlined-warning-100-900 hover:preset-filled-warning-400-600
                                        transition
                                        "
                                            title="Delete this file">
                                            <span class="fas fa-trash-alt mx-1"
                                            ></span>
                                            <!-- <span class="fas fa-minus mx-1"></span> -->
                                            Delete
                                        </button>
                                    </div>
                                {/if}
                            {/if}
                        </span>
                    {/each}
                </div>
            {/if}

            <div>
                <label class="form-group w-100">
                    <span class="text-surface-600-400 text-sm font-semibold">
                        BB post topic:
                    </span>
                    <select
                        name="topic_id"
                        class="
                        select preset-tonal-surface hover:preset-filled-surface-100-900
                        form-control col-sm-12
                        w-96 px-1
                        "
                        bind:value={post_form.topic_id}>
                        <option value="">-- None --</option>
                        <option value={16}
                            >Licensing/ monitoring/ credentialing issues</option>
                        <option value={17}>Return to practice</option>
                        <option value={18}
                            >Contacts/ sponsorship in my area</option>
                        <option value={19}>Professional positions</option>
                        <option value={25}>Speaker Bureau</option>
                        <option value={21} disabled={!$ae_loc.trusted_access}>
                            Announcement
                        </option>
                    </select>
                </label>
            </div>

            <h3 class="h3 text-surface-800-200 text-base font-bold">
                Poster's Information
            </h3>
            <fieldset class="form-group">
                <legend
                    class="legend text-surface-600-400 text-sm font-semibold"
                    >Post as "Anonymous"?</legend>
                <div
                    class="preset-tonal-surface hover:preset-filled-surface-100-900 flex flex-row gap-2">
                    <input
                        type="radio"
                        id="anonymous_no"
                        name="anonymous"
                        value={false}
                        bind:group={post_form.anonymous}
                        class="radio form-check-input" />
                    <label for="anonymous_no" class="form-check-label"
                        ><strong>No</strong>, include my name and email address</label>
                </div>
                <div
                    class="preset-tonal-surface hover:preset-filled-surface-100-900 flex flex-row gap-2">
                    <input
                        type="radio"
                        id="anonymous_yes"
                        name="anonymous"
                        value={true}
                        bind:group={post_form.anonymous}
                        class="radio form-check-input" />
                    <label for="anonymous_yes" class="form-check-label"
                        ><strong>Yes</strong>, the post will be listed as
                        <strong>"Anonymous"</strong></label>
                </div>
            </fieldset>

            <div>
                <div class="form-group d-block block w-100">
                    <span
                        class={$ae_loc.trusted_access
                            ? 'text-surface-600-400 text-sm font-semibold'
                            : 'text-surface-600-400 text-xs font-medium opacity-80 dark:text-surface-400'}>
                        <span class="fas fa-link"></span> Linked with Novi ID
                    </span>
                    {#if !$ae_loc.trusted_access}
                        <span
                            class="fas fa-lock m-1 text-xs opacity-70"
                            title="Field is locked"></span>
                        <div
                            class="mt-1 w-96 rounded-md border border-dashed border-surface-300/70 bg-surface-100/60 px-2.5 py-1.5 text-xs leading-snug text-surface-600 opacity-85 shadow-sm dark:border-surface-600/70 dark:bg-surface-900/45 dark:text-surface-400"
                            style="overflow-wrap: anywhere;">
                            <span class="fas fa-lock mr-2 opacity-60"></span>
                            {post_form.external_person_id || '-- not set --'}
                        </div>
                        <input
                            type="hidden"
                            name="external_person_id"
                            value={post_form.external_person_id ?? ''} />
                    {:else}
                        <div class="ae_highlight bg-yellow-100 p-2 text-sm">
                            Primary link using the Novi API UUID. This must be
                            empty, a staff person, or an active member of IDAA
                            and should be the primary contact for this meeting.
                        </div>
                        <span
                            class="fas fa-unlock m-1"
                            title="Field is unlocked"></span>
                        <input
                            type="text"
                            id="external_person_id"
                            name="external_person_id"
                            bind:value={post_form.external_person_id}
                            readonly={!$ae_loc.administrator_access}
                            class="input preset-tonal-surface hover:preset-filled-surface-100-900 form-control w-96" />
                    {/if}
                </div>
            </div>

            <div>
                <div class="form-group d-block block w-75">
                    <span
                        class={$ae_loc.trusted_access
                            ? 'text-surface-600-400 text-sm font-semibold'
                            : 'text-surface-600-400 text-xs font-medium opacity-80 dark:text-surface-400'}>
                        Name
                        {#if !$ae_loc.trusted_access}
                            <span
                                class="fas fa-lock m-1 text-xs opacity-70"
                                title="Field is locked"></span>
                        {:else}
                            <span
                                class="fas fa-unlock m-1"
                                title="Field is unlocked"></span>
                        {/if}
                    </span>
                    {#if !$ae_loc.trusted_access}
                        <div
                            class="mt-1 w-96 rounded-md border border-dashed border-surface-300/70 bg-surface-100/60 px-2.5 py-1.5 text-xs leading-snug text-surface-600 opacity-85 shadow-sm dark:border-surface-600/70 dark:bg-surface-900/45 dark:text-surface-400"
                            style="overflow-wrap: anywhere;">
                            <span class="fas fa-lock mr-2 opacity-60"></span>
                            {post_form.full_name || '-- not set --'}
                        </div>
                        <input
                            type="hidden"
                            name="full_name"
                            value={post_form.full_name ?? ''} />
                    {:else}
                        <input
                            type="text"
                            id="full_name"
                            name="full_name"
                            bind:value={post_form.full_name}
                            readonly={!$ae_loc.trusted_access}
                            class="input preset-tonal-surface hover:preset-filled-surface-100-900 form-control w-96" />
                    {/if}
                </div>
            </div>

            {#if $ae_loc.trusted_access}
                <div>
                    <label for="email" class="form-group d-block block w-75">
                        <span
                            class="text-surface-600-400 text-sm font-semibold">
                            Email
                        </span>
                        {#if !$ae_loc.trusted_access}
                            <span
                                class="fas fa-lock m-1"
                                title="Field is locked"></span>
                        {:else}
                            <span
                                class="fas fa-unlock m-1"
                                title="Field is unlocked"></span>
                        {/if}
                        <input
                            type="email"
                            name="email"
                            bind:value={post_form.email}
                            readonly={!$ae_loc.trusted_access}
                            class="input preset-tonal-surface hover:preset-filled-surface-100-900 form-control w-96" />
                        <span class="text-surface-600-400 text-xs italic">
                            Secondary link using the Novi email address
                        </span>
                    </label>
                </div>
            {:else}
                <input
                    type="hidden"
                    name="email"
                    value={$idaa_slct.post_obj?.email
                        ? $idaa_slct.post_obj?.email
                        : ($idaa_loc.novi_email ?? '')} />
            {/if}

            <!-- A yes/no radio button group to determine if they want to be notified of comments on this post. -->
            <fieldset class="form-group">
                <legend
                    class="legend text-surface-600-400 text-sm font-semibold">
                    Notify me of comments?
                </legend>
                <div
                    class="preset-tonal-surface hover:preset-filled-surface-100-900 flex flex-row gap-2">
                    <input
                        type="radio"
                        id="notify_no"
                        name="notify"
                        value={false}
                        bind:group={post_form.notify}
                        class="radio form-check-input" />
                    <label for="notify_no"
                        ><strong>No</strong>, do not notify me of comments</label>
                </div>
                <div
                    class="preset-tonal-surface hover:preset-filled-surface-100-900 flex flex-row gap-2">
                    <input
                        type="radio"
                        id="notify_yes"
                        name="notify"
                        value={true}
                        bind:group={post_form.notify}
                        class="radio form-check-input" />
                    <label for="notify_yes"
                        ><strong>Yes</strong>, notify me of comments</label>
                </div>
            </fieldset>
        </div>
        <!-- END: section post__general_information -->

        {#if $ae_loc.trusted_access}
            <!-- BEGIN: section post__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.bb.show__admin_options =
                            !$idaa_loc.bb.show__admin_options;
                    }}>
                    <span
                        class="fas fa-{$idaa_loc.bb.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.bb.show__admin_options}>
                    <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-2">
                            <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={post_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={post_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={post_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={post_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={post_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={post_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="form-check flex flex-row gap-2">
                                    <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={post_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={post_form.enable}
                                            class="radio form-check-input" />
                                        <label for="enable_no">No</label>
                                    </div>
                                </fieldset>
                            </span>
                        {:else}
                            <!-- <input type="hidden" name="enable" value={$idaa_slct.post_obj.enable ?? false} /> -->
                        {/if}
                    </span>

                    {#if $ae_loc.trusted_access}
                        <label for="notes" class="ae_label post__notes 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 hover:preset-filled-surface-100-900"
                                placeholder="Internal notes for staff only. Not shown to the public." />
                        </label>
                    {/if}
                </div>
            </div>
            <!-- END: section post__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
        ">
            <div>
                <!-- BEGIN: section post__options -->
                {#if $idaa_slct.post_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__post_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}
                        onclick={() => {
                            if (
                                !confirm(
                                    'Are you sure you want to create this post?'
                                )
                            ) {
                                return false;
                            }
                            // handle_save_post_obj({post_id: $idaa_slct.post_id, method: 'create'});
                        }}
                        class="
                    novi_btn btn-warning
                    btn
                    preset-tonal-warning hover:preset-filled-warning-200-800
                    transition
                    ">
                        {#await prom_api__post_obj}
                            <span class="fas fa-spinner fa-spin m-1"></span> Saving
                        {:then}
                            <span class="fas fa-plus m-1"></span> Save New Post
                        {/await}
                    </button>
                {/if}

                {#if $idaa_slct.post_id}
                    {#if $ae_loc.administrator_access}
                        <button
                            type="button"
                            onclick={() => {
                                if (
                                    !confirm(
                                        'Are you sure you want to delete this post?'
                                    )
                                ) {
                                    return false;
                                }
                                handle_delete_post_obj({
                                    post_id: $idaa_slct.post_id,
                                    method: 'delete'
                                });
                            }}
                            class="
                novi_btn
                btn btn-sm
                preset-filled-warning-400-600 hover:preset-filled-error-200-800
                "
                            title="Delete record permanently">
                            <span class="fas fa-minus m-1"></span> Delete
                        </button>
                    {:else if $ae_loc.trusted_access}
                        <button
                            type="button"
                            onclick={() => {
                                if (
                                    !confirm(
                                        'Are you sure you want to disable this post?'
                                    )
                                ) {
                                    return false;
                                }
                                handle_delete_post_obj({
                                    post_id: $idaa_slct.post_id,
                                    method: 'disable'
                                });
                            }}
                            class="
                novi_btn
                btn btn-sm
                preset-filled-warning-200-800 hover:preset-filled-error-200-800
                transition
                "
                            title="Disable record to delete">
                            <span class="fas fa-minus m-1"></span> Delete
                        </button>
                    {:else}
                        <button
                            type="button"
                            onclick={() => {
                                if (
                                    !confirm(
                                        'Are you sure you want to hide this post?'
                                    )
                                ) {
                                    return false;
                                }
                                handle_delete_post_obj({
                                    post_id: $idaa_slct.post_id,
                                    method: 'hide'
                                });
                            }}
                            class="
                novi_btn
                btn btn-sm
                preset-filled-warning-200-800 hover:preset-filled-error-200-800
                transition
                "
                            title="Hide record to delete">
                            <span class="fas fa-comment-slash m-1"></span> Delete
                        </button>
                    {/if}
                {/if}
            </div>

            <div>
                <button
                    type="button"
                    onclick={() => {
                        if (obj_changed) {
                            if (
                                confirm(
                                    'You have unsaved changes. Are you sure you want to cancel?'
                                )
                            ) {
                                $idaa_sess.bb.edit__post_obj = false;
                            }
                        } else {
                            // No changes, just close the edit view.
                            $idaa_sess.bb.edit__post_obj = false;
                        }
                    }}
                    class="
                novi_btn
                btn btn-sm
                preset-filled-warning-200-800 hover:preset-filled-success-200-800
                transition
                "
                    title="Cancel editing of post for {$idaa_slct.post_obj
                        .full_name} (ID: {$idaa_slct.post_obj.post_id}">
                    <span class="fas fa-times m-1"></span>
                    Cancel Edit
                </button>
            </div>
        </div>
    </form>
</section>

<style lang="scss">
</style>
