<!DOCTYPE html>
<html lang="ja">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>トイレファインダー - 自転車でも安心</title>
    <link rel="stylesheet" href="styles.css">
    <script async src="https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js?client=ca-pub-1636079219527574"
     crossorigin="anonymous"></script>
    <style>
        /* 地図コンテナの修正 */
        .map-container {
            width: 100% !important;
            height: 500px !important;
            min-height: 500px !important;
            display: block !important;
            position: relative !important;
        }
        
        #map {
            width: 100% !important;
            height: 100% !important;
            display: block !important;
        }
        
        /* モーダルの背景 */
        .modal {
            display: none;
            position: fixed;
            z-index: 1000;
            left: 0;
            top: 0;
            width: 100%;
            height: 100%;
            background-color: rgba(0,0,0,0.5);
        }
        
        /* モーダルコンテンツを画面中央に配置 */
        .modal-content {
            position: fixed;
            top: 50%;
            left: 50%;
            transform: translate(-50%, -50%);
            background-color: white;
            padding: 20px;
            border-radius: 10px;
            width: 90%;
            max-width: 500px;
            max-height: 90vh;
            overflow-y: auto;
            box-shadow: 0 4px 6px rgba(0,0,0,0.1);
        }
        
        /* フォームスタイル */
        .form-group {
            margin-bottom: 15px;
        }
        
        .form-group label {
            display: block;
            margin-bottom: 5px;
            font-weight: bold;
        }
        
        .form-group input[type="text"],
        .form-group select,
        .form-group textarea {
            width: 100%;
            padding: 8px;
            border: 1px solid #ddd;
            border-radius: 4px;
        }
        
        .form-group textarea {
            resize: vertical;
            min-height: 60px;
        }
        
        .form-actions {
            display: flex;
            gap: 10px;
            justify-content: flex-end;
            margin-top: 20px;
        }
        
        .close {
            position: absolute;
            right: 15px;
            top: 15px;
            font-size: 28px;
            font-weight: bold;
            cursor: pointer;
            color: #666;
        }
        
        .close:hover {
            color: #000;
        }
    </style>
</head>
<body>
    <header>
        <h1>🚻 トイレファインダー</h1>
        <p>自転車での遠出も安心！みんなでトイレ情報を共有しよう</p>
    </header>
    
    <main>
        <div class="controls">
            <button id="addToiletBtn" class="btn-primary">📍 トイレを追加</button>
            <button id="myLocationBtn" class="btn-secondary">📍 現在地</button>
            <button id="clearDirectionsBtn" class="btn-clear" style="display:none;">🗺️ 道順を消去</button>
            <button id="importCSVBtn" class="btn-secondary" onclick="document.getElementById('csvFile').click()">
                📂 CSVインポート
            </button>
            <input type="file" id="csvFile" accept=".csv" style="display: none;">
            <button id="searchNearbyBtn" class="btn-secondary">🔍 周辺のコンビニ検索</button>
        </div>
        
        <div class="filter-buttons" style="margin: 10px 0;">
            <button onclick="if(toiletFinder) toiletFinder.toggleFilter('showFree')" class="filter-btn">
                🆓 無料のみ
            </button>
            <button onclick="if(toiletFinder) toiletFinder.toggleFilter('showWheelchair')" class="filter-btn">
                ♿ バリアフリー
            </button>
        </div>
        
        <div class="main-content">
            <div id="map" class="map-container"></div>
            <div class="sidebar">
                <div class="ad-sidebar" style="background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%); padding: 20px; border-radius: 10px; margin-bottom: 20px;">
                    <h4 style="color: #fff; text-align: center; margin-bottom: 15px; font-size: 20px;">
                        🎁 応援お願いします！
                    </h4>
                    <p style="color: #fff; text-align: center; margin-bottom: 15px; font-size: 14px; line-height: 1.6;">
                        こちらのリンクからAmazonで買い物をしてくれたら<br>
                        <span style="font-size: 18px; font-weight: bold;">ムセビ泣きます(TT)</span><br>
                        経費の補填としてどうかご慈悲を！
                    </p>
                    <div style="text-align: center;">
                        <a href="https://amzn.to/3UTldNO" target="_blank" rel="nofollow" 
                           style="display: inline-block; background: #fff; color: #f5576c; padding: 10px 20px; border-radius: 20px; text-decoration: none; font-weight: bold; transition: all 0.3s; box-shadow: 0 4px 10px rgba(0,0,0,0.2);"
                           onmouseover="this.style.transform='scale(1.05)'; this.style.boxShadow='0 6px 20px rgba(0,0,0,0.3)'" 
                           onmouseout="this.style.transform='scale(1)'; this.style.boxShadow='0 4px 10px rgba(0,0,0,0.2)'">
                            🛍️ Amazonへ
                        </a>
                    </div>
                </div>
                
                <div class="stats-panel">
                    <h4>📊 トイレ統計</h4>
                    <div id="toiletStats">
                        <p>総トイレ数: <span id="totalCount">0</span></p>
                        <p>無料トイレ: <span id="freeCount">0</span></p>
                        <p>バリアフリー: <span id="wheelchairCount">0</span></p>
                    </div>
                </div>
                
                <div id="directionsPanel" class="directions-panel" style="display:none;">
                    <h4>📍 道順</h4>
                    <div id="directionsText"></div>
                </div>
            </div>
        </div>
        
        <!-- CSVインポートモーダル -->
        <div id="csvImportModal" class="modal">
            <div class="modal-content">
                <span class="close" onclick="closeCSVModal()">&times;</span>
                <h2>CSVデータインポート</h2>
                <div id="csvPreview">
                    <p>CSVファイルを選択してください</p>
                    <div class="csv-instructions">
                        <h4>対応形式：</h4>
                        <ul>
                            <li>自治体のオープンデータ（公衆トイレ一覧）</li>
                            <li>最低限必要な列: 名称, 緯度, 経度</li>
                            <li>オプション: 住所, 多目的トイレ, 営業時間など</li>
                        </ul>
                    </div>
                </div>
                <div class="form-actions">
                    <button id="importBtn" class="btn-primary" style="display:none;">インポート</button>
                    <button class="btn-secondary" onclick="closeCSVModal()">キャンセル</button>
                </div>
            </div>
        </div>
        
        <!-- トイレ追加モーダル -->
        <div id="addToiletModal" class="modal">
            <div class="modal-content">
                <span class="close" onclick="closeToiletModal()">&times;</span>
                <h2>トイレ情報を追加</h2>
                <p style="color: #666; margin-bottom: 15px;">地図上をクリックして位置を選択してください</p>
                <form id="toiletForm">
                    <div class="form-group">
                        <label for="toiletName">名前:</label>
                        <input type="text" id="toiletName" name="toiletName" required placeholder="例: コンビニのトイレ">
                    </div>
                    <div class="form-group">
                        <label for="toiletType">種類:</label>
                        <select id="toiletType" name="toiletType" required>
                            <option value="convenience">コンビニ</option>
                            <option value="park">公園</option>
                            <option value="station">駅</option>
                            <option value="restaurant">レストラン・カフェ</option>
                            <option value="gas">ガソリンスタンド</option>
                            <option value="other">その他</option>
                        </select>
                    </div>
                    <div class="form-group">
                        <label for="toiletNotes">備考:</label>
                        <textarea id="toiletNotes" name="toiletNotes" placeholder="営業時間、利用条件など"></textarea>
                    </div>
                    <div class="form-group">
                        <label>
                            <input type="checkbox" id="toiletFree" name="toiletFree" checked> 無料
                        </label>
                    </div>
                    <div class="form-group">
                        <label>
                            <input type="checkbox" id="toiletWheelchair" name="toiletWheelchair"> ♿ 車椅子対応
                        </label>
                    </div>
                    <div class="form-actions">
                        <button type="submit" class="btn-primary">追加</button>
                        <button type="button" class="btn-secondary" onclick="closeToiletModal()">キャンセル</button>
                    </div>
                </form>
            </div>
        </div>
    </main>
    
    <footer style="text-align: center; padding: 20px; color: #666;">
        <p>※当サイトはAmazonアソシエイトプログラムに参加しています</p>
    </footer>
    
    <!-- Firebase SDK -->
    <script src="https://www.gstatic.com/firebasejs/10.7.1/firebase-app-compat.js"></script>
    <script src="https://www.gstatic.com/firebasejs/10.7.1/firebase-database-compat.js"></script>
    
<script>
    // Firebaseの設定
    const firebaseConfig = {
        apiKey: "AIzaSyCSYSu-BS7zffRl0umu1YwXpW2znrBA7jM",
        authDomain: "toiletfinder-8bd3a.firebaseapp.com",
        databaseURL: "https://toiletfinder-8bd3a-default-rtdb.firebaseio.com",
        projectId: "toiletfinder-8bd3a",
        storageBucket: "toiletfinder-8bd3a.firebasestorage.app",
        messagingSenderId: "738709661269",
        appId: "1:738709661269:web:baaf76b8d2b357952b16dc"
    };
    
    firebase.initializeApp(firebaseConfig);
    const database = firebase.database();
    console.log('Firebase初期化完了');
    
    // 初期トイレデータ
    window.INITIAL_TOILET_DATA = [
        {
            id: "tokyo-station-1",
            name: "東京駅 丸の内南口 公衆トイレ",
            type: "station",
            lat: 35.6797,
            lng: 139.7677,
            free: true,
            wheelchair: true,
            notes: "改札外、きれいで広い",
            isPreset: true
        },
        {
            id: "shibuya-hachiko",
            name: "渋谷駅 ハチ公口 公衆トイレ",
            type: "station",
            lat: 35.6590,
            lng: 139.7005,
            free: true,
            wheelchair: true,
            notes: "ハチ公像近く",
            isPreset: true
        },
        {
            id: "shinjuku-south",
            name: "新宿駅 南口 公衆トイレ",
            type: "station",
            lat: 35.6896,
            lng: 139.7006,
            free: true,
            wheelchair: true,
            notes: "駅構内",
            isPreset: true
        },
        {
            id: "asakusa-kaminari",
            name: "雷門前 公衆トイレ",
            type: "park",
            lat: 35.7105,
            lng: 139.7927,
            free: true,
            wheelchair: true,
            notes: "観光客多い、混雑注意",
            isPreset: true
        },
        {
            id: "ueno-park",
            name: "上野公園 噴水前トイレ",
            type: "park",
            lat: 35.7150,
            lng: 139.7730,
            free: true,
            wheelchair: true,
            notes: "きれいに改装済み",
            isPreset: true
        }
    ];
    
    console.log('ページ読み込み完了');
    
    // アラート管理用の変数
    let originalAlert = window.alert;
    let isAddingToilet = false;
    
    // alert関数をオーバーライド
    window.alert = function(message) {
        // トイレ追加中で、特定のメッセージの場合は無視
        if (isAddingToilet && (message.includes('トイレ情報を追加') || message.includes('地図上の位置を選択'))) {
            console.log('アラート抑制:', message);
            return;
        }
        // それ以外は通常のアラートを表示
        return originalAlert.call(window, message);
    };
    
    // モーダルを閉じる関数
    function closeToiletModal() {
        document.getElementById('addToiletModal').style.display = 'none';
        document.getElementById('toiletForm').reset();
        if (window.tempMarker) {
            window.tempMarker.setMap(null);
            window.tempMarker = null;
        }
        // clickedPositionをリセット
        if (window.toiletFinder) {
            window.toiletFinder.clickedPosition = null;
        }
        isAddingToilet = false;
    }
    
    function closeCSVModal() {
        document.getElementById('csvImportModal').style.display = 'none';
        document.getElementById('csvFile').value = '';
    }
    
    // CSVインポート機能
    document.getElementById('csvFile').addEventListener('change', function(e) {
        const file = e.target.files[0];
        if (!file) return;
        
        const reader = new FileReader();
        reader.onload = function(e) {
            const csv = e.target.result;
            parseCSV(csv);
        };
        reader.readAsText(file, 'UTF-8');
    });
    
    function parseCSV(csv) {
        if (csv.charCodeAt(0) === 0xFEFF) {
            csv = csv.substr(1);
        }
        
        const lines = csv.split(/\r\n|\r|\n/).filter(line => line.trim() !== '');
        
        if (lines.length < 2) {
            alert('CSVファイルにデータがありません');
            return;
        }
        
        const headers = lines[0].split(',').map(h => h.trim().replace(/^"|"$/g, ''));
        
        document.getElementById('csvImportModal').style.display = 'block';
        
        const preview = document.getElementById('csvPreview');
        preview.innerHTML = `
            <h4>インポートプレビュー</h4>
            <p>検出された列: ${headers.join(', ')}</p>
            <p>データ行数: ${lines.length - 1}</p>
        `;
        
        document.getElementById('importBtn').style.display = 'block';
        document.getElementById('importBtn').onclick = function() {
            importToilets(lines, headers);
        };
    }
    
    function importToilets(lines, headers) {
        let imported = 0;
        let failed = 0;
        
        const nameIndex = headers.findIndex(h => h === '名称' || h === 'name' || h === '施設名');
        const latIndex = headers.findIndex(h => h === '緯度' || h === 'lat' || h === 'latitude');
        const lngIndex = headers.findIndex(h => h === '経度' || h === 'lng' || h === 'longitude' || h === 'lon');
        
        if (nameIndex === -1 || latIndex === -1 || lngIndex === -1) {
            alert('必要な列（名称、緯度、経度）が見つかりません');
            return;
        }
        
        for (let i = 1; i < lines.length; i++) {
            const line = lines[i].trim();
            if (!line) continue;
            
            const values = [];
            let current = '';
            let inQuotes = false;
            
            for (let j = 0; j < line.length; j++) {
                const char = line[j];
                if (char === '"') {
                    inQuotes = !inQuotes;
                } else if (char === ',' && !inQuotes) {
                    values.push(current.trim());
                    current = '';
                } else {
                    current += char;
                }
            }
            values.push(current.trim());
            
            const name = values[nameIndex] || '';
            const lat = parseFloat(values[latIndex] || '');
            const lng = parseFloat(values[lngIndex] || '');
            
            if (!name || isNaN(lat) || isNaN(lng)) {
                failed++;
                continue;
            }
            
            const toilet = {
                id: 'csv-' + Date.now() + '-' + i,
                name: name,
                lat: lat,
                lng: lng,
                type: 'other',
                free: true,
                wheelchair: false,
                isPreset: true,
                addedAt: new Date().toISOString()
            };
            
            if (window.toiletFinder) {
                isAddingToilet = true;
                toiletFinder.addToilet(toilet);
                isAddingToilet = false;
                imported++;
            }
        }
        
        alert(`${imported}件のトイレ情報をインポートしました！\n（${failed}件スキップ）`);
        closeCSVModal();
        updateStats();
    }
    
    window.updateStats = function() {
        if (window.toiletFinder) {
            const total = toiletFinder.toilets.length;
            const free = toiletFinder.toilets.filter(t => t.free).length;
            const wheelchair = toiletFinder.toilets.filter(t => t.wheelchair).length;
            
            document.getElementById('totalCount').textContent = total;
            document.getElementById('freeCount').textContent = free;
            document.getElementById('wheelchairCount').textContent = wheelchair;
        }
    }
    
    setTimeout(() => {
        if (window.updateStats) {
            window.updateStats();
        }
    }, 1000);
    
    document.getElementById('searchNearbyBtn').addEventListener('click', function() {
        if (!window.toiletFinder) {
            alert('地図の初期化中です。少々お待ちください。');
            return;
        }
        toiletFinder.searchNearbyStores();
    });
    
    // トイレフォームの送信処理
    document.getElementById('toiletForm').onsubmit = function(e) {
        e.preventDefault();
        
        if (!window.toiletFinder || !window.toiletFinder.clickedPosition) {
            // この「地図上の位置を選択してください」は表示する
            originalAlert('地図上の位置を選択してください');
            return;
        }
        
        const toilet = {
            id: Date.now().toString(),
            name: document.getElementById('toiletName').value,
            lat: window.toiletFinder.clickedPosition.lat,
            lng: window.toiletFinder.clickedPosition.lng,
            type: document.getElementById('toiletType').value,
            notes: document.getElementById('toiletNotes').value,
            free: document.getElementById('toiletFree').checked,
            wheelchair: document.getElementById('toiletWheelchair').checked,
            addedAt: new Date().toISOString()
        };
        
        // トイレ追加中フラグを設定
        isAddingToilet = true;
        
        // トイレを追加
        window.toiletFinder.addToilet(toilet);
        
        // 少し遅延してフラグをリセット
        setTimeout(() => {
            isAddingToilet = false;
        }, 100);
        
        // モーダルを閉じる
        closeToiletModal();
        
        // 成功メッセージを表示
        setTimeout(() => {
            alert('トイレを追加しました！');
        }, 200);
    };
</script>
    <script src="app.js"></script>
    <script async defer 
        src="https://maps.googleapis.com/maps/api/js?key=AIzaSyBRcfuL5q0oWg1t4hW6pwj8iA_XFUSSJ5E&libraries=places&callback=initMap">
    </script>
</body>
</html>
