<script lang="ts">
	interface Props {
		lq__post_obj: any;
		lq__post_comment_obj_li: any;
		lq__post_comment_obj: any;
	}

	let { lq__post_obj, lq__post_comment_obj_li, lq__post_comment_obj }: Props = $props();

	// *** Import Svelte specific
	import { browser } from '$app/environment';

	// *** 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 { api } from '$lib/api/api';
	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, idaa_trig } from '$lib/stores/ae_idaa_stores';

	// import Comp__post_obj_id_edit from './ae_idaa_comp__post_obj_id_edit.svelte';
	import Comp__post_comment_obj_id_edit from './ae_idaa_comp__post_comment_obj_id_edit.svelte';

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

	if ($idaa_slct.post_id) {
		console.log(`Post ID selected: ${$idaa_slct.post_id}`);
		console.log(`Post Object selected: `, $lq__post_obj);
		console.log(`Post Object title (name): ${$lq__post_obj?.title}`);

		$idaa_trig.post_id = $idaa_slct.post_id;
	}

	$effect(() => {
		if (browser && $lq__post_obj?.post_id) {
			document.body.scrollIntoView();

			// const url = new URL(location);
			// url.searchParams.set('post_id', $lq__post_obj?.post_id);
			// history.pushState({}, '', url);
		}
	});

	// onDestroy(() => {
	//     console.log('** Component Destroyed: ** View - Post Obj');

	//     const url = new URL(location);
	//     url.searchParams.delete('post_id');
	//     history.pushState({}, '', url);
	// });

	// function handle_post_comment_obj_created(event) {
	//     console.log('*** handle_post_comment_obj_created() ***');
	//     console.log(event.detail);

	//     $idaa_slct.post_comment_id = null;
	//     $idaa_slct.post_comment_obj = {};

	//     $idaa_trig = 'load__post_obj_li';
	//     $idaa_trig = 'load__post_obj';
	//     $idaa_trig = 'load__post_comment_obj_li';

	//     // $idaa_sess.bb.show_post_list = false;
	//     // $idaa_sess.bb.show_edit__post_id = false;
	//     // $idaa_sess.bb.show_view__post_id = true;
	//     $idaa_sess.bb.show_edit__post_comment = false;
	// }
	// function handle_post_comment_obj_updated(event) {
	//     console.log('*** handle_post_comment_obj_updated() ***');
	//     console.log(event.detail);

	//     $idaa_trig = 'load__post_obj';
	//     $idaa_trig = 'load__post_comment_obj_li';

	//     // $idaa_sess.bb.show_post_list = false;
	//     // $idaa_sess.bb.show_edit__post_id = false;
	//     // $idaa_sess.bb.show_view__post_id = true;
	//     $idaa_sess.bb.show_edit__post_comment = false;
	// }
	// function handle_post_comment_obj_deleted(event) {
	//     console.log('*** handle_post_comment_obj_deleted() ***');
	//     console.log(event.detail);

	//     $idaa_trig = 'load__post_obj_li';
	//     $idaa_trig = 'load__post_obj';
	//     $idaa_trig = 'load__post_comment_obj_li';

	//     // $idaa_sess.bb.show_post_list = false;
	//     // $idaa_sess.bb.show_edit__post_id = false;
	//     // $idaa_sess.bb.show_view__post_id = true;
	//     $idaa_sess.bb.show_edit__post_comment = false;
	// }
</script>

<section
	bind:clientHeight={$ae_loc.iframe_height_modal_body}
	class="svelte_component ae_section ae_view post_obj view__post_obj space-y-2"
>
	<!-- {#if $idaa_sess.bb.show__inline_edit__post_obj}
    <Comp__post_obj_id_edit
        lq__post_obj={lq__post_obj}
        />
{:else} -->

	<!-- <div class="post__header">
    <h2 class="post__title flex flex-row gap-2 items-center h3">
        <span class="">
            <span class="fas fa-comment-alt m-1"></span>
            {@html $lq__post_obj?.title ?? 'New Post'}
        </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}
    </h2>
</div> -->

	<div class="post__content space-y-2">
		<!-- <pre class="post__content p-2 bg-white shadow-md rounded-lg text-wrap text-sm font-normal whitespace-pre-wrap">{@html $lq__post_obj?.content}</pre> -->

		<div
			class="post__content p-2 bg-white shadow-md rounded-lg text-wrap text-sm font-normal reset_css"
		>
			{@html $lq__post_obj?.content}
		</div>

		{#if $lq__post_obj?.linked_li_json && $lq__post_obj?.linked_li_json.length}
			<div class="ae_section flex flex-row flex-wrap gap-1 items-center justify-center">
				<span class="fas fa-paperclip"></span>
				<span class="text-sm text-gray-600 dark:text-gray-400 italic">Linked files:</span>
				{#each $lq__post_obj.linked_li_json as linked_obj, index}
					<!-- <a
                    href={linked_obj.url}
                    target="_blank"
                    class="badge badge-info variant-filled-info"
                    >
                    <span class="fas fa-paperclip m-1"></span>
                    {linked_obj.filename}
                    ({linked_obj.hosted_file_id_random})
                </a> -->

					{#if $ae_loc.authenticated_access && linked_obj?.hosted_file_id_random}
						{#if linked_obj.extension === 'png' || linked_obj.extension === 'jpg' || linked_obj.extension === 'jpeg' || linked_obj.extension === 'gif' || linked_obj.extension === 'webp' || linked_obj.extension === 'svg'}
							<div>
								<img
									src="{$ae_api.base_url}/hosted_file/{linked_obj?.hosted_file_id_random}/download?x_no_account_id_token=direct-download"
									alt={linked_obj.filename}
									class="w-fit min-w-96 h-fit object-cover rounded-lg shadow-md"
								/>
								<!-- <img src={api.download_hosted_file({
                                    api_cfg: $ae_api,
                                    hosted_file_id: linked_obj.hosted_file_id_random,
                                    return_file: true,
                                    filename: linked_obj.filename,
                                    auto_download: false,
                                    log_lvl: 1
                                    })
                                }
                                alt={linked_obj.filename}
                                class="w-fit min-w-96 h-fit object-cover rounded-lg shadow-md"
                                /> -->
							</div>
						{:else}
							<button
								type="button"
								disabled={!$ae_loc.trusted_access}
								onclick={() => {
									ae_promises[linked_obj.hosted_file_id_random] = api.download_hosted_file({
										api_cfg: $ae_api,
										hosted_file_id: linked_obj.hosted_file_id_random,
										return_file: true,
										filename: linked_obj.filename,
										auto_download: true,
										log_lvl: 0
									});

									// window.postMessage({ type: 'download_event_file', hosted_file_id: linked_obj.hosted_file_id_random, filename: linked_obj.filename, auto_download: true }, '*');
								}}
								class="novi_btn btn btn-sm lg:btn-md preset-tonal-tertiary border border-tertiary-500 hover:preset-filled-tertiary-500 min-w-48"
								title={`Download this file:\n${linked_obj.filename}\n[API] SHA256: ${linked_obj?.hash_sha256.slice(0, 10)}... Hosted ID: ${linked_obj.hosted_file_id_random} Archive Content ID: ${linked_obj.archive_content_id}`}
							>
								{#await ae_promises[linked_obj.hosted_file_id_random]}
									<span class="fas fa-spinner fa-spin mx-1"></span>
									<span class="">
										Downloading
										{#if $ae_sess.api_download_kv[linked_obj.hosted_file_id_random]}
											{$ae_sess.api_download_kv[linked_obj.hosted_file_id_random]
												.percent_completed}%
										{/if}
										:
									</span>
								{:then}
									<span class="fas fa-{ae_util.file_extension_icon(linked_obj?.extension)}"></span>
								{/await}

								<span class="grow">
									{ae_util.shorten_filename({ filename: linked_obj?.filename, max_length: 30 })}
								</span>
							</button>
						{/if}
					{/if}
				{/each}
			</div>
		{/if}
	</div>

	<section
		class="ae_section ae_meta post__meta text-xs text-gray-500 mt-4 flex flex-row gap-2 items-center justify-between"
	>
		<div class="ae_group flex flex-col gap-1">
			{#if $lq__post_obj?.anonymous}
				<div class="post__posted_by">
					Posted by: <span class="fas fa-user-secret"></span>
					<span class="post__full_name">Anonymous</span>
				</div>
			{:else if $lq__post_obj?.full_name}
				<div class="post__posted_by">
					Posted by: <span class="fas fa-user"></span>
					<span class="post__full_name">{$lq__post_obj?.full_name}</span>
					{#if $ae_loc.trusted_access && $lq__post_obj?.email}
						<a href="mailto:{$lq__post_obj?.email}?subject=IDAA BB Post">{$lq__post_obj?.email}</a>
					{/if}
				</div>
			{/if}

			<div class="post__created_on_updated_on">
				{#if !$lq__post_obj?.updated_on}
					<span class="ae_label">Created on:</span>
					<span class="ae_value post__created_on"
						>{ae_util.iso_datetime_formatter($lq__post_obj?.created_on, 'datetime_12_short')}</span
					>
				{:else}
					<span class="ae_label">Updated on:</span>
					<span class="ae_value post__updated_on">
						{ae_util.iso_datetime_formatter($lq__post_obj?.updated_on, 'datetime_12_short')}</span
					>
				{/if}
				<span class="post__archive_on" class:hidden={!$ae_loc.administrator_access}>
					<span class="ae_label">Archive on:</span>
					<span class="ae_value"
						>{ae_util.iso_datetime_formatter($lq__post_obj?.archive_on, 'datetime_12_short')}</span
					>
				</span>
			</div>
		</div>

		<div class="ae_options flex flex-row gap-1 items-center">
			{#if $lq__post_obj?.post_comment_count}
				<span class="ae_badge ae_info post__post_comment_count">
					<span class="fas fa-comment"></span>
					{$lq__post_obj?.post_comment_count == 1
						? `${$lq__post_obj?.post_comment_count} comment`
						: `${$lq__post_obj?.post_comment_count} comments`}
				</span>
			{/if}
			{#if ($ae_loc.trusted_access && $ae_loc.edit_mode) || $idaa_loc.novi_uuid}
				<button
					type="button"
					onclick={() => {
						if (!confirm('Are you sure you want to add a new comment?')) {
							return;
						}

						$idaa_slct.post_comment_id = null;
						$idaa_slct.post_comment_obj = {};

						$idaa_sess.bb.show__inline_edit__post_comment_id = true;
					}}
					class="
                novi_btn btn-primary
                btn btn-md preset-tonal-secondary
                border border-secondary-500 hover:preset-filled-secondary-500
                transition-all"
					title={`New comment on: ${$lq__post_obj?.title}`}
				>
					<span class="fas fa-plus m-1"></span> New Comment
				</button>
			{/if}

			{#if ($ae_loc.trusted_access && $ae_loc.edit_mode) || $lq__post_obj?.external_person_id === $idaa_loc.novi_uuid}
				<button
					type="button"
					onclick={() => {
						// $idaa_slct.post_id = $idaa_slct.post_obj.post_id_random;
						$idaa_slct.post_obj = $lq__post_obj; // In case things changed

						// const url = new URL(location);
						// url.searchParams.set('post_id', $idaa_slct.post_obj.post_id_random);
						// history.pushState({}, '', url);

						// $idaa_sess.bb.show_main__options = false;
						// $idaa_sess.bb.show_list__post_li = false;
						// $idaa_sess.bb.show_view__post_id = false;
						// $idaa_sess.bb.show__inline_edit__post_obj = true;
						$idaa_sess.bb.edit__post_obj = $idaa_slct.post_id;
					}}
					class="
                novi_btn
                btn btn-sm preset-tonal-warning
                hover:preset-filled-warning-500 transition
                "
					title="Edit post for {$lq__post_obj?.full_name} (ID: {$lq__post_obj?.post_id}"
				>
					<span class="fas fa-edit m-1"></span> Edit Post
				</button>
			{/if}
		</div>
	</section>
	<!-- {/if} -->

	{#if $idaa_sess.bb.show__inline_edit__post_comment_id === true}
		<Comp__post_comment_obj_id_edit
			{lq__post_obj}
			{lq__post_comment_obj}
			{lq__post_comment_obj_li}
		/>
	{/if}

	{#if $lq__post_comment_obj_li?.length}
		<section class="post_comment_obj_li space-y-2 border p-0 border-y-0">
			{#each $lq__post_comment_obj_li as post_comment_obj, index}
				<div
					class="p-4 space-y-1 border-b-2"
					class:dim={post_comment_obj?.hide}
					class:bg-warning-100={!post_comment_obj?.enable}
				>
					{#if $idaa_sess.bb.show__inline_edit__post_comment_id == post_comment_obj.post_comment_id}
						{$lq__post_comment_obj_li.length ?? 'unknown???'}
						<Comp__post_comment_obj_id_edit
							{lq__post_obj}
							{lq__post_comment_obj}
							{lq__post_comment_obj_li}
						/>
					{:else}
						<div class="post_comment__content">
							<pre
								class="post_comment__content p-2 bg-white shadow-md rounded-lg text-wrap text-sm font-normal whitespace-pre-wrap">{@html post_comment_obj.content}</pre>
						</div>

						<section
							class="ae_section ae_meta post_comment__meta text-xs text-gray-500 mt-4 flex flex-row gap-2 items-center justify-between"
						>
							<div class="flex flex-col gap-1">
								<span class="post_comment__posted_by `comment_by_container">
									<span class="comment_by_lable">Comment by:</span>
									{#if post_comment_obj.anonymous}
										<span class="fas fa-user-secret"></span>
										<span class="comment_by_full_name anonymous">Anonymous</span>
									{:else}
										<span class="fas fa-user"></span>
										<span class="comment_by_full_name">{post_comment_obj.full_name}</span>
									{/if}
								</span>
								<span class="post_comment__created_on_updated_on">
									{#if !post_comment_obj.updated_on || $ae_loc.edit_mode}
										<span class="ae_label">Created on:</span>
										<span class="ae_value post_comment__created_on"
											>{ae_util.iso_datetime_formatter(
												post_comment_obj.created_on,
												'datetime_12_short'
											)}</span
										>
									{/if}
									{#if post_comment_obj.updated_on}
										<span class="ae_label">Updated on:</span>
										<span class="ae_value post_comment__updated_on"
											>{ae_util.iso_datetime_formatter(
												post_comment_obj.updated_on,
												'datetime_12_short'
											)}</span
										>
									{/if}
								</span>
							</div>

							{#if ($ae_loc.trusted_access && $ae_loc.edit_mode) || post_comment_obj.external_person_id === $idaa_loc.novi_uuid}
								<div class="ae_options">
									<button
										type="button"
										onclick={() => {
											$idaa_slct.post_comment_id = post_comment_obj.post_comment_id;
											$idaa_slct.post_comment_obj = post_comment_obj;

											$idaa_sess.bb.show__inline_edit__post_comment_id =
												post_comment_obj.post_comment_id;
										}}
										class="
                    novi_btn
                    btn btn-sm preset-tonal-warning
                    hover:preset-filled-warning-500 transition"
										title="Edit comment by {post_comment_obj?.full_name} (for post ID {$lq__post_obj?.id})"
									>
										<span class="fas fa-edit m-1"></span>
										Edit Comment
									</button>
								</div>
							{/if}
						</section>
					{/if}
				</div>
			{/each}
		</section>
	{/if}
</section>

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