<!DOCTYPE html>
<html lang="id">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
    <meta name="apple-mobile-web-app-capable" content="yes">
    <meta name="apple-mobile-web-app-status-bar-style" content="black-translucent">
    <title>Franchise Game — Papan Jawara</title>
    <link rel="stylesheet" href="../assets/css/game-layout.css">
    <style>
        #game-container canvas {
            z-index: 1;
            image-rendering: pixelated;
            image-rendering: crisp-edges;
        }
    </style>
</head>

<body>

    <div id="desktop-wrapper">
        <div id="mobile-frame">
            <div id="status-bar">
                <span id="clock">00:00</span>
                <span>&#11044;&#11044;&#11044;</span>
            </div>
            <div id="game-container"></div>
        </div>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/phaser@3.88.2/dist/phaser.min.js"></script>

    <script>
        const GAME_WIDTH = 360;
        const GAME_HEIGHT = 760;

        // =====================================================
        //  HELPER — Shimmer pada PNG icon (BitmapMask)
        // =====================================================
        function addIconShimmer(scene, img, delay) {
            const w = img.displayWidth;
            const h = img.displayHeight;
            const shimW = w * 0.32;
            const slant = h * 0.65;

            // Create BitmapMask directly from the target image (conforms to png transparency shape)
            const bitmapMask = img.createBitmapMask();

            const shimGfx = scene.add.graphics();
            shimGfx.setMask(bitmapMask);

            const animData = { progress: 0 };
            const tween = scene.tweens.add({
                targets: animData,
                progress: 1,
                duration: 600,
                ease: 'Quad.easeInOut',
                delay: delay || 0,
                repeat: -1,
                repeatDelay: 2600,
                onUpdate: () => {
                    if (!img.active) return;

                    let wx = img.x;
                    let wy = img.y;
                    let parent = img.parentContainer;
                    while (parent) {
                        wx += parent.x;
                        wy += parent.y;
                        parent = parent.parentContainer;
                    }

                    const ix = wx - w / 2;
                    const iy = wy - h / 2;

                    const startX = ix - shimW - slant * 2;
                    const endX = ix + w + shimW;
                    const currentX = startX + (endX - startX) * animData.progress;

                    shimGfx.clear();
                    shimGfx.fillStyle(0xffffff, 0.55);
                    shimGfx.fillPoints([
                        { x: currentX, y: iy },
                        { x: currentX + shimW, y: iy },
                        { x: currentX + shimW + slant * 2, y: iy + h },
                        { x: currentX + slant * 2, y: iy + h },
                    ], true);
                },
                onRepeat: () => shimGfx.clear()
            });

            // Clean up graphics and stop tween when the image is destroyed
            img.once('destroy', () => {
                if (tween) tween.stop();
                if (shimGfx) shimGfx.destroy();
            });
        }

        // =====================================================
        //  LEADERBOARD SCENE CLASS
        // =====================================================
        class LeaderboardScene extends Phaser.Scene {
            constructor() { super({ key: 'LeaderboardScene' }); }

            preload() {
                this.load.image('bgmenu', '../assets/image/bg/bgmenu.jpg');
                this.load.image('koin', '../assets/image/ui/koin.png');
                this.load.image('back', '../assets/image/ui/back.png');
                this.load.image('piala', '../assets/image/ui/piala.png');
            }

            create() {
                const W = this.scale.width;
                const H = this.scale.height;
                const cx = W / 2;

                this.cameras.main.fadeIn(500, 240, 253, 244);

                // ---- Background cover ----
                const bg = this.add.image(cx, H / 2, 'bgmenu');
                const scaleX_bg = W / bg.width;
                const scaleY_bg = H / bg.height;
                bg.setScale(Math.max(scaleX_bg, scaleY_bg));

                // =============================================
                //  HEADER BAR & NAV
                // =============================================
                // ---- Tombol Kembali (Top Left) ----
                const backBtnContainer = this.add.container(38, 34);
                backBtnContainer.setSize(48, 48);
                backBtnContainer.setInteractive({ useHandCursor: true });

                const backBtnBg = this.add.graphics();
                function drawBackBtnBg(fillAlpha, lineAlpha, lineWidth) {
                    backBtnBg.clear();
                    backBtnBg.fillStyle(0xffffff, fillAlpha);
                    backBtnBg.lineStyle(lineWidth, 0xffffff, lineAlpha);
                    backBtnBg.fillRoundedRect(-24, -24, 48, 48, 8);
                    backBtnBg.strokeRoundedRect(-24, -24, 48, 48, 8);
                }
                drawBackBtnBg(0.2, 0.4, 2);
                backBtnContainer.add(backBtnBg);

                const backIcon = this.add.image(0, 0, 'back').setDisplaySize(32, 32);
                backBtnContainer.add(backIcon);

                // Action klik kembali
                backBtnContainer.on('pointerdown', () => {
                    this.tweens.add({
                        targets: backBtnContainer,
                        scaleX: 0.8, scaleY: 0.8,
                        duration: 80, ease: 'Power2',
                        yoyo: true,
                        onComplete: () => {
                            this.cameras.main.fadeOut(300, 240, 253, 244);
                            this.cameras.main.once('camerafadeoutcomplete', () => {
                                window.location.href = '../mainmenu.php';
                            });
                        }
                    });
                });

                // Hover effect
                backBtnContainer.on('pointerover', () => {
                    drawBackBtnBg(0.35, 0.7, 2.5);
                    this.tweens.add({ targets: backBtnContainer, scaleX: 1.05, scaleY: 1.05, duration: 90, ease: 'Power2' });
                });
                backBtnContainer.on('pointerout', () => {
                    drawBackBtnBg(0.2, 0.4, 2);
                    this.tweens.add({ targets: backBtnContainer, scaleX: 1, scaleY: 1, duration: 90, ease: 'Power2' });
                });

                // Shimmer pada tombol kembali kotak
                const backMask = this.make.graphics({ add: false });
                backMask.fillStyle(0xffffff);
                backMask.fillRoundedRect(38 - 24, 34 - 24, 48, 48, 8);

                const backShimGfx = this.add.graphics();
                backShimGfx.setMask(backMask.createGeometryMask());

                const backWsp = { v: 14 - 15 - 15 };
                this.tweens.add({
                    targets: backWsp,
                    v: 62 + 15,
                    duration: 650,
                    ease: 'Quad.easeInOut',
                    delay: Math.random() * 500 + 1000,
                    repeat: -1,
                    repeatDelay: 2500,
                    onUpdate: () => {
                        backShimGfx.clear();
                        backShimGfx.fillStyle(0xffffff, 0.45);
                        backShimGfx.fillPoints([
                            { x: backWsp.v, y: 34 - 24 },
                            { x: backWsp.v + 15, y: 34 - 24 },
                            { x: backWsp.v + 15 + 15, y: 34 + 24 },
                            { x: backWsp.v + 15, y: 34 + 24 },
                        ], true);
                    },
                    onRepeat: () => backShimGfx.clear()
                });

                // =============================================
                //  TOP RIGHT: KOIN
                // =============================================
                const BAR_Y = 34;
                const COIN_ICON_X = W - 78;

                const coinImgGlobal = this.add.image(COIN_ICON_X, BAR_Y, 'koin')
                    .setDisplaySize(36, 36)
                    .setInteractive({ useHandCursor: true });

                coinImgGlobal.on('pointerdown', () => {
                    this.tweens.add({
                        targets: coinImgGlobal,
                        scaleX: 0.7, scaleY: 0.7,
                        duration: 80, ease: 'Power2',
                        yoyo: true
                    });
                });

                let coinCount = parseInt(localStorage.getItem('coins') || '100000');

                const coinText = this.add.text(COIN_ICON_X + 22, BAR_Y + 1, String(coinCount), {
                    fontFamily: '"Pixelify Sans", monospace',
                    fontSize: '13px',
                    fontStyle: 'bold',
                    color: '#FFD700',
                    stroke: '#15803d',
                    strokeThickness: 3
                }).setOrigin(0, 0.5);

                addIconShimmer(this, coinImgGlobal, 1100);

                // =============================================
                //  TITLE BANNER
                // =============================================
                this.add.text(cx, 110, '✦ PAPAN JAWARA ✦', {
                    fontFamily: '"Press Start 2P", monospace',
                    fontSize: '18px',
                    fontStyle: 'bold',
                    color: '#22c55e',
                    stroke: '#ffffff',
                    strokeThickness: 4
                }).setOrigin(0.5);

                // =============================================
                //  LEADERBOARD PANEL
                // =============================================
                const cardContainer = this.add.container(cx, 420);
                const cW = W - 44;
                const cH = 460;

                const cardBg = this.add.graphics();
                const radius = 20;
                const shadowOffset = 5;

                // Shadow
                cardBg.fillStyle(0x15803d, 0.3);
                cardBg.fillRoundedRect(-cW / 2 + shadowOffset, -cH / 2 + shadowOffset, cW, cH, radius);
                // Main panel
                cardBg.fillStyle(0xffffff, 1);
                cardBg.lineStyle(4, 0x22c55e, 1);
                cardBg.fillRoundedRect(-cW / 2, -cH / 2, cW, cH, radius);
                cardBg.strokeRoundedRect(-cW / 2, -cH / 2, cW, cH, radius);

                cardContainer.add(cardBg);

                // Leaderboard Data List (15 players, wins and losses)
                const customUserName = localStorage.getItem('jalurName') || 'Sanak Kuansing';
                const leaderboardData = [
                    { name: 'Datuk Rajo Lelo', wins: 48, losses: 8, isUser: false, rank: 1 },
                    { name: `${customUserName} (Kamu)`, wins: 42, losses: 12, isUser: true, rank: 2 },
                    { name: 'Sutan Bagindo', wins: 38, losses: 10, isUser: false, rank: 3 },
                    { name: 'Bujang Selamat', wins: 32, losses: 15, isUser: false, rank: 4 },
                    { name: 'Malin Kundang', wins: 25, losses: 22, isUser: false, rank: 5 },
                    { name: 'Rajo Dubalang', wins: 22, losses: 9, isUser: false, rank: 6 },
                    { name: 'Panglima Alang', wins: 20, losses: 12, isUser: false, rank: 7 },
                    { name: 'Datuk Bandaro', wins: 18, losses: 14, isUser: false, rank: 8 },
                    { name: 'Sutan Muda', wins: 17, losses: 11, isUser: false, rank: 9 },
                    { name: 'Bujang Juara', wins: 15, losses: 16, isUser: false, rank: 10 },
                    { name: 'Rajo Melayu', wins: 14, losses: 15, isUser: false, rank: 11 },
                    { name: 'Datuk Majo Lelo', wins: 12, losses: 18, isUser: false, rank: 12 },
                    { name: 'Sutan Sari', wins: 10, losses: 14, isUser: false, rank: 13 },
                    { name: 'Bujang Senang', wins: 9, losses: 17, isUser: false, rank: 14 },
                    { name: 'Malin Deman', wins: 8, losses: 20, isUser: false, rank: 15 }
                ];

                // Mask for scrollable list visible area (inside card panel)
                const listMaskGfx = this.make.graphics({ add: false });
                listMaskGfx.fillStyle(0xffffff, 1);
                listMaskGfx.fillRoundedRect(cx - cW / 2 + 6, 420 - cH / 2 + 20, cW - 12, cH - 40, 12);
                const listMask = listMaskGfx.createGeometryMask();

                // Create Container for scrollable items
                const listContainer = this.add.container(0, 0);
                listContainer.setMask(listMask);
                cardContainer.add(listContainer);

                const rowHeight = 72;
                const startYPos = -200;

                leaderboardData.forEach((player, i) => {
                    const rowY = startYPos + 32 + i * rowHeight;

                    // Row background card
                    const rowBg = this.add.graphics();
                    rowBg.fillStyle(player.isUser ? 0xf0fdf4 : 0xf9fafb, 1);
                    rowBg.lineStyle(2, player.isUser ? 0x22c55e : 0xe5e7eb, 1);
                    rowBg.fillRoundedRect(-cW / 2 + 16, rowY - 28, cW - 32, 56, 12);
                    rowBg.strokeRoundedRect(-cW / 2 + 16, rowY - 28, cW - 32, 56, 12);
                    listContainer.add(rowBg);

                    // Rank Trophy Icon or Number
                    if (player.rank <= 3) {
                        const trophy = this.add.image(-cW / 2 + 42, rowY, 'piala')
                            .setDisplaySize(24, 24)
                            .setOrigin(0.5);

                        // Color tints for Gold, Silver, Bronze
                        if (player.rank === 1) trophy.setTint(0xffd700);
                        else if (player.rank === 2) trophy.setTint(0xc0c0c0);
                        else if (player.rank === 3) trophy.setTint(0xcd7f32);

                        listContainer.add(trophy);
                        addIconShimmer(this, trophy, 400 + i * 300);
                    } else {
                        const rankTxt = this.add.text(-cW / 2 + 42, rowY, String(player.rank), {
                            fontFamily: '"Press Start 2P", monospace',
                            fontSize: '11px',
                            color: '#9ca3af'
                        }).setOrigin(0.5);
                        listContainer.add(rankTxt);
                    }

                    // Player details text
                    const nameTxt = this.add.text(-cW / 2 + 70, rowY - 10, player.name, {
                        fontFamily: '"Pixelify Sans", monospace',
                        fontSize: '14px',
                        fontStyle: 'bold',
                        color: player.isUser ? '#15803d' : '#374151'
                    }).setOrigin(0, 0.5);
                    listContainer.add(nameTxt);

                    const statsTxt = this.add.text(-cW / 2 + 70, rowY + 10, `${player.wins} Menang  •  ${player.losses} Kalah`, {
                        fontFamily: '"Pixelify Sans", monospace',
                        fontSize: '11px',
                        fontStyle: 'bold',
                        color: player.isUser ? '#16a34a' : '#6b7280'
                    }).setOrigin(0, 0.5);
                    listContainer.add(statsTxt);

                    // Shimmer specifically for player row border highlighting
                    if (player.isUser) {
                        this.tweens.add({
                            targets: rowBg,
                            alpha: 0.82,
                            duration: 1000,
                            yoyo: true,
                            repeat: -1,
                            ease: 'Sine.easeInOut'
                        });
                    }
                });

                // Scrolling variables & constraints
                let isDragging = false;
                let startPointerY = 0;
                let startScrollY = 0;
                let scrollY = 0;

                const visibleHeight = cH - 40;
                const contentHeight = leaderboardData.length * rowHeight;
                const minScroll = visibleHeight - contentHeight; // 420 - 1080 = -660
                const maxScroll = 0;

                // Scrollbar
                const scrollbarGfx = this.add.graphics();
                cardContainer.add(scrollbarGfx);

                const drawScrollbar = () => {
                    scrollbarGfx.clear();
                    const trackX = cW / 2 - 10;
                    const trackY = startYPos + 10;
                    const trackH = cH - 60;

                    // Track background
                    scrollbarGfx.fillStyle(0xe5e7eb, 0.4);
                    scrollbarGfx.fillRoundedRect(trackX - 2, trackY, 4, trackH, 2);

                    // Handle height
                    const handleH = Math.max(30, (visibleHeight / contentHeight) * trackH);

                    // Handle position based on scroll ratio
                    const scrollRatio = scrollY / minScroll;
                    const handleY = trackY + scrollRatio * (trackH - handleH);

                    scrollbarGfx.fillStyle(0x22c55e, 1);
                    scrollbarGfx.fillRoundedRect(trackX - 3, handleY, 6, handleH, 3);
                };

                // Draw initial scrollbar
                drawScrollbar();

                // Drag events on the list area
                this.input.on('pointerdown', (pointer) => {
                    if (pointer.x > cx - cW / 2 && pointer.x < cx + cW / 2 &&
                        pointer.y > 420 - cH / 2 + 20 && pointer.y < 420 + cH / 2 - 20) {
                        isDragging = true;
                        startPointerY = pointer.y;
                        startScrollY = scrollY;
                    }
                });

                this.input.on('pointermove', (pointer) => {
                    if (!isDragging) return;
                    const deltaY = pointer.y - startPointerY;
                    scrollY = startScrollY + deltaY;

                    // Clamp
                    scrollY = Phaser.Math.Clamp(scrollY, minScroll, maxScroll);
                    listContainer.y = scrollY;
                    drawScrollbar();
                });

                this.input.on('pointerup', () => {
                    isDragging = false;
                });

                // Mouse wheel scrolling support
                this.input.on('wheel', (pointer, gameObjects, deltaX, deltaY) => {
                    scrollY -= deltaY * 0.4;
                    scrollY = Phaser.Math.Clamp(scrollY, minScroll, maxScroll);
                    listContainer.y = scrollY;
                    drawScrollbar();
                });

                // Intro Animation for card container
                cardContainer.setScale(0);
                this.tweens.add({
                    targets: cardContainer,
                    scaleX: 1, scaleY: 1,
                    duration: 450,
                    ease: 'Back.easeOut',
                    delay: 150
                });

                // =============================================
                //  FOOTER TEXT
                // =============================================
                this.add.text(cx, H - 24, 'v1.0.0  |  Papan Jawara Pacu Jalur', {
                    fontFamily: '"Pixelify Sans", monospace',
                    fontSize: '11px',
                    fontStyle: 'bold',
                    color: 'rgba(21, 128, 61, 0.45)'
                }).setOrigin(0.5);
            }
        }

        // =====================================================
        //  INIT PHASER GAME
        // =====================================================
        const game = new Phaser.Game({
            type: Phaser.AUTO,
            width: GAME_WIDTH,
            height: GAME_HEIGHT,
            backgroundColor: '#f0fdf4',
            parent: 'game-container',
            pixelArt: true,
            scene: [LeaderboardScene],
            scale: {
                mode: Phaser.Scale.RESIZE,
                autoCenter: Phaser.Scale.CENTER_BOTH
            }
        });
    </script>

    <script src="../assets/js/game-layout.js?v=<?= time() ?>"></script>
</body>

</html>