<script lang="ts">
import { run } from 'svelte/legacy';

import { page } from '$app/state';
interface Props {
    /** @type {import('./$types').PageData} */
    data: any;
}

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

let log_lvl: number = 0;
if (log_lvl) {
    console.log(`ae_idaa_bb +page.svelte data:`, data);
}

// import { browser } from '$app/environment';

import { Modal } from 'flowbite-svelte';

// import type { key_val } from '$lib/ae_stores';
// import { ae_util } from '$lib/ae_utils/ae_utils';

import { liveQuery } from "dexie";
// import { core_func } from '$lib/ae_core/ae_core_functions';
import { db_posts } from "$lib/ae_posts/db_posts";
import { ae_snip, ae_loc, ae_sess, ae_api, ae_trig, slct, slct_trigger } from '$lib/ae_stores';
import { idaa_loc, idaa_sess, idaa_slct, idaa_trig, idaa_prom } from '$lib/ae_idaa_stores';
import { posts_func } from '$lib/ae_posts/ae_posts_functions';

import Comp__post_obj_li from './ae_idaa_comp__post_obj_li.svelte';
import Comp__post_obj_id_view from './ae_idaa_comp__post_obj_id_view.svelte';
import Comp__post_options from './ae_idaa_comp__post_options.svelte';


let post_id = page.url.searchParams.get('post_id') ?? null;
if (!post_id) {
    $idaa_slct.post_id = null;
} else {
    console.log(`ae Posts - [post_id] +page.ts: post_id = `, post_id);
    $idaa_slct.post_id = post_id;
    $idaa_trig.post_id = post_id;
}


let lq__post_obj_li = $derived(liveQuery(async () => {
    let results = await db_posts.post
        .where('account_id')
        .equals($slct.account_id)
        // .orderBy('updated_on')
        // .toArray()
        .reverse()
        .sortBy('tmp_sort_1');
        // .sortBy('updated_on');
        // .sortBy('updated_on, created_on');
        // .sortBy('[updated_on+created_on]');
        // .sortBy('[created_on+updated_on]');

    return results;
}));

let lq__post_obj = $derived(liveQuery(async () => {
    let results = await db_posts.post
        .get($idaa_slct.post_id ?? ''); // null or undefined does not reset things like '' does

    return results;
}));

let lq__post_comment_obj_li = $derived(liveQuery(async () => {
    let results = await db_posts.comment
        .where('post_id')
        .equals($idaa_slct.post_id ?? '') // null or undefined does not reset things like '' does
        .reverse()
        .sortBy('updated_on');
        // .sortBy('title');

    return results;
}));

let lq__post_comment_obj = $derived(liveQuery(async () => {
    let results = await db_posts.comment
        .get($idaa_slct.post_comment_id ?? ''); // null or undefined does not reset things like '' does

    return results;
}));



$effect(() => {
    if ($idaa_trig.post_li) {
        $idaa_trig.post_li = false;

        if (log_lvl) {
            console.log(`Triggered: $idaa_trig.post_li`);
        }

        // This may need to be rethought... For now things are cleared  if query is anything but 'all' for enabled and hidden.
        if ($idaa_loc.bb.qry__enabled !== 'all' || $idaa_loc.bb.qry__hidden !== 'all' || $idaa_loc.bb.qry__limit < 50) {
            console.log(`Deleting disabled or hidden post.`);
            let results = db_posts.post
                .clear();
            console.log(`Deleted ${results} disabled post.`);

            console.log(`Deleting disabled or hidden post comments.`);
            results = db_posts.comment
                .clear();
            console.log(`Deleted ${results} disabled post comments.`);
        }

        $idaa_prom.load__post_obj_li = posts_func.load_ae_obj_li__post({
            api_cfg: $ae_api,
            for_obj_type: 'account',
            for_obj_id: $idaa_slct.account_id,
            inc_comment_li: true,
            enabled: $idaa_loc.bb.qry__enabled,
            hidden: $idaa_loc.bb.qry__hidden,
            limit: $idaa_loc.bb.qry__limit,
            order_by_li: $idaa_loc.bb.qry__order_by_li,
            try_cache: true,
            log_lvl: log_lvl,
        });
    }
});

$effect(() => {
    if ($idaa_trig.post_id) {
        // log_lvl = 1;
        $idaa_trig.post_id = false;

        if (log_lvl) {
            console.log(`Triggered: $idaa_trig.post_id`);
        }

        $idaa_prom.load__post_obj = posts_func.load_ae_obj_id__post({
            api_cfg: $ae_api,
            post_id: $idaa_slct.post_id,
            enabled: $idaa_loc.bb.qry__enabled,
            hidden: $idaa_loc.bb.qry__hidden,
            limit: $idaa_loc.bb.qry__limit,
            inc_comment_li: true,
            try_cache: true,
            log_lvl: log_lvl,
        })
        .then((post_obj) => {
            if (log_lvl) {
                console.log(`Post object loaded: `, post_obj);
            }

            $idaa_slct.post_obj = post_obj;
            $idaa_slct.post_comment_id = null;
            $idaa_slct.post_comment_obj = null;

            // $idaa_sess.bb.show__modal_view__post_id = $idaa_slct.post_id;
            // $idaa_sess.bb.show__modal_edit__post_id = false;
        });

        // $idaa_slct.post_obj = $idaa_prom.load__post_obj;

        if (!page.url.searchParams.get('post_id')) {
            const url = new URL(location);
            url.searchParams.set('post_id', $idaa_slct.post_id);
            history.pushState({}, '', url);

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

        $idaa_sess.bb.show__modal_view__post_id = $idaa_slct.post_id;
        $idaa_sess.bb.show__modal_edit__post_id = false;
    }
});
</script>



<svelte:head>
	<title>
        IDAA Bulletin Board:
        - Novi - {$ae_loc?.title}
    </title>
</svelte:head>


<section
    class="
        ae_idaa__bb
        container h-full mx-auto
        flex flex-col gap-1
        py-1 px-2 pb-16
        items-center
        min-w-full
        max-w-max
        "
    >


<Comp__post_options
    />

<!-- <h1>Bulletin Board {$lq__post_obj_li?.length}</h1> -->

{#if $lq__post_obj_li && $lq__post_obj_li?.length}
    <Comp__post_obj_li
        lq__post_obj_li={lq__post_obj_li}
        />
{:else}
    <p>No posts available to show.</p>
{/if}


</section>


<!-- Modal: Post (Bulletin Board) view ID -->
<Modal
    title="{$lq__post_obj?.title ?? 'New Post'} - {$lq__post_obj?.id ?? 'Not Saved Yet'}"
    bind:open={$idaa_sess.bb.show__modal_view__post_id}
    autoclose={false}
    outsideclose={true}
    placement="top-center"
    size="lg"
    class="bg-white dark:bg-gray-800 text-gray-800 dark:text-gray-200 rounded-lg border-gray-200 dark:border-gray-700 divide-gray-200 dark:divide-gray-700 shadow-md relative flex flex-col mx-auto w-full divide-y"
    on:close={() => {
        // We want to cancel the inline edit if the modal is closed
        $idaa_sess.bb.show__inline_edit__post_obj = false;
    }}
    >

    {#snippet header()}


            <div class="flex flex-row items-center justify-between w-full">
                <h3 class="text-lg font-semibold">
                    {#if $ae_loc.trusted_access || $lq__post_obj?.external_person_id === $idaa_loc.novi_uuid}
                        <button
                            onclick={() => {
                            // const url = new URL(location);
                            // url.searchParams.set('post_id', $lq__post_obj?.post_id_random);
                            // history.pushState({}, '', url);

                            // $idaa_sess.bb.show__modal_view = false;
                            if ($idaa_sess.bb.show__inline_edit__post_obj) {
                                $idaa_sess.bb.show__inline_edit__post_obj = false;
                            } else {
                                $idaa_sess.bb.show__inline_edit__post_obj = true;
                            }
                        }}
                            class="novi_btn btn btn-sm variant-ghost-warning hover:variant-filled-warning transition"
                            title={`Edit meeting: ${$lq__post_obj?.title}`}
                            >
                            {#if $idaa_sess.bb.show__inline_edit__post_obj}
                                <span class="fas fa-times m-1"></span> Cancel Edit
                            {:else}
                                <span class="fas fa-edit m-1"></span> Edit
                            {/if}
                        </button>
                    {/if}
                    <!-- {$lq__post_obj?.title ?? 'New Post'} -->
                    <span class="">
                        <span class="fas fa-comment-alt m-1"></span>
                        {@html $lq__post_obj?.title ?? 'New Post'}
                        <!-- - {$lq__post_obj?.id ?? 'Not Yet Saved'} -->
                    </span>
                    {#if $lq__post_obj?.topic_id}<span class="badge badge-info variant-glass-secondary"><span class="fas fa-user-md m-1"></span> {$lq__post_obj?.topic_name}</span>{/if}
                </h3>
            </div>

    {/snippet}

    <Comp__post_obj_id_view
        lq__post_obj={lq__post_obj}
        lq__post_comment_obj_li={lq__post_comment_obj_li}
        lq__post_comment_obj={lq__post_comment_obj}
        />

</Modal>
