<script lang="ts">
interface AccountPageData {
    slct?: {
        post_id?: string | null;
    };
}

interface Props {
    data: { account_id: string } & Record<string, AccountPageData>;
}
let { data }: Props = $props();

let log_lvl: number = $state(0);

// *** Import Svelte specific
import { page } from '$app/state';
import { browser } from '$app/environment';
import { untrack } from 'svelte';
// import { goto, invalidate, pushState, replaceState } from '$app/navigation';

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

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

import Comp__post_obj_id_edit from './ae_idaa_comp__post_obj_id_edit.svelte';
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;
}

// *** Functions and Logic
// Stable LiveQuery Pattern (Aether UI V3)
let lq__post_obj_li = $derived.by(() => {
    // SVELTE 5 REACTIVITY: Track account selection synchronously
    const account_id = $slct.account_id ?? '';

    return liveQuery(async () => {
        const now = new Date();
        const results = await db_posts.post
            .where('account_id')
            .equals(account_id)
            .filter((x) => {
                if (!x.archive_on) return true;
                const archiveDate =
                    x.archive_on instanceof Date
                        ? x.archive_on
                        : new Date(x.archive_on);
                return archiveDate > now;
            })
            .toArray();

        // SORT: Most recently updated or created at the top (Refactored 2026-02-05)
        // ROBUSTNESS: Ensure fallback to 0 to prevent NaN comparison issues
        results.sort((a, b) => {
            const date_a =
                new Date(a.updated_on ?? a.created_on ?? 0).getTime() || 0;
            const date_b =
                new Date(b.updated_on ?? b.created_on ?? 0).getTime() || 0;
            return date_b - date_a;
        });

        return results;
    });
});

// let lq__post_obj = $derived.by(() => {
//     const post_id = $idaa_slct.post_id ?? '';
//     return liveQuery(async () => {
//         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 ?? '';
//     return liveQuery(async () => {
//         if (!post_id) return [];
//         return await db_posts.comment
//             .where('post_id')
//             .equals(post_id)
//             .reverse()
//             .sortBy('updated_on');
//     });
// });

// 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);
//     });
// });

// Initial post load — gated on novi_verified.
// WHY $effect and not +page.ts: +page.ts runs before layout effects and fires on SvelteKit
// link prefetch (hover), causing private IDAA data to be written to IDB before auth runs.
// $effect only runs post-mount, after the layout has completed Novi verification.
$effect(() => {
    if (!$idaa_loc.novi_verified && !$ae_loc.trusted_access) return;
    untrack(() => {
        posts_func.load_ae_obj_li__post({
            api_cfg: $ae_api,
            for_obj_type: 'account',
            for_obj_id: data.account_id,
            inc_comment_li: false,
            enabled: 'enabled',
            hidden: 'not_hidden',
            limit: 19,
            order_by_li: { updated_on: 'DESC', created_on: 'DESC' },
            try_cache: true,
            log_lvl
        });
    });
});

// Handle Single Post Load Trigger
$effect(() => {
    if ($idaa_trig.post_id) {
        const post_id = $idaa_trig.post_id;
        $idaa_trig.post_id = null;

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

        // Non-blocking background refresh
        posts_func.load_ae_obj_id__post({
            api_cfg: $ae_api,
            post_id: post_id,
            inc_comment_li: true,
            try_cache: true,
            log_lvl
        });
    }
});

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

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

        // Wrap the data fetching logic in an async function to await clearing
        const refresh_posts = async () => {
            // 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.`);
                await db_posts.post.clear();
                console.log(`Deleted disabled post.`);

                console.log(`Deleting disabled or hidden post comments.`);
                await db_posts.comment.clear();
                console.log(`Deleted disabled post comments.`);
            }

            $idaa_prom.load__post_obj_li = posts_func.qry__post({
                api_cfg: $ae_api,
                account_id: $slct.account_id,
                qry_archive_on: '2024-01-01', // (new Date()).toISOString(),
                inc_comment_li: false,
                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
            });
        };

        refresh_posts();
    }
});

if (browser) {
    console.log('Browser environment detected.');

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

    // add_activity_log(
    //     {
    //         action: 'idaa_bb_page',
    //         action_with: 'browser',
    //     }
    // );
}

// function add_activity_log({
//     action = 'idaa_bb_page',
//     action_with = 'none'
// }: {
//     action?: string;
//     action_with?: string;
// }) {
//     let last_cache_refresh_iso = new Date($ae_loc?.last_cache_refresh);

//     let activity_description = `
//     ${$idaa_loc.novi_full_name ?? 'none'} ${$idaa_loc.novi_email ?? 'no-email'}
//     allow=${$ae_loc?.allow_access}
//     last_cache_refresh=${last_cache_refresh_iso.toLocaleString()}
//     data_route=${data?.route.toString() ?? 'unknown'}
// `;

//     let data_kv = {
//         external_client_id: data?.route.id,
//         name: `IDAA: ${$idaa_loc.novi_full_name ?? 'none'} ${$idaa_loc.novi_email ?? ''}`,
//         description: activity_description ?? null,
//         object_type: 'post', // archive, post, event
//         // object_id: data?.params?.event_id ?? null,
//         // object_id: ae_acct.slct.archive_id, // data?.params?.archive_id ?? null,
//         url_root: data?.url.origin,
//         // url_full_path: data?.url.href,
//         url_full_path: data?.url.pathname,
//         url_params: data?.url.searchParams.toString(),
//         action: action,
//         action_with: action_with ?? 'none',
//         meta_json: {
//             allow_access: $ae_loc?.allow_access,
//             last_cache_refresh: $ae_loc?.last_cache_refresh,
//             last_cache_refresh_iso: last_cache_refresh_iso.toISOString(),
//             last_cache_refresh_locale: last_cache_refresh_iso.toLocaleString(),
//             access_level: $ae_loc?.access_level,
//             iframe: $ae_loc?.iframe
//             // site_access_key: $ae_loc?.site_access_key,
//             // site_domain_access_key: $ae_loc?.site_domain_access_key,
//             // site_domain: $ae_loc?.site_domain,
//             // extra_data: extra_data ?? '',
//             // log_lvl: log_lvl,
//         }
//     };

//     core_func.create_ae_obj__activity_log({
//         api_cfg: $ae_api,
//         account_id: $ae_loc.account_id,
//         data_kv: data_kv,
//         log_lvl: log_lvl
//     });
// }
</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 />

{#if $idaa_sess.bb.edit__post_obj || $idaa_loc.bb.edit__post_obj}
    <Comp__post_obj_id_edit
        bind:obj_changed={$idaa_sess.bb.obj_changed} />
{/if}

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

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

<!-- </section> -->
