<script lang="ts">
/**
 * launcher_session_view_posters.svelte
 *
 * WHY: Digital Poster sessions need a dedicated card-grid layout optimised for
 * touch-first PWA use on tablets and phones.  Keeping this separate from the oral
 * session view avoids cluttering that template with a growing set of poster-specific
 * branches and lets each view own its own layout concerns cleanly.
 *
 * The menu will typically be hidden and the page may be in iframe mode
 * ($ae_loc.iframe == true), so this view fills the full available width.
 *
 * Deployment context: operator tablet / phone PWA, also works on desktop.
 */
interface Props {
    slct__event_session_id?: string | null;
    log_lvl?: number;
}

let {
    slct__event_session_id = $bindable(null),
    log_lvl = $bindable(1)
}: Props = $props();

import { liveQuery } from 'dexie';
import { ae_loc } from '$lib/stores/ae_stores';
import { db_events } from '$lib/ae_events/db_events';
import { events_sess } from '$lib/stores/ae_events_stores';
import { launcher_loc } from '$lib/stores/ae_events_stores__launcher.svelte';

import Event_launcher_file_cont from './launcher_file_cont.svelte';
import { Image, Images, LoaderCircle, User, Users } from '@lucide/svelte';
import Launcher_presentation_view from './launcher_presentation_view.svelte';
import Launcher_presenter_view_posters from './launcher_presenter_view_posters.svelte';

// Session object
let lq__event_session_obj = $derived(
    liveQuery(() => db_events.session.get(slct__event_session_id))
);

// Session-level files (rare — program PDFs, flyers, etc.)
let lq__event_file_obj_li = $derived(
    liveQuery(async () => {
        if (!slct__event_session_id) return [];
        return await db_events.file
            .where('for_id')
            .equals(slct__event_session_id)
            .reverse()
            .sortBy('created_on');
    })
);

// Presentations sorted alphabetically — typical for poster sessions
let lq__event_presentation_obj_li = $derived(
    liveQuery(async () => {
        if (!slct__event_session_id) return [];
        return await db_events.presentation
            .where('event_session_id')
            .equals(slct__event_session_id)
            .sortBy('name');
    })
);

// All presenters for this session; filtered per card in the template
let lq__event_presenter_obj_li = $derived(
    liveQuery(async () => {
        if (!slct__event_session_id) return [];
        return await db_events.presenter
            .where('event_session_id')
            .equals(slct__event_session_id)
            .sortBy('full_name');
    })
);

// Poster count for the session header badge
let poster_count = $derived($lq__event_presentation_obj_li?.length ?? 0);
</script>

<!--
    Digital Poster session view — touch-first card grid.
    The outer div mirrors the grow/h-full/w-full contract expected by
    +layout.svelte so this slots in as a drop-in replacement for the oral view.
-->
<div
    class="poster_session_view flex h-full w-full flex-col gap-0 overflow-hidden">
    {#if $events_sess.launcher?.loading__session_id_status}
        <span
            class="absolute top-0 right-0 z-10 flex items-center gap-1 p-1 text-sm text-gray-400">
            <LoaderCircle size="1em" class="animate-spin" />
            Loading...
        </span>
    {/if}

    {#if $lq__event_session_obj && $lq__event_session_obj.event_session_id}
        <!-- ── Compact session identity strip ──────────────────────────────── -->
        <header
            class="
                poster_session_header
                border-surface-300 dark:border-surface-600 bg-surface-100/60 dark:bg-surface-800/60 flex
                shrink-0 flex-row
                items-center justify-between gap-2
                border-b-2 px-2
                py-1.5
            ">
            <h2
                class="line-clamp-1 min-w-0 grow text-base font-bold"
                title={$lq__event_session_obj.name}>
                <Images
                    size="1em"
                    class="text-primary-500 mr-1.5 inline opacity-70" />
                {$lq__event_session_obj.name}
            </h2>

            <span class="flex shrink-0 flex-row items-center gap-1.5">
                <!-- Poster count badge -->
                {#if poster_count > 0}
                    <span
                        class="text-surface-500 bg-surface-200 dark:bg-surface-700 rounded-full px-2 py-0.5 font-mono text-xs font-semibold"
                        title="Number of posters in this session">
                        {poster_count}&times;
                    </span>
                {/if}

                <!-- Session code -->
                {#if $lq__event_session_obj.code}
                    <span
                        class="text-surface-400 bg-surface-100 dark:bg-surface-800 border-surface-300 dark:border-surface-600 rounded border px-2 py-0.5 font-mono text-xs font-bold"
                        title="Session code: {$lq__event_session_obj.code}">
                        {$lq__event_session_obj.code}
                    </span>
                {/if}
            </span>
        </header>

        <!-- ── Session-level files (rarely present — program, schedule, etc.) ── -->
        {#if $lq__event_file_obj_li && $lq__event_file_obj_li.length}
            <section
                class="session_resources_strip border-surface-200 dark:border-surface-700 shrink-0 border-b px-2 pt-1 pb-2">
                <p
                    class="text-surface-500 mb-1 text-[10px] font-bold tracking-wider uppercase opacity-60">
                    Session Resources:
                </p>
                <ul class="flex flex-row flex-wrap gap-2">
                    {#each $lq__event_file_obj_li as event_file_obj (event_file_obj.event_file_id)}
                        <li
                            class:hidden={!launcher_loc.current
                                .show_content__hidden_files &&
                                event_file_obj.hide}>
                            <Event_launcher_file_cont
                                event_file_id={event_file_obj.event_file_id}
                                {event_file_obj}
                                hide_created_on={true}
                                show_internal_purpose_files={launcher_loc.current
                                    .show_content__internal_files}
                                show_bak_download={$ae_loc.trusted_access &&
                                    $ae_loc.edit_mode}
                                session_type="poster"
                                open_method="modal"
                                modal_title={$lq__event_session_obj?.name}
                                bind:modal__title={
                                    $events_sess.launcher.modal__title
                                }
                                bind:modal__open_event_file_id={
                                    $events_sess.launcher
                                        .modal__open_event_file_id
                                }
                                bind:modal__event_file_obj={
                                    $events_sess.launcher.modal__event_file_obj
                                } />
                        </li>
                    {/each}
                </ul>
            </section>
        {/if}

        <!-- ── Poster card grid ────────────────────────────────────────────── -->
        {#if $lq__event_presentation_obj_li === undefined}
            <!-- Still resolving from Dexie -->
            <div
                class="flex grow items-center justify-center gap-2 p-10 opacity-40">
                <LoaderCircle size="2em" class="animate-spin" />
                <span>Loading posters…</span>
            </div>
        {:else if $lq__event_presentation_obj_li.length === 0}
            <!-- Loaded but empty -->
            <div
                class="flex grow flex-col items-center justify-center gap-3 p-12 text-center opacity-40">
                <Image size="3em" />
                <p class="text-lg font-medium">
                    No posters in this session yet.
                </p>
            </div>
        {:else}
            <!--
                Grid: 1 col on phone, 2 on tablet (sm), 3 on large desktop (xl).
                Each card is a self-contained poster unit: title → presenter → action.
                overflow-y-auto + grow means the grid scrolls within the available
                height while the session header and resource strip stay fixed above.
            -->
            <ul
                class="
                    poster_card_grid
                    grid
                    grow
                    grid-cols-1
                    gap-3
                    overflow-y-auto
                    p-3
                    sm:grid-cols-2
                    xl:grid-cols-3
                ">
                {#each $lq__event_presentation_obj_li as presentation, i (presentation.event_presentation_id)}
                    {@const presenters_for_this = (
                        $lq__event_presenter_obj_li ?? []
                    ).filter(
                        (p) =>
                            p.event_presentation_id ===
                            presentation.event_presentation_id
                    )}

                    <!--
                        Poster card.
                        min-h-40 prevents very short cards for single-word titles.
                        active:scale-[0.98] gives a tactile press feel on touch.
                    -->
                    <li
                        class="
                            poster_card
                            border-surface-200 dark:border-surface-700 dark:bg-surface-900 hover:border-primary-400
                            dark:hover:border-primary-500
                            relative flex min-h-40
                            flex-col gap-2
                            rounded-xl border
                            bg-white p-3
                            shadow-sm transition-all
                            duration-150 hover:shadow-md
                            active:scale-[0.98]
                            active:shadow-sm
                        ">
                        <!--
                            Top-right badge: prefer the presentation code (e.g. "P-042")
                            as it matches physical poster board numbers; fall back to
                            the 1-based index so there's always a quick reference number.
                        -->
                        <span
                            class="
                                text-primary-600 dark:text-primary-400 bg-primary-50
                                dark:bg-primary-950/60 border-primary-200 dark:border-primary-800 absolute
                                top-2 right-2
                                rounded-full border
                                px-2 py-0.5 font-mono
                                text-xs leading-tight
                                font-bold
                            "
                            title={presentation.code
                                ? 'Poster code: ' + presentation.code
                                : 'Poster #' + (i + 1)}>
                            {presentation.code || '#' + (i + 1)}
                        </span>

                        <!--
                            Presentation / poster title — the primary search target.
                            pr-14 prevents text from running under the badge.
                            line-clamp-3 keeps cards a predictable height while
                            the full text is accessible via the title attribute.
                        -->
                        <h3
                            class="
                                poster_title
                                text-surface-950 dark:text-surface-50
                                line-clamp-3 grow
                                pr-14
                                text-base leading-snug
                                font-bold
                                md:text-lg
                            "
                            title={presentation.name}>
                            {presentation.name}
                        </h3>

                        <!--
                            Presenter(s) — shown below the title so the title
                            gets the first visual hit during scanning.
                            Multiple presenters are listed vertically.
                            WHY given_name === 'Group': some events have a single
                            "Group" presenter whose full name is stored in affiliations.
                        -->
                        {#if presenters_for_this.length}
                            <div class="presenter_info shrink-0 space-y-0.5">
                                {#each presenters_for_this as presenter (presenter.event_presenter_id)}
                                    <p
                                        class="
                                            text-surface-500 dark:text-surface-400 flex flex-row flex-wrap
                                            items-baseline gap-x-1.5 text-sm
                                            leading-snug
                                        ">
                                        {#if presenter.given_name && presenter.given_name !== 'Group'}
                                            <User
                                                size="0.7em"
                                                class="mt-px shrink-0 opacity-50" />
                                            <span
                                                class="text-surface-700 dark:text-surface-300 font-medium"
                                                >{presenter.full_name}</span>
                                            {#if presenter.affiliations}
                                                <span
                                                    class="line-clamp-1 min-w-0 text-xs italic opacity-70"
                                                    title={presenter.affiliations}>
                                                    — {presenter.affiliations}
                                                </span>
                                            {/if}
                                        {:else if presenter.given_name === 'Group'}
                                            <Users
                                                size="0.7em"
                                                class="mt-px shrink-0 opacity-50" />
                                            <span
                                                class="text-surface-700 dark:text-surface-300 font-medium"
                                                >{presenter.affiliations}</span>
                                        {:else}
                                            <span class="text-xs opacity-40"
                                                >—</span>
                                        {/if}
                                    </p>
                                {/each}
                            </div>
                        {/if}

                        <!--
                            File action buttons pushed to the bottom of the card via
                            mt-auto.  Files may be attached at presentation level,
                            presenter level, or both — render both sub-components so
                            neither source is missed.
                        -->
                        <div
                            class="poster_actions mt-auto flex shrink-0 flex-col gap-1 pt-1">
                            <!-- Presentation-level files (the most common attachment point) -->
                            <Launcher_presentation_view
                                lq__event_presentation_obj={presentation}
                                session_type="poster" />

                            <!--
                                Presenter-level files (some events attach the PDF here instead).
                                hide_name=true because the name is already shown above in
                                the presenter_info section; no need to repeat it.
                            -->
                            {#each presenters_for_this as presenter (presenter.event_presenter_id)}
                                <Launcher_presenter_view_posters
                                    lq__event_presenter_obj={presenter}
                                    hide_name={true} />
                            {/each}
                        </div>
                    </li>
                {/each}
            </ul>
        {/if}
    {:else}
        <!-- No session selected or still loading -->
        <div class="flex grow items-center justify-center gap-2 p-8 opacity-40">
            <LoaderCircle size="1em" class="animate-spin" />
            <span>No session selected</span>
        </div>
    {/if}
</div>
