<!DOCTYPE html>
<html lang="zh-TW">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>衝！脫！棒！蓋爽！(全台公廁快查)</title>
    
    <link rel="stylesheet" href="https://unpkg.com/leaflet@1.9.4/dist/leaflet.css" crossorigin=""/>
    <link rel="stylesheet" href="https://unpkg.com/leaflet.markercluster@1.5.3/dist/MarkerCluster.css" />
    <link rel="stylesheet" href="https://unpkg.com/leaflet.markercluster@1.5.3/dist/MarkerCluster.Default.css" />
    
    <script src="https://unpkg.com/leaflet@1.9.4/dist/leaflet.js" crossorigin=""></script>
    <script src="https://unpkg.com/leaflet.markercluster@1.5.3/dist/leaflet.markercluster.js"></script>

    <style>
        /* CSS 樣式，修改按鈕容器佈局和下拉選單文字對齊 */
        html, body { height: 100%; margin: 0; padding: 0; font-family: sans-serif; display: flex; flex-direction: column; }
        #map-container { flex-grow: 1; position: relative; order: 1; }
        #map { height: 100%; width: 100%; display: block; background-color: #eee; }
        
        /* 定位按鈕與下拉選單容器樣式 */
        .recenter-button-container {
            order: 2; 
            padding: 10px 15px; 
            background-color: #f8f9fa; 
            border-top: 1px solid #dee2e6; 
            display: flex; /* 始終保持 Flexbox */
            justify-content: center; 
            align-items: center; 
            gap: 10px; 
        }
        
        /* 容器內元素的樣式 */
        .recenter-button-container label { margin: 0; font-size: 1em; white-space: nowrap; flex-shrink: 0; /* 防止標籤被壓縮 */ }
        .recenter-button-container select, 
        .recenter-button-container button { padding: 8px 12px; border: 1px solid #ced4da; border-radius: 4px; font-size: 1em; }
        .recenter-button-container select { 
             max-width: 250px; 
             flex: 1 1 auto; /* 允許下拉選單彈性增長和收縮 */
             /* 嘗試置中文字，效果依瀏覽器 */
             text-align: center; 
             text-align-last: center; 
             -moz-text-align-last: center; /* Firefox */
        }
        #locateMapButton {
            background-color: #e53935; /* 紅色 */
            color: white; border: none; cursor: pointer;
            transition: background-color 0.2s; white-space: nowrap;
            flex-shrink: 0; /* 防止按鈕被壓縮 */
            border-radius: 24px; /* 圓角 */
            padding: 10px 20px; /* 調整 padding */
        }
        #locateMapButton:hover { background-color: #b71c1c; }
        
        /* 控制台樣式 */
        #controls { background-color: #f8f9fa; order: 3; overflow: hidden; transition: max-height 0.3s ease-out; max-height: 500px; }
        #controls.collapsed { max-height: 40px; }
        #control-header { padding: 10px 15px; background-color: #f8f9fa; cursor: pointer; display: flex; justify-content: space-between; align-items: center; }
        #control-header h1 { margin: 0; font-size: 1.5em; flex-grow: 1; text-align: center; }
        #toggle-button { background: none; border: none; font-size: 1.2em; cursor: pointer; padding: 0 10px; }
        #control-content { padding: 0 15px 15px 15px; }
        #controls p.description { margin-bottom: 15px; color: #6c757d; text-align: center; font-size: 0.9em; }
        #filters { display: none; /* 由於下拉選單已移走，此 div 可隱藏或移除 */ } 
        #loading { position: absolute; top: 10px; left: 50%; transform: translateX(-50%); background-color: rgba(255, 255, 255, 0.9); padding: 8px 15px; border-radius: 5px; z-index: 1000; display: none; text-align: center; box-shadow: 0 2px 4px rgba(0,0,0,0.2); }
        .leaflet-popup-content-wrapper { border-radius: 8px; box-shadow: 0 1px 5px rgba(0,0,0,0.2); padding: 1px; }
        .leaflet-popup-content { margin: 12px 18px; font-size: 14px; line-height: 1.6; max-height: 250px; overflow-y: auto; white-space: normal !important; }
        .toilet-popup { min-width: 250px; }
        .toilet-popup h4 { margin: 0 0 10px 0; font-size: 1.1em; font-weight: bold; color: #333; border-bottom: 1px solid #eee; padding-bottom: 5px; }
        .toilet-popup p { margin: 5px 0; color: #555; }
        .toilet-popup strong.label { display: inline-block; font-weight: bold; color: #000; margin-right: 6px; }
        .toilet-popup .diaper-yes { color: #28a745; font-weight: bold; }
        .toilet-popup .diaper-no { color: #6c757d; }
        .leaflet-popup-close-button { top: 12px; right: 12px; }
        /* 聚合圖標樣式 */
        .marker-cluster { border-radius: 50% !important; width: 56px !important; height: 56px !important; margin-left: -28px !important; margin-top: -28px !important; }
        .marker-cluster div { border-radius: 50% !important; width: 46px !important; height: 46px !important; margin-left: 3px !important; margin-top: 3px !important; border: 2px solid black !important; box-sizing: border-box !important; line-height: 42px !important; font-size: 22px !important; font-weight: bold !important; color: black !important; }
        .marker-cluster-small { background-color: rgb(191, 255, 0); } .marker-cluster-small div { background-color: rgb(127, 255, 0); }  
        .marker-cluster-medium { background-color: rgb(127, 255, 0); } .marker-cluster-medium div { background-color: rgb(50, 205, 50); } 
        .marker-cluster-large { background-color: rgb(50, 205, 50); } .marker-cluster-large div { background-color: rgb(0, 128, 0); } 
        
        @media (max-width: 768px) { /* 響應式樣式 */
            .recenter-button-container { 
                padding: 8px 10px; /* 稍微減少 padding */
                /* 移除 flex-direction: column */
                gap: 8px; /* 稍微減少間距 */
            }
             .recenter-button-container label { display: none; /* 手機上直接隱藏標籤 */ }
             .recenter-button-container select {
                 max-width: none; /* 移除最大寬度限制 */
                 flex: 1 1 auto; /* 讓它填滿可用空間 */
                 /* 強制置中文字 */
                 text-align: center;
                 text-align-last: center;
                 -moz-text-align-last: center;
                 /* 恢復箭頭 */
                 -webkit-appearance: none; 
                 -moz-appearance: none;
                 appearance: none;
                 background: white url('data:image/svg+xml;charset=US-ASCII,%3Csvg%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20width%3D%22292.4%22%20height%3D%22292.4%22%3E%3Cpath%20fill%3D%22%23007bff%22%20d%3D%22M287%2069.4a17.6%2017.6%200%200%200-13-5.4H18.4c-5%200-9.3%201.8-12.9%205.4A17.6%2017.6%200%200%200%200%2082.2c0%205%201.8%209.3%205.4%2012.9l128%20127.9c3.6%203.6%207.8%205.4%2012.8%205.4s9.2-1.8%2012.8-5.4L287%2095c3.5-3.5%205.4-7.8%205.4-12.8%200-5-1.9-9.2-5.5-12.8z%22%2F%3E%3C%2Fsvg%3E') no-repeat right 10px center; 
                 background-size: 10px auto; 
                 padding-right: 30px; 
             }
             #locateMapButton {
                 flex: 0 0 auto; /* 不壓縮也不增長 */
                 font-size: 1em; /* 恢復字體大小 */
                 padding: 8px 15px; /* 調整 padding */
                 /* width: auto; 移除固定寬度 */
             }
            #control-content { padding: 10px; } #control-header h1 { font-size: 1.3em; } 
            /* 移除舊的 filters 樣式 */
            .marker-cluster div { font-size: 18px !important; line-height: 42px !important; } 
        }
        @media (max-width: 400px) { 
             #control-header h1 { font-size: 1.1em; } #controls p.description { font-size: 0.8em; } 
             .recenter-button-container select, .recenter-button-container button { font-size: 0.9em; padding: 6px 10px;} 
             .marker-cluster div { font-size: 16px !important; } 
        }
    </style>
</head>
<body>

    <div id="map-container">
        <div id="map"></div>
        <div id="loading">正在初始化地圖並定位...</div>
    </div>

    <!-- 定位按鈕與下拉選單容器 -->
    <div class="recenter-button-container">
         <label for="typeFilter">搜尋目標:</label>
         <select id="typeFilter">
             <option value="" selected disabled>選擇廁所類型</option> 
             <option value="all">所有類型廁所</option>
             <option value="male">男廁 (含友善/無障礙/親子等)</option> 
             <option value="female">女廁 (含友善/無障礙/親子等)</option>
             <option value="child">兒童廁所 (含無障礙/親子等)</option> 
             <option value="diaper_only">換尿布 (不限類型)</option> 
         </select>
        <button id="locateMapButton">回到我的位置</button> 
    </div>

    <div id="controls"> 
        <div id="control-header">
            <button id="toggle-button">▼</button> 
            <h1>衝！脫！棒！蓋爽！(全台公廁快查)</h1>
        </div>
        
        <div id="control-content">
            <p class="description">
選擇上方搜尋目標，地圖將顯示您周邊的廁所位置。<br>
移動地圖區域後將自動更新。(資料更新日:2025/04)<br>
※本工具由<strong>虚空蔵</strong>研發，供自由使用，但嚴禁抄襲。<br>
※如您覺得受用請訂閱我的<a href="https://www.youtube.com/@kokuzo" target="_blank">Youtube頻道</a>以資鼓勵。
</p>
        </div>
    </div>

    <script>
        // JavaScript 程式碼與前一版本相同，無需修改
        const loadingDiv = document.getElementById('loading');
        const mapDiv = document.getElementById('map');
        const locateMapButton = document.getElementById('locateMapButton'); 
        const typeFilterElement = document.getElementById('typeFilter');
        const controlsElement = document.getElementById('controls');
        const toggleButton = document.getElementById('toggle-button');
        const controlHeader = document.getElementById('control-header');

        let map = null; 
        let userMarker = null; 
        let toiletMarkers = null; 
        let lastUserLocation = null; 
        let lastQueryCenter = null; 
        let queryRadius = 2.0; 
        let timeoutHandler = null; 

        const redIcon = L.icon({ 
            iconUrl: 'https://raw.githubusercontent.com/pointhi/leaflet-color-markers/master/img/marker-icon-2x-red.png',
            shadowUrl: 'https://cdnjs.cloudflare.com/ajax/libs/leaflet/1.7.1/images/marker-shadow.png',
            iconSize: [25, 41], iconAnchor: [12, 41], popupAnchor: [1, -34], shadowSize: [41, 41]
        });

        function updateLocateButtonPosition() { 
            // 此函數現在不再需要，因為按鈕不在浮動
        }

        controlHeader.addEventListener('click', function() { 
            controlsElement.classList.toggle('collapsed');
            toggleButton.textContent = controlsElement.classList.contains('collapsed') ? '▲' : '▼';
            // 移除 updateLocateButtonPosition 調用
            setTimeout(() => { if (map) map.invalidateSize(); }, 350); 
        });

        document.addEventListener('DOMContentLoaded', function() { 
            loadingDiv.style.display = 'block'; 
            attemptLocateUser(); 
            // 移除 updateLocateButtonPosition 調用
        });
        
        // 移除 resize 和 scroll 事件監聽器中的 updateLocateButtonPosition
        window.removeEventListener('resize', updateLocateButtonPosition);
        window.removeEventListener('scroll', updateLocateButtonPosition);


        function initializeMap(centerCoords, zoomLevel) { 
            if (map) { map.setView(centerCoords, zoomLevel); return; }
            mapDiv.style.display = 'block'; map = L.map('map').setView(centerCoords, zoomLevel); 
            L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', { maxZoom: 19, attribution: '&copy; <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors' }).addTo(map);
            
            toiletMarkers = L.markerClusterGroup({
                chunkedLoading: true, 
                maxClusterRadius: 60 
            });
            map.addLayer(toiletMarkers);
            
            if (lastUserLocation) placeOrUpdateMarker(lastUserLocation, false); 
            loadingDiv.style.display = 'none'; 
            console.log("地圖初始化完成"); 

            map.on('moveend', function() { 
                 if (map) { clearTimeout(timeoutHandler); timeoutHandler = setTimeout(function() { const center = map.getCenter(); 
                     if (lastQueryCenter && typeFilterElement.value !== "") { 
                         const distanceKm = calculateDistance( center.lat, center.lng, lastQueryCenter.lat, lastQueryCenter.lng ); 
                         if (distanceKm > queryRadius / 1.5 || Math.abs(map.getZoom() - lastQueryCenter.zoom) >= 1 ) { 
                             fetchNearbyToilets(center.lat, center.lng); 
                         } 
                     } 
                 }, 500); }
            });
            setTimeout(() => { if (map) map.invalidateSize(); /* 移除 updateLocateButtonPosition */ }, 100); 
        }

        function placeOrUpdateMarker(location, openPopup = true) { 
            if (!map) return; if (!userMarker) { userMarker = L.marker(location, { icon: redIcon }).addTo(map).bindPopup('<b>我在這!</b>'); } else { userMarker.setLatLng(location); } if (openPopup) userMarker.openPopup();
        }

        function attemptLocateUser(panOrSetView = true, targetZoom = 18) { 
             if ('geolocation' in navigator) { console.log("嘗試定位使用者..."); if (panOrSetView) { loadingDiv.textContent = '正在定位您的位置...'; loadingDiv.style.display = 'block'; } navigator.geolocation.getCurrentPosition( (position) => { const lat = position.coords.latitude; const lon = position.coords.longitude; const newUserLocation = [lat, lon]; console.log(`定位成功！ 位置: ${lat}, ${lon}`); lastUserLocation = newUserLocation; if (!map) { initializeMap(newUserLocation, targetZoom); } else { if (panOrSetView) { map.setView(newUserLocation, targetZoom, { animate: true }); loadingDiv.style.display = 'none'; } placeOrUpdateMarker(newUserLocation, panOrSetView); } /* 移除 updateLocateButtonPosition */ }, (error) => { console.error("定位失敗！錯誤碼:", error.code, "錯誤訊息:", error.message); if (panOrSetView) loadingDiv.style.display = 'none'; if (!map) { const defaultCenter = [23.9731, 120.9796]; const defaultZoom = 14; initializeMap(defaultCenter, defaultZoom); } else { alert("無法取得您目前的位置。"); } /* 移除 updateLocateButtonPosition */ }, { enableHighAccuracy: true, timeout: 10000, maximumAge: 60000 } ); } else { if (panOrSetView) loadingDiv.style.display = 'none'; if (!map) { const defaultCenter = [23.9731, 120.9796]; const defaultZoom = 14; initializeMap(defaultCenter, defaultZoom); } else { alert("您的瀏覽器不支援定位功能。"); } /* 移除 updateLocateButtonPosition */ }
        }
        
        function goToMyLocation() { 
            if (!map) { alert("地圖尚未初始化。"); return; }
            if (lastUserLocation) { map.setView(lastUserLocation, 18, { animate: true }); if (userMarker) { setTimeout(() => { userMarker.openPopup(); }, 150); } } 
            else { attemptLocateUser(true, 18); }
        }

        function calculateDistance(lat1, lon1, lat2, lon2) { 
            const R = 6371; const dLat = (lat2 - lat1) * Math.PI / 180; const dLon = (lon2 - lon1) * Math.PI / 180; const a = Math.sin(dLat/2) * Math.sin(dLat/2) + Math.cos(lat1 * Math.PI / 180) * Math.cos(lat2 * Math.PI / 180) * Math.sin(dLon/2) * Math.sin(dLon/2); const c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a)); const distance = R * c; return distance;
        }

        function fetchNearbyToilets(userLat, userLon, radiusInKm = 2.0) { 
             queryRadius = radiusInKm; const filterTypeValue = typeFilterElement.value; 
             if (filterTypeValue === "") { if (toiletMarkers) toiletMarkers.clearLayers(); loadingDiv.style.display = 'none'; return; }
             
             console.log(`查詢座標 (${userLat}, ${userLon}), 半徑 ${radiusInKm}km, 選項: ${filterTypeValue}`);
             loadingDiv.textContent = '正在查詢附近廁所...'; loadingDiv.style.display = 'block'; 
             lastQueryCenter = { lat: userLat, lng: userLon, zoom: map.getZoom() };
             if (toiletMarkers) toiletMarkers.clearLayers(); 
             let apiUrl = `api.php?lat=${userLat}&lon=${userLon}&radius=${radiusInKm}`;
             if (filterTypeValue !== 'all') { apiUrl += `&type=${encodeURIComponent(filterTypeValue)}`; }
             console.log("呼叫 API:", apiUrl);
             fetch(apiUrl) 
                .then(response => { /* API 回應處理 */
                    if (!response.ok) { return response.json().then(errData => { throw new Error(`API 錯誤 (${response.status}): ${errData.error || '未知錯誤'}`); }).catch(() => { throw new Error(`API 請求失敗，狀態碼: ${response.status}`); }); }
                    return response.json(); 
                })
                .then(toilets => { /* 處理廁所資料 */
                    if (!toiletMarkers) return; 
                    if (toilets.length === 0) { loadingDiv.textContent = '此區域未找到符合條件的廁所'; setTimeout(() => { loadingDiv.style.display = 'none'; }, 2500); return; }
                    loadingDiv.textContent = '正在加入地圖標記...';
                    const markersToAdd = [];
                    toilets.forEach(toilet => {
                        const lat = parseFloat(toilet.latitude); const lon = parseFloat(toilet.longitude);
                        if (!isNaN(lat) && !isNaN(lon)) {
                            const marker = L.marker([lat, lon]);
                            let popupContent = `<div class="toilet-popup"><h4>${toilet.name || '名稱未知'}</h4>`; 
                            popupContent += `<p><strong class="label">地址:</strong> ${toilet.address || '地址未知'}</p>`;
                            popupContent += `<p><strong class="label">類別:</strong> ${toilet.type || 'N/A'}</p>`;
                            if (toilet.distance !== undefined) { popupContent += `<p><strong class="label">距離:</strong> ${parseFloat(toilet.distance).toFixed(2)} 公里</p>`; }
                            const diaperStatus = toilet.diaper == 1 ? '<span class="diaper-yes">✓ 有尿布台</span>' : '<span class="diaper-no">✗ 無尿布台</span>';
                            popupContent += `<p><strong class="label">設施:</strong> ${diaperStatus}</p></div>`; 
                            marker.bindPopup(popupContent, { maxWidth: 500 }); 
                            markersToAdd.push(marker); 
                        }
                    });
                    toiletMarkers.addLayers(markersToAdd); 
                    console.log(`${toilets.length} 個廁所標記已加入地圖`); loadingDiv.style.display = 'none'; 
                })
                .catch(error => { /* 錯誤處理 */
                    console.error("查詢或處理附近廁所資料時發生錯誤:", error); alert(`查詢附近廁所失敗: ${error.message}`); loadingDiv.style.display = 'none'; 
                });
        }

        // --- 事件監聽器 ---
        locateMapButton.addEventListener('click', goToMyLocation); 
        typeFilterElement.addEventListener('change', () => { 
            if (map) { 
                 const selectedValue = typeFilterElement.value;
                 if (selectedValue !== "") {
                     console.log("篩選條件變更，搜尋目前地圖中心區域");
                     const center = map.getCenter();
                     fetchNearbyToilets(center.lat, center.lng); 
                     if (!controlsElement.classList.contains('collapsed')) {
                         controlsElement.classList.add('collapsed');
                         toggleButton.textContent = '▲'; 
                         // 移除 updateLocateButtonPosition
                         setTimeout(() => { if (map) map.invalidateSize(); }, 350);
                     }
                 } else {
                     if (toiletMarkers) toiletMarkers.clearLayers();
                     console.log("已選擇預設選項，清空地圖。");
                 }
            } 
        });

    </script>

</body>
</html>
