<!DOCTYPE html>
<html lang="ja">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=no">
    <title>カロッツェリア・ヒストリー・スロット</title>
    <link rel="stylesheet" href="style.css">
</head>
<body>

    <div id="game-container">
        <header class="header">
            <h1>HISTORY SLOT</h1>
            <p>あの頃の憧れが、今、蘇る。</p>
        </header>
        
        <div id="slot-machine">
            <div class="reel" id="reel1"><div class="reel-inner"></div></div>
            <div class="reel" id="reel2"><div class="reel-inner"></div></div>
            <div class="reel" id="reel3"><div class="reel-inner"></div></div>
        </div>

        <div id="controls">
            <button id="spin-button" class="state-spin">SPIN!</button>
        </div>
    </div>

    <div id="modal">
        <div class="modal-content">
            <h2 id="modal-prize-name"></h2>
            <p id="modal-prize-item"></p>
            <img id="modal-item-image" src="" alt="景品画像">
            <p id="modal-item-description"></p>
            <div class="share-buttons">
                <a id="twitter-share-button" href="#" target="_blank" class="share-button twitter-share">Xでシェア</a>
                <a id="line-share-button" href="#" target="_blank" class="share-button line-share">LINEで教える</a>
            </div>
            <button id="modal-close-button">閉じる</button>
        </div>
    </div>

    <script>
    document.addEventListener('DOMContentLoaded', () => {
        // --- データ定義 ---
        // 画像は軽量なSVGをData URIとして埋め込み、外部リクエストを無くす
        const ITEMS = [
            { id: 'lonesome_carboy', name: 'ロンサムカーボーイ', image: 'data:image/svg+xml;utf8,<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 100 100"><rect width="100" height="100" fill="%23eee"/><rect x="10" y="20" width="80" height="50" fill="%23444" rx="5"/><circle cx="32" cy="45" r="12" fill="%23eee"/><circle cx="68" cy="45" r="12" fill="%23eee"/><path d="M32 45 L25 38 M32 45 L39 38 M68 45 L61 38 M68 45 L75 38" stroke="%23888" stroke-width="2"/><rect x="25" y="50" width="50" height="10" fill="%23888" rx="2"/><text x="50" y="85" font-size="12" text-anchor="middle" fill="%23333">TS-X9</text></svg>', description: '1980年代、クルマに本格オーディオ文化を根付かせた伝説のシリーズ。そのサウンドとデザインは、当時の若者の心を鷲掴みにした。' },
            { id: 'deh_p999', name: 'DEH-P999', image: 'data:image/svg+xml;utf8,<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 100 100"><rect width="100" height="100" fill="%23ddd"/><rect x="10" y="10" width="80" height="80" fill="%23111" rx="5"/><rect x="15" y="30" width="70" height="40" fill="%2300e5ff" opacity="0.2"/><text x="50" y="55" font-family="Orbitron" font-size="14" fill="%2300e5ff" text-anchor="middle">Carrozzeria</text><circle cx="80" cy="80" r="5" fill="%23555"/></svg>', description: '1999年発売。世界初のOELディスプレイを搭載し、美しいイルミネーションで一世を風靡した伝説の1DINヘッドユニット。' },
            { id: 'cyber_navi_1st', name: '初代サイバーナビ', image: 'data:image/svg+xml;utf8,<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 100 100"><rect width="100" height="100" fill="%23ccc"/><path d="M10 10 L50 90 L90 10 Z" fill="%2333C4FF" opacity="0.5"/><path d="M50 50 L20 20 M50 50 L80 20 M50 50 L50 80" stroke="%23fff" stroke-width="3"/><circle cx="50" cy="50" r="8" fill="red" stroke="white" stroke-width="2"/><text x="50" y="25" text-anchor="middle" font-weight="bold" fill="%23111">AVIC</text></svg>', description: '1997年、DVD-ROMを搭載しナビの常識を覆した初代モデル。エンターテインメントとナビゲーションを高次元で融合させた。' },
            { id: 'carrozzeria_x', name: 'カロッツェリアX', image: 'data:image/svg+xml;utf8,<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 100 100"><rect width="100" height="100" fill="%23222"/><text x="50" y="68" font-family="Orbitron" font-size="80" fill="%23FFC300" text-anchor="middle">X</text><rect x="10" y="48" width="80" height="4" fill="%23FFC300" opacity="0.7"/></svg>', description: '音質を極限まで追求するコンペティターのために生まれたハイエンドシリーズ。妥協なき設計思想が最高の音響空間を創造する。' },
            { id: 'air_navi', name: 'エアーナビ', image: 'data:image/svg+xml;utf8,<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 100 100"><rect width="100" height="100" fill="%23eee"/><path d="M50 90 L40 50 L60 50 Z" fill="%239A33FF"/><path d="M50 50 L20 20 M50 50 Q70 30 80 20 M50 50 Q30 30 20 20" stroke="%239A33FF" stroke-width="4" fill="none" stroke-linecap="round"/></svg>', description: '通信機能を活用し、いつでも最新情報にアクセスできる「スマートループ」を搭載。ポータブルナビの可能性を大きく広げた。' }
        ];

        const PRIZES = {
            'lonesome_carboy': { rank: '特賞 (Wチャンス)', prize: '最新サイバーナビ or ハイエンドスピーカー', matchedItem: ITEMS[0] },
            'carrozzeria_x': { rank: '1等', prize: '限定復刻デザインTシャツ', matchedItem: ITEMS[3] },
            'deh_p999': { rank: '2等', prize: '限定復刻ホログラムステッカーセット', matchedItem: ITEMS[1] },
            'cyber_navi_1st': { rank: '3等', prize: '歴代名機 デジタルカタログ壁紙セット', matchedItem: ITEMS[2] },
            'default': { rank: '参加賞', prize: 'ランダム壁紙 1枚', matchedItem: null }
        };

        const reels = [document.querySelector('#reel1 .reel-inner'), document.querySelector('#reel2 .reel-inner'), document.querySelector('#reel3 .reel-inner')];
        const spinButton = document.getElementById('spin-button');
        const modal = document.getElementById('modal');
        const modalCloseButton = document.getElementById('modal-close-button');

        let spinSound, stopSound, winSound, startSound;
        const initAudio = () => {
            if (!startSound) {
                startSound = new Audio('data:audio/mp3;base64,UklGRigAAABXQVZFZm10IBAAAAABAAEARKwAAIhYAQACABAAAABkYXRhAgAAAAEA'); // Short click for lever
                spinSound = new Audio('https://cdn.pixabay.com/audio/2022/03/15/audio_73134812f8.mp3');
                stopSound = new Audio('https://cdn.pixabay.com/audio/2022/03/10/audio_e96b4cf85f.mp3');
                winSound = new Audio('https://cdn.pixabay.com/audio/2022/11/17/audio_88a87b5c33.mp3');
            }
        };

        const REEL_ITEM_HEIGHT = 120; // img (100px) + margin (10px*2)
        let gameState = 'ready'; // 'ready', 'spinning', 'stopping', 'result'
        let stopReelIndex = 0;
        let finalResults = [];

        function setupReels() {
            reels.forEach(reel => {
                reel.innerHTML = '';
                const shuffledItems = [...ITEMS].sort(() => Math.random() - 0.5);
                
                // 無限ループ用の要素複製
                const reelItems = [...shuffledItems, ...shuffledItems];

                reelItems.forEach(item => {
                    const img = document.createElement('img');
                    img.src = item.image;
                    img.alt = item.name;
                    img.dataset.id = item.id;
                    reel.appendChild(img);
                });
            });
        }
        
        function updateButton(state, text) {
            spinButton.textContent = text;
            spinButton.classList.remove('state-spin', 'state-stop');
            if (state === 'spin') {
                spinButton.classList.add('state-spin');
            } else if (state === 'stop') {
                spinButton.classList.add('state-stop');
            }
            spinButton.disabled = (state === 'disabled');
        }
        
        function determineResult() {
            // 20%の確率で当たり
            if (Math.random() < 0.2) {
                const winningItem = ITEMS[Math.floor(Math.random() * ITEMS.length)];
                finalResults = [winningItem.id, winningItem.id, winningItem.id];
            } else { // 80%はハズレ
                finalResults = Array(3).fill(null).map(() => ITEMS[Math.floor(Math.random() * ITEMS.length)].id);
                if (finalResults[0] === finalResults[1] && finalResults[1] === finalResults[2]) {
                    finalResults[2] = ITEMS[(ITEMS.findIndex(item => item.id === finalResults[2]) + 1) % ITEMS.length].id;
                }
            }
        }

        async function startSpin() {
            if (gameState !== 'ready') return;
            gameState = 'spinning';
            
            initAudio();
            startSound.play();
            
            determineResult();
            
            reels.forEach(reel => {
                reel.style.transition = 'none'; // リセット
                reel.style.transform = 'translateY(0)';
                void reel.offsetWidth; // 強制リフロー
                reel.classList.add('spinning');
            });

            updateButton('stop', 'STOP');
            stopReelIndex = 0;
        }

        function stopReel() {
            if (gameState !== 'spinning' || stopReelIndex >= reels.length) return;

            stopSound.currentTime = 0;
            stopSound.play();

            const reel = reels[stopReelIndex];
            reel.classList.remove('spinning');
            
            const targetId = finalResults[stopReelIndex];
            const allItems = Array.from(reel.children);
            // 停止位置をITEMSの半分の位置にある絵柄に合わせる(無限ループのため)
            const targetIndex = allItems.findIndex((img, i) => img.dataset.id === targetId && i >= ITEMS.length);

            const currentTransformY = new WebKitCSSMatrix(window.getComputedStyle(reel).transform).m42;
            const itemCycle = ITEMS.length * REEL_ITEM_HEIGHT;
            const normalizedY = currentTransformY % itemCycle;
            
            reel.style.transform = `translateY(${normalizedY}px)`;
            
            const targetPosition = -(targetIndex * REEL_ITEM_HEIGHT);

            reel.style.transition = 'transform 0.5s ease-out';
            reel.style.transform = `translateY(${targetPosition}px)`;
            
            stopReelIndex++;

            if (stopReelIndex >= reels.length) {
                gameState = 'stopping';
                updateButton('disabled', '...');
                setTimeout(checkResult, 1000); // 全リール停止後、少し待ってから結果表示
            }
        }

        function checkResult() {
            let resultKey = 'default';
            let matchedItemForModal;

            if (finalResults[0] === finalResults[1] && finalResults[1] === finalResults[2]) {
                resultKey = finalResults[0];
            }
            
            const prizeInfo = PRIZES[resultKey];
            
            if (prizeInfo.rank === '参加賞') {
                const middleItemId = finalResults[1];
                matchedItemForModal = ITEMS.find(item => item.id === middleItemId);
            } else {
                matchedItemForModal = prizeInfo.matchedItem;
                winSound.play();
            }

            showModal(prizeInfo, matchedItemForModal);
            gameState = 'result';
        }

        function resetGame() {
            setupReels();
            updateButton('spin', 'SPIN!');
            gameState = 'ready';
        }
        
        spinButton.addEventListener('click', () => {
            if (gameState === 'ready') {
                startSpin();
            } else if (gameState === 'spinning') {
                stopReel();
            }
        });

        // --- モーダル表示とシェアボタンのロジック ---
        function showModal(prizeInfo, itemInfo) {
            document.getElementById('modal-prize-name').textContent = prizeInfo.rank;
            document.getElementById('modal-prize-item').textContent = prizeInfo.prize;
            document.getElementById('modal-item-image').src = itemInfo.image;
            document.getElementById('modal-item-image').alt = itemInfo.name;
            document.getElementById('modal-item-description').textContent = itemInfo.description;
            
            const shareText = `カロッツェリアヒストリースロットで【${prizeInfo.rank}】をGET！懐かしの「${itemInfo.name}」が当たりました！`;
            const hashtags = "あの頃のカロッツェリア,カロッツェリアヒストリースロット";
            
            const twitterURL = `https://twitter.com/intent/tweet?text=${encodeURIComponent(shareText)}&hashtags=${hashtags}`;
            document.getElementById('twitter-share-button').href = twitterURL;

            const lineURL = `https://line.me/R/msg/text/?${encodeURIComponent(shareText)}`;
            document.getElementById('line-share-button').href = lineURL;

            modal.classList.add('show');
        }
        
        modalCloseButton.addEventListener('click', () => {
            modal.classList.remove('show');
            resetGame();
        });
        modal.addEventListener('click', (e) => {
            if (e.target === modal) {
                modal.classList.remove('show');
                resetGame();
            }
        });

        resetGame(); // 初期化
    });
    </script>
</body>
</html>