<script>
    import { mapStore } from '$lib/stores/mapStore.js';
    import { getDecayInfo } from '$lib/utils/time.js'
    import { echoMessage } from '$lib/firebase/messages.js'
    import { playEchoTone } from '$lib/utils/sound.js';
    import SharePopover from '$lib/components/SharePopover.svelte';
    import {
        incrementRead,
        incrementEchoed,
        incrementLetGo,
        hasSeenLastChancePrompt,
        markLastChancePromptSeen
    } from '$lib/utils/stats.js';

    let { message } = $props();

    let decay = $derived(
        message ? getDecayInfo(message.createdAt, message.lastEchoAt) : null
    );

    // --- "last chance" state ----------------------------------------------
    // A message is on its genuinely LAST day if it has 1 (or 0) days left
    // AND isn't already expired/faded - daysLeft <= 1 && !isExpired.
    // getDecayInfo() derives daysLeft from lastEchoAt, so a message that was
    // recently echoed already has a much higher daysLeft and won't trigger
    // this - "hasn't been echoed recently enough to have more time" is
    // automatically satisfied whenever this condition is true.
    let isLastChance = $derived(
        decay ? (decay.daysLeft <= 1 && !decay.isExpired) : false
    );

    let echoed = $state(false);

    // one-time "last chance" prompt for the currently-open message
    let showLastChancePrompt = $state(false);

    // tracks which message was open last time this effect ran, so the
    // read-count + prompt logic below only fires once per "open" (not on
    // every reactive re-run while the same message stays selected)
    let previousMessageId = null;

    $effect(() => {
        const currentId = message?.id ?? null;

        if (currentId && currentId !== previousMessageId) {
            // --- engagement stat: a detail view was just opened ----------
            incrementRead();

            // --- one-time "last chance" prompt ----------------------------
            // only show it if this message is CURRENTLY in its last-chance
            // state AND this device hasn't already seen the prompt for this
            // message ID. Marking it seen immediately (rather than waiting
            // for an explicit dismiss) means it won't reappear even if the
            // user navigates away without closing it.
            if (isLastChance && !hasSeenLastChancePrompt(currentId)) {
                showLastChancePrompt = true;
                markLastChancePromptSeen(currentId);
            } else {
                showLastChancePrompt = false;
            }
        }

        if (!currentId) {
            showLastChancePrompt = false; // closed - reset for the next open
        }

        previousMessageId = currentId;
    });

    async function handleEcho() {
        await echoMessage(message.id);
        echoed = true;
        // engagement stat: Echo pressed
        incrementEchoed();
        // taking action dismisses the last-chance prompt for this message
        showLastChancePrompt = false;
        // gentle ascending "thank you" tone confirming the echo went through
        playEchoTone();
    }

    // Let go's behavior is unchanged (just closes the sheet) - this only
    // adds the engagement-stat increment and prompt dismissal alongside it
    function handleLetGo() {
        incrementLetGo();
        showLastChancePrompt = false;
        mapStore.set({ selectedMessage: null, composing: false });
    }

    let startY = 0; // where the swipe started

    function startDrag(e) {
        startY = e.clientY; // remember the starting y position
        window.addEventListener('pointerup', endDrag, { once: true }); // wait for them to let go
    }

    function endDrag(e) {
        const diff = e.clientY - startY; // how far down they dragged
        // if they dragged down more than 60px, close the sheet
        if (diff > 60) {
            mapStore.set({ selectedMessage: null, composing: false });
        }
    }
</script>

<!-- if message exists, sheet is visible -->
<div class="sheet" class:visible={!!message}>
    {#if message}
        <!-- drag this down to close the sheet -->
        <!-- bigger invisible area so the bar is actually easy to grab -->
        <div
            class="handle-area"
            role="button"
            tabindex="0"
            aria-label="drag down to close"
            onpointerdown={startDrag}
        >
            <div class="handle"></div>
        </div>
        <div class="content" class:last-chance={isLastChance}>
            {#if message.imageUrl}
                <img class="message-img" src={message.imageUrl} alt="message attachment" />
            {/if}
            <p class="message-text">{message.text}</p>
            {#if decay}
                {#if isLastChance}
                    <!-- "last chance" framing replaces the normal countdown text -->
                    <p class="meta last-chance-text">this is the last chance to keep this alive</p>
                {:else}
                    <p class="meta">left {decay.daysAgo} days ago. fading in {decay.daysLeft} days.</p>
                {/if}
            {/if}

            {#if showLastChancePrompt}
                <!-- one-time prompt (see stats.js) - gently frames Echo as
                     the way to give this message more time, without being
                     pushy. Dismissible on its own, or implicitly dismissed
                     by pressing Echo/Let go below. -->
                <div class="last-chance-prompt">
                    <p>if this one means something, an echo will keep it here a little longer.</p>
                    <button class="dismiss-prompt" onclick={() => showLastChancePrompt = false} aria-label="dismiss">×</button>
                </div>
            {/if}

            <div class="actions">
                <button class="echo-button"
                class:echoed={echoed}
                onclick={handleEcho}
                disabled={echoed}>
                    {echoed ? 'Echoed' : 'Echo'}
                </button>
                <button class="letgo-button" onclick={handleLetGo}>
                    let go
                </button>
                <!-- share link + QR code popover (see SharePopover.svelte) -->
                <SharePopover {message} />
            </div>
        </div>
    {/if}
</div>

<style>
    .sheet {
        position: fixed;
        bottom: 0;
        left: 0;
        right: 0;
        background: white;
        border-radius: 20px 20px 0 0;
        /* extra 64px of bottom padding = the height of .bottom-nav in
           +page.svelte (z-index 200, above this sheet's 100), which sits on
           top of the sheet's bottom edge and was covering the Echo/Let go
           buttons. pushing the buttons up by that much keeps them clear of
           the nav bar instead of hidden behind it. */
        padding: 1rem 1.5rem calc(2rem + 64px);
        /* flat 2D style for now - shadow removed, paper-style shadows may be added later */
        transform: translateY(100%);
        transition: transform 0.35s cubic-bezier(0.32, 0.72, 0, 1);
        z-index: 100;
    }

    .sheet.visible {
        transform: translateY(0);
    }

    .handle-area {
        display: flex;
        justify-content: center;
        padding: 12px 0;
        margin-bottom: 0.25rem;
        touch-action: none; /* stop the browser from treating the drag as a page scroll */
    }

    .handle {
        width: 40px;
        height: 4px;
        background: #ddd;
        border-radius: 2px;
        /* flat 2D style for now - shadow removed, paper-style shadows may be added later */
    }

    .message-text {
        font-size: 1rem;
        line-height: 1.6;
        margin-bottom: 0.5rem;
        color: #111;
    }

    .meta {
        font-size: 0.75rem;
        color: #999;
        margin-bottom: 1.2rem;
    }

    /* "last chance" treatment - a soft warm peach tint + border, distinct
       from the normal white card but staying within the existing pastel/
       parchment palette. A faint glow (box-shadow) adds a touch of warmth
       without being a jarring "alert" color like red. */
    .content.last-chance {
        background: #fff6ea;
        border: 1px solid #f3dcb8;
        border-radius: 14px;
        padding: 0.9rem;
        margin: -0.25rem -0.25rem 0;
        box-shadow: 0 0 0 4px rgba(243, 184, 92, 0.08);
    }

    /* replaces the normal "fading in X days" meta line when isLastChance */
    .last-chance-text {
        color: #b08a5a;
        font-weight: 500;
    }

    /* one-time prompt shown above the action buttons - same warm palette as
       .content.last-chance, slightly more saturated so it reads as the
       "active" element within the card */
    .last-chance-prompt {
        display: flex;
        align-items: center;
        justify-content: space-between;
        gap: 0.5rem;
        background: #fdf0db;
        border: 1px solid #f3dcb8;
        border-radius: 10px;
        padding: 0.6rem 0.75rem;
        margin-bottom: 0.9rem;
        font-size: 0.8rem;
        color: #9c7240;
        line-height: 1.5;
    }

    .last-chance-prompt p {
        margin: 0;
    }

    .dismiss-prompt {
        background: none;
        border: none;
        color: #c4a37a;
        font-size: 1rem;
        line-height: 1;
        cursor: pointer;
        padding: 0;
        flex-shrink: 0;
    }

    .actions {
        display: flex;
        gap: 0.75rem;
    }

    .echo-button {
        flex: 1;
        padding: 0.75rem;
        background: #111;
        color: white;
        border: none;
        border-radius: 10px;
        font-size: 0.95rem;
        cursor: pointer;
        /* flat 2D style for now - shadow removed, paper-style shadows may be added later */
    }

    .letgo-button {
        flex: 1;
        padding: 0.75rem;
        background: transparent;
        color: #111;
        border: 1.5px solid #ddd;
        border-radius: 10px;
        font-size: 0.95rem;
        cursor: pointer;
        /* flat 2D style for now - shadow removed, paper-style shadows may be added later */
    }

    .echo-button.echoed {
        background: #4ecdc4;
        animation: pulsate 1.5s ease-in-out 3;
    }

    .message-img{
        width: 100%;
        max-height: 220px;
        object-fit: cover;
        border-radius: 12px;
        margin-bottom: 0.75rem;
        /* flat 2D style for now - shadow removed, paper-style shadows may be added later */
    }

    @keyframes pulsate {
        0%, 100% {box-shadow: 0 0 0 0 rgba(78,205,196,0.4); }
        50% {box-shadow: 0 0 0 12px rgba(78, 205, 196, 0);}
    }
</style>