<script lang="ts">
interface Props {
    /** @type {import('./$types').PageData} */
    data: any;
}

let { data }: Props = $props();

let log_lvl: number = 0;

// *** Import Svelte specific
import { onMount, onDestroy, untrack } from 'svelte';
import { goto } from '$app/navigation';

// *** Import other supporting libraries
import { liveQuery } from 'dexie';

// *** Import Aether specific variables and functions
import { ae_util } from '$lib/ae_utils/ae_utils';
import {
    ae_snip,
    ae_loc,
    ae_sess,
    ae_api,
    ae_trig,
    slct,
    slct_trigger
} from '$lib/stores/ae_stores';
import { db_posts } from '$lib/ae_posts/db_posts';
// import { posts_func } from '$lib/ae_posts/ae_posts_functions';
import {
    idaa_loc,
    idaa_sess,
    idaa_slct,
    idaa_trig,
    idaa_prom
} from '$lib/stores/ae_idaa_stores';

import Comp__post_obj_id_edit from '.././ae_idaa_comp__post_obj_id_edit.svelte';
import Comp__post_obj_id_view from '.././ae_idaa_comp__post_obj_id_view.svelte';

// *** Quickly pull out data from parent(s)
let ae_acct = $derived(data[data.account_id]);

$idaa_sess.bb.edit__post_obj = null;
$effect(() => {
    if (!ae_acct) return;
    if (log_lvl) console.log(`ae_acct = `, ae_acct);
    untrack(() => {
        $idaa_slct.post_id = ae_acct.slct.post_id;
        $idaa_trig.post_id = ae_acct.slct.post_id;
        // $idaa_slct.post_obj = ae_acct.slct.post_obj;
    });
});

// *** Functions and Logic
let lq__post_obj = $derived.by(() => {
    // SVELTE 5 REACTIVITY: Track IDs synchronously
    const post_id = $idaa_slct.post_id ?? '';

    return liveQuery(async () => {
        if (log_lvl) console.log(`lq__post_obj: post_id = ${post_id}`);
        if (!post_id) return null;

        return await db_posts.post.get(post_id);
    });
});

let lq__post_comment_obj_li = $derived.by(() => {
    const post_id = $idaa_slct.post_id ?? '';
    const limit = $idaa_loc.bb.qry__limit;

    return liveQuery(async () => {
        if (!post_id) return [];

        // tmp_sort_1 is built with build_tmp_sort() and is designed for ASC sort:
        // priority=true -> '0', so priority records naturally sort first.
        const comments = await db_posts.comment
            .where('post_id')
            .equals(post_id)
            .limit(limit)
            .sortBy('tmp_sort_1');
        return comments;
    });
});

let lq__post_comment_obj = $derived.by(() => {
    const comment_id = $idaa_slct.post_comment_id ?? '';

    return liveQuery(async () => {
        if (!comment_id) return null;
        return await db_posts.comment.get(comment_id);
    });
});

function clear_bb_edit_state() {
    $idaa_sess.bb.edit__post_obj = false;
    $idaa_loc.bb.edit__post_obj = false;
    $idaa_sess.bb.show__inline_edit__post_obj = false;
    $idaa_loc.bb.show__inline_edit__post_obj = false;
    $idaa_sess.bb.show__inline_edit__post_comment_id = false;
    $idaa_loc.bb.show__inline_edit__post_comment_id = false;
    $idaa_sess.bb.obj_changed = false;
}

function handle_back_to_posts_list() {
    if ($idaa_sess.bb.obj_changed) {
        if (!confirm('You have unsaved changes. Are you sure you want to cancel?')) {
            return;
        }
    }

    clear_bb_edit_state();
    void goto('/idaa/bb');
}

onMount(() => {
    console.log('Browser environment detected.');

    // NOTE: Use data[data.account_id].slct.post_id (from load / URL params),
    // NOT $idaa_slct.post_id (the store). The store is updated by a $effect that runs
    // after this synchronous block — reading it here sends the old/null value.
    let message = { post_id: data[data.account_id]?.slct?.post_id ?? null };
    window.parent.postMessage(message, '*');

    if ($ae_loc?.iframe) {
        console.log(
            'In iframe, sending message to parent window to scroll to top as well'
        );
        window.parent.postMessage({ scroll_to: 0 }, '*'); // This should be in pixels
    }
});

onDestroy(() => {
    log_lvl = 1;
    if (log_lvl) {
        console.log(`Destroying bb page for post_id: ${$idaa_slct?.post_id}`);
    }

    let message = { post_id: null };
    window.parent.postMessage(message, '*');

    // $idaa_slct.post_id = null;
    // $idaa_slct.post_obj = null;
});
</script>

<svelte:head>
    <title>
        IDAA BB:
        {$lq__post_obj?.name
            ? ae_util.shorten_string({
                  string: $lq__post_obj?.name,
                  max_length: 20,
                  begin_length: 10,
                  end_length: 4
              })
            : ''}
        - Novi - {$ae_loc?.title}
    </title>
</svelte:head>

<header
    class="ae_header flex w-full flex-row flex-wrap items-center justify-evenly gap-2">
    <h2
        class="
            ae_name post__name
            h3
            flex max-w-full
            min-w-1/2 flex-row items-center justify-center gap-2
            text-2xl
            font-bold
            ">
        <!-- <span class="ae_icon fas fa-calendar-alt"></span> -->
        <span class="ae_icon fas fa-calendar-day text-neutral-800/80"></span>
        {$lq__post_obj?.name ? $lq__post_obj?.name : 'BB Post'}
    </h2>

    <div
        class="
            flex max-w-full min-w-1/4 flex-row items-center
            justify-evenly
            gap-2
        ">
        <!-- {#if $lq__post_obj?.topic_id}<span class="badge badge-info preset-tonal-secondary"><span class="fas fa-user-md m-1"></span> {$lq__post_obj?.topic_name}</span>{/if} -->

        <span
            class="float-right flex flex-row flex-wrap items-center justify-end gap-1">
            {#if $lq__post_obj?.topic_name}
                <span class="badge badge-info preset-tonal-secondary"
                    ><span class="fas fa-tag"></span>
                    {$lq__post_obj?.topic_name}</span>
            {/if}
            {#if $ae_loc.trusted_access && $lq__post_obj?.hide}
                <span class="badge badge-warning"
                    ><span class="fas fa-exclamation-triangle m-1"></span> Hidden</span>
            {/if}
            {#if $ae_loc.administrator_access && !$lq__post_obj?.enable}
                <span class="badge badge-warning preset-tonal-warning"
                    ><span class="fas fa-exclamation-triangle m-1"></span> Not enabled</span>
            {/if}
        </span>
    </div>
</header>

<div
    class="
        border-b-surface-300-700 mb-2 flex w-full flex-row
        items-center
        justify-evenly gap-2 border-b
        p-1 pb-2
        ">
    <button
        type="button"
        onclick={handle_back_to_posts_list}
        class="
            novi_btn btn btn-secondary btn-sm
            preset-tonal-tertiary border-tertiary-500 hover:preset-filled-tertiary-500
            border
            transition
            ">
        <span class="fas fa-arrow-left m-1 text-neutral-800/80"></span> Back to
        Posts List
        <!-- <span class="fas fa-times m-1"></span> View Other Meetings -->
    </button>

    <!-- View (default)/Edit post_id toggle -->
    {#if $idaa_sess.bb.edit__post_obj}
        <button
            type="button"
            class="
                novi_btn
                btn btn-sm
                preset-filled-warning-200-800 hover:preset-filled-success-200-800
                transition
                "
            onclick={() => {
                if ($idaa_sess.bb.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;
                }
                // if (log_lvl) {
                //     console.log(`Toggle edit__post_obj: ${$idaa_sess.bb.edit__post_obj}`);
                // }
            }}
            title="View this BB Post">
            <!-- <span class="far fa-window-close m-1"></span> -->
            <span class="fas fa-times m-1 text-neutral-800/80"></span>
            Cancel Edit
        </button>
    {:else}
        <!-- This checks if the currently logged in Novi user has a matching UUID or email address. -->
        {#if ($ae_loc.trusted_access && $ae_loc.edit_mode) || $lq__post_obj?.external_person_id === $idaa_loc.novi_uuid || $lq__post_obj?.email === $idaa_loc.novi_email}
            <button
                type="button"
                class="
                    novi_btn
                    btn btn-sm preset-tonal-warning
                    hover:preset-filled-warning-500 transition
                    "
                onclick={() => {
                    // $idaa_slct.post_obj = {
                    //     ...$lq__post_obj,
                    // }
                    $idaa_sess.bb.edit__post_obj = $idaa_slct.post_id;
                    // if (log_lvl) {
                    //     console.log(`Toggle edit__post_obj: ${$idaa_sess.bb.edit__post_obj}`);
                    // }
                }}
                title="Edit this BB Post">
                <span class="fas fa-edit m-1"></span>
                Edit Post
            </button>
        {/if}
    {/if}
</div>

{#if $idaa_sess.bb.edit__post_obj || $idaa_loc.bb.edit__post_obj}
    <!-- lq__post_comment_obj_li={lq__post_comment_obj_li} -->
    <!-- lq__post_comment_obj={lq__post_comment_obj} -->
    <Comp__post_obj_id_edit
        bind:obj_changed={$idaa_sess.bb.obj_changed} />
{:else}
    <Comp__post_obj_id_view
        {lq__post_obj}
        {lq__post_comment_obj_li}
        {lq__post_comment_obj} />
{/if}
