<?php
/**
 * Reusable Floating Music Player Component (G007)
 * Location: app/views/components/music_player.php
 *
 * Variables expected:
 *   $musicFileUrl   — string — Public URL to stream the track.
 *   $musicCoverUrl  — string — Public URL to the cover art.
 *   $songTitle      — string — Title of the track.
 *   $songArtist     — string — Name of the artist.
 *   $autoplay       — bool   — Should track start automatically.
 *   $loop           — bool   <!-- Should track loop indefinitely. -->
 *   $startMinimized — bool   — Start player minimized or expanded.
 *   $volume         — int    — Initial volume (0 - 100).
 *
 * @package Inveetaire
 * @ref     G007
 */

$songTitleEsc  = escape_html($songTitle ?: 'Wedding Song');
$songArtistEsc = escape_html($songArtist ?: '');
$autoplayVal   = $autoplay ? 'true' : 'false';
$loopVal       = $loop ? 'true' : 'false';
$minimizedVal  = 'true'; // Default initial state = Close (minimized)
$volumeVal     = max(0, min(100, $volume)) / 100;
?>

<div id="music-player-container" 
     class="transition-all duration-300 ease-in-out font-sans-modern"
     style="display: none; position: fixed !important; bottom: 24px !important; right: 24px !important; top: auto !important; left: auto !important; z-index: 40 !important;">
    
    <!-- ── EXPANDED PLAYER STATE ── -->
    <div id="mp-card" class="hidden bg-slate-900 text-white backdrop-blur-md border border-slate-800 shadow-2xl rounded-xl p-3 w-60 sm:w-64 flex flex-col gap-2 relative overflow-hidden transition-all duration-300">
        
        <!-- Top Horizontal Navigation Bar (Text Actions with Hover: Mute & Minimize) -->
        <div class="flex items-center justify-between border-b border-slate-800/80 pb-2">
            <!-- Mute / Unmute Text Button -->
            <button id="mp-mute-btn" 
                    class="px-2.5 py-1 rounded-lg bg-slate-800/80 text-slate-300 hover:text-white hover:bg-slate-700 border border-slate-700/50 text-[10px] font-medium tracking-wide transition-all active:scale-95 cursor-pointer"
                    aria-label="Mute or Unmute"
                    title="Mute / Unmute">
                <span id="mp-mute-text">Mute</span>
            </button>

            <!-- Minimize Text Button -->
            <button id="mp-minimize-btn" 
                    class="px-2.5 py-1 rounded-lg bg-slate-800/80 text-slate-400 hover:text-white hover:bg-slate-700 border border-slate-700/50 text-[10px] font-medium tracking-wide transition-all active:scale-95 cursor-pointer"
                    title="Minimize player">
                Minimize
            </button>
        </div>

        <!-- Bottom: Song info & progress bar (Clean layout, timestamps removed) -->
        <div class="space-y-1.5 pt-0.5">
            <!-- Song info -->
            <div>
                <div class="overflow-hidden whitespace-nowrap text-ellipsis relative" style="max-width: 210px;">
                    <div id="mp-song-title" class="text-[11px] font-bold text-white uppercase tracking-wide truncate">
                        <?= $songTitleEsc ?>
                    </div>
                </div>
                <?php if ($songArtistEsc !== ''): ?>
                    <p class="text-[9px] text-slate-400 truncate mt-0.5"><?= $songArtistEsc ?></p>
                <?php endif; ?>
            </div>

            <!-- Progress bar -->
            <div class="w-full bg-slate-800 h-1 rounded-full cursor-pointer overflow-hidden relative" id="mp-progress-bar">
                <div id="mp-progress-fill" class="bg-white h-full w-0 transition-all duration-100"></div>
            </div>
        </div>

    </div>

    <!-- ── MINIMIZED PLAYER STATE (PERFECT ROUND CIRCLE BUTTON) ── -->
    <button id="mp-minimized-disk" 
            class="w-12 h-12 aspect-square flex-shrink-0 rounded-full bg-slate-900 text-white border border-slate-700/80 shadow-2xl flex items-center justify-center hover:scale-105 active:scale-95 transition-all group relative overflow-hidden"
            style="width: 48px !important; height: 48px !important; min-width: 48px !important; min-height: 48px !important; max-width: 48px !important; max-height: 48px !important; border-radius: 9999px !important;"
            aria-label="Music Player">
        
        <?php if (!empty($musicCoverUrl)): ?>
            <img id="mp-min-cover-img" src="<?= escape_html($musicCoverUrl) ?>" alt="Album Cover" class="w-full h-full object-cover rounded-full">
        <?php else: ?>
            <div class="w-full h-full bg-slate-900 flex items-center justify-center text-white rounded-full">
                <i class="fa-solid fa-music text-base text-white"></i>
            </div>
        <?php endif; ?>

        <!-- Floating White Music Note Icon Overlay on Hover -->
        <div class="absolute inset-0 bg-slate-950/60 opacity-0 group-hover:opacity-100 transition-opacity flex items-center justify-center text-white rounded-full">
            <i class="fa-solid fa-music text-sm text-white"></i>
        </div>
    </button>

</div>

<style>
/* CSS Animations for Album Rotation */
.mp-rotate-active {
    animation: mp-spin-album 6s linear infinite;
}
@keyframes mp-spin-album {
    from { transform: rotate(0deg); }
    to { transform: rotate(360deg); }
}

/* Auto-hide floating music player when any modal pop-up is active */
body:has(#pass-modal:not(.hidden)) #music-player-container,
body:has(#qris-modal:not(.hidden)) #music-player-container {
    display: none !important;
}
</style>

<script>
(function () {
    "use strict";

    const TRACK_URL   = <?= json_encode($musicFileUrl) ?>;
    const AUTOPLAY    = <?= json_encode((bool) ($musicAutoplay ?? $autoplay ?? true)) ?>;
    const LOOP        = <?= json_encode((bool) ($musicLoop ?? $loop ?? true)) ?>;
    const VOLUME      = <?= json_encode($volumeVal) ?>;
    const GUEST_TOKEN = <?= json_encode($guestToken ?? 'guest') ?>;

    if (!TRACK_URL) return;

    // DOM Elements
    const container      = document.getElementById('music-player-container');
    const cardState      = document.getElementById('mp-card');
    const minState       = document.getElementById('mp-minimized-disk');
    const minimizeBtn    = document.getElementById('mp-minimize-btn');
    const muteBtn        = document.getElementById('mp-mute-btn');
    const muteText       = document.getElementById('mp-mute-text');
    const progressBar    = document.getElementById('mp-progress-bar');
    const progressFill   = document.getElementById('mp-progress-fill');

    // Album Cover Arts
    const coverImgs      = [
        document.getElementById('mp-cover-img'),
        document.getElementById('mp-min-cover-img')
    ].filter(el => el !== null);

    // Audio State Variables
    let audio = null;
    let isPlaying = false;

    // Storage Keys
    const STORAGE_TIME_KEY = `mp_time_${GUEST_TOKEN}`;
    const STORAGE_PLAY_KEY = `mp_playing_${GUEST_TOKEN}`;
    const STORAGE_MIN_KEY  = `mp_minimized_${GUEST_TOKEN}`;

    function initAudio() {
        if (audio) return;

        audio = new Audio();
        audio.src = TRACK_URL;
        audio.preload = "metadata";
        audio.loop = LOOP;
        audio.volume = VOLUME;

        const savedTime = sessionStorage.getItem(STORAGE_TIME_KEY);
        if (savedTime !== null) {
            audio.currentTime = parseFloat(savedTime);
        }

        // Event listeners
        audio.addEventListener('play', () => {
            isPlaying = true;
            togglePlayUI(true);
            sessionStorage.setItem(STORAGE_PLAY_KEY, 'true');
        });

        audio.addEventListener('pause', () => {
            isPlaying = false;
            togglePlayUI(false);
            sessionStorage.setItem(STORAGE_PLAY_KEY, 'false');
        });

        audio.addEventListener('timeupdate', () => {
            sessionStorage.setItem(STORAGE_TIME_KEY, audio.currentTime);
            if (audio.duration && progressFill) {
                const percent = (audio.currentTime / audio.duration) * 100;
                progressFill.style.width = percent + '%';
            }
        });

        audio.addEventListener('ended', () => {
            if (!LOOP) {
                isPlaying = false;
                togglePlayUI(false);
            }
        });
    }

    function togglePlayUI(playing) {
        coverImgs.forEach(img => {
            if (playing) img.classList.add('mp-rotate-active');
            else img.classList.remove('mp-rotate-active');
        });
    }

    function setMinimizedState(minimized) {
        if (minimized) {
            if (cardState) cardState.classList.add('hidden');
            if (minState) minState.classList.remove('hidden');
            sessionStorage.setItem(STORAGE_MIN_KEY, 'true');
        } else {
            if (minState) minState.classList.add('hidden');
            if (cardState) cardState.classList.remove('hidden');
            sessionStorage.setItem(STORAGE_MIN_KEY, 'false');
        }
    }

    function playAudio() {
        initAudio();
        audio.play()
            .then(() => {
                isPlaying = true;
            })
            .catch(err => {
                console.log("Music Engine: Autoplay blocked, waiting for guest interaction.");
                togglePlayUI(false);
                isPlaying = false;
                bindInteractionPlay();
            });
    }

    let interactionBound = false;
    function bindInteractionPlay() {
        if (interactionBound) return;
        interactionBound = true;

        const startPlaybackOnInteraction = () => {
            if (!isPlaying) {
                playAudio();
            }
            document.removeEventListener('click', startPlaybackOnInteraction);
            document.removeEventListener('touchstart', startPlaybackOnInteraction);
            document.removeEventListener('scroll', startPlaybackOnInteraction);
            interactionBound = false;
        };

        document.addEventListener('click', startPlaybackOnInteraction);
        document.addEventListener('touchstart', startPlaybackOnInteraction);
        document.addEventListener('scroll', startPlaybackOnInteraction, { passive: true });
    }

    function toggleMuteUI(muted) {
        if (muteText) {
            muteText.textContent = muted ? 'Unmute' : 'Mute';
        }
    }

    if (muteBtn) {
        muteBtn.onclick = (e) => {
            e.stopPropagation();
            if (!audio) initAudio();
            audio.muted = !audio.muted;
            toggleMuteUI(audio.muted);
        };
    }

    if (minimizeBtn) {
        minimizeBtn.onclick = (e) => {
            e.stopPropagation();
            setMinimizedState(true);
        };
    }

    if (minState) {
        minState.onclick = (e) => {
            e.stopPropagation();
            setMinimizedState(false);
        };
    }

    if (progressBar) {
        progressBar.onclick = (e) => {
            if (!audio || !audio.duration) return;
            const rect = progressBar.getBoundingClientRect();
            const clickX = e.clientX - rect.left;
            const width = rect.width;
            const percent = clickX / width;
            audio.currentTime = percent * audio.duration;
        };
    }

    // ── Startup Sequence ─────────────────────────────────────────────────────
    window.addEventListener('DOMContentLoaded', () => {
        if (container) container.style.display = 'block';

        // 1. Force starting layout state to CLOSED (minimized) on initial page load
        setMinimizedState(true);

        // 2. Resolve starting playback state
        const savedPlay = sessionStorage.getItem(STORAGE_PLAY_KEY);
        if (savedPlay === 'true') {
            playAudio();
        } else if (savedPlay === null && AUTOPLAY) {
            playAudio();
        } else {
            // Started paused, register interaction triggers in case they click play later
            initAudio();
        }
    });

})();
</script>
