document.addEventListener("DOMContentLoaded", () => {
    let currentLang = "en";
    const locations = ["KLCC", "Bangsar", "Mont Kiara", "Cheras", "Petaling Jaya", "Greater KL"];

    // 4言語すべての辞書を完全網羅
    const localDict = {
        en: {
            title: "KL Certified Aesthetic & Plastic Surgery Directory",
            subtitle: "Verified medical centres and clinics with KKM LCP certifications in Kuala Lumpur",
            lblLocation: "Location",
            btnNearMe: "📍 Find Near Me",
            btnNearMeActive: "🟢 Sorted by Distance",
            locAll: "All Locations",
            suffix: "verified clinics found",
            jpNotice: ""
        },
        cn: {
            title: "吉隆坡认证医美与整形医院指南",
            subtitle: "吉隆坡拥有马来西亚卫生部 (KKM) LCP 认证的权威医疗机构与诊所名单",
            lblLocation: "区域地点",
            btnNearMe: "📍 查找附近诊所 (Near Me)",
            btnNearMeActive: "🟢 已按距离由近到远排序",
            locAll: "所有区域",
            suffix: "家认证医疗机构已找到",
            jpNotice: ""
        },
        bm: {
            title: "Direktori Estetik & Pembedahan Plastik Disahkan KL",
            subtitle: "Senarai pusat perubatan dan klinik disahkan dengan pensijilan KKM LCP di Kuala Lumpur",
            lblLocation: "Lokasi / Kawasan",
            btnNearMe: "📍 Cari Berdekatan Saya",
            btnNearMeActive: "🟢 Diisih mengikut Jarak Terdekat",
            locAll: "Semua Lokasi",
            suffix: "klinik perubatan disahkan ditemui",
            jpNotice: ""
        },
        jp: {
            title: "KL認証美容・整形クリニック案内",
            subtitle: "マレーシアKKM認証の主要な医療機関・クリニック一覧",
            lblLocation: "エリア・場所",
            btnNearMe: "📍 現在地から近い順に探す (Near Me)",
            btnNearMeActive: "🟢 現在地から近い順に表示中",
            locAll: "すべてのエリア",
            suffix: "件の認証医療機関が見つかりました",
            jpNotice: "⚠️ 日本語通訳・スタッフが必要な場合は事前に要確認。"
/* Near Me Button Styling - PAGIKL Styled Premium Button */
.btn-nearme {
    width: 100%;
    height: 46px; /* セレクトボックスと同一 */
    background: #111827; /* 深いダークトーン */
    color: #e2e8f0;
    border: 1px solid #374151;
    border-radius: 6px;
    font-size: 13px;
    font-weight: 600;
    letter-spacing: 0.5px;
    cursor: pointer;
    display: flex;
    align-items: center;
    justify-content: center;
    transition: all 0.2s ease;
    padding: 0 20px;
}

.btn-nearme:hover {
    background: #1f2937;
    border-color: #9ca3af;
    color: #ffffff;
    box-shadow: 0 0 10px rgba(255, 255, 255, 0.05);
}

.btn-nearme.active {
    background: #064e3b; /* 成功時のシックなグリーン */
    border-color: #10b981;
    color: #a7f3d0;
}
/* カード内の画像コンテナ */
.clinic-image-container {
    width: 100%;
    height: 160px; /* 画像の高さ（お好みで調整してください） */
    margin: 12px 0; /* 上下の余白 */
    border-radius: 8px; /* 角を少し丸める */
    overflow: hidden; /* はみ出し防止 */
    background-color: #1e293b; /* 画像が読み込まれるまでの背景色 */
}

/* 画像自体の設定 */
.clinic-card-img {
    width: 100%;
    height: 100%;
    object-fit: cover; /* 縦横比を維持したままエリアを埋める（超重要） */
    object-position: center; /* 画像の中心を基準に切り抜き */
}
    };

    const langSelect = document.getElementById("langSelect");
    const filterLocation = document.getElementById("filterLocation");
    const clinicGrid = document.getElementById("clinicGrid");
    const matchCount = document.getElementById("matchCount");
    const btnNearMe = document.getElementById("btnNearMe");

    function updateLanguageUI() {
        const dict = localDict[currentLang];
        
        if(document.getElementById("txtTitle")) document.getElementById("txtTitle").innerText = dict.title;
        if(document.getElementById("txtSubTitle")) document.getElementById("txtSubTitle").innerText = dict.subtitle;
        if(document.getElementById("lblLocation")) document.getElementById("lblLocation").innerText = dict.lblLocation;
        if(btnNearMe && !btnNearMe.classList.contains("active")) btnNearMe.innerText = dict.btnNearMe;

        if (filterLocation) {
            const prevValue = filterLocation.value || "all";
            filterLocation.innerHTML = `<option value="all">${dict.locAll}</option>` + locations.map(loc => `<option value="${loc}">${loc}</option>`).join("");
            filterLocation.value = prevValue;
        }

        renderClinics();
    }

    function renderClinics(sortedClinics = null) {
        if (!filterLocation) return;
        const selectedLocation = filterLocation.value || "all";
        if (typeof clinicData === 'undefined') return;

        let targetData = sortedClinics || clinicData;

        const filtered = targetData.filter(clinic => {
            if (selectedLocation !== "all" && clinic.location !== selectedLocation) return false;
            return true;
        });

        if (matchCount) {
            matchCount.innerText = `${filtered.length} ${localDict[currentLang].suffix}`;
        }

        if (clinicGrid) {
            if (filtered.length === 0) {
                clinicGrid.innerHTML = `<div style="grid-column:1/-1; text-align:center; padding: 40px; color:#94a3b8;">No clinics match the criteria.</div>`;
                return;
            }

            clinicGrid.innerHTML = filtered.map(clinic => {
                const jpnNoticeHtml = (currentLang === 'jp' && !clinic.japaneseStaff)
                    ? `<div class="jp-staff-notice" style="color: #f59e0b; font-size: 13px; margin: 8px 0; font-weight: 500;">${localDict.jp.jpNotice}</div>` 
                    : '';

                const distanceHtml = clinic.distance !== undefined 
                    ? `<span class="distance-badge" style="background:#22c55e;color:#fff;padding:2px 8px;border-radius:4px;font-size:12px;margin-left:10px;font-weight:600;">🚗 ${clinic.distance.toFixed(1)} km</span>` 
                    : '';

                return `
                    <div class="clinic-card">
                        <div>
                            <span class="badge-kkm">✓ KKM LCP CERTIFIED</span>
                            <h3>${clinic.name} ${distanceHtml}</h3>
                            <p class="clinic-location">📍 ${clinic.location}, Malaysia</p>
                            ${jpnNoticeHtml}
                        </div>
                        <div>
                            <div class="map-buttons-container">
                                <a href="${clinic.mapsUrl}" target="_blank" class="btn-map google-maps-btn">Google Maps</a>
                                <a href="${clinic.wazeUrl}" target="_blank" class="btn-map waze-btn">Waze</a>
                            </div>
                        </div>
                    </div>
                `;
            }).join("");
        }
    }

    // 正確に修正されたハバーサイン公式距離計算関数
    function calculateDistance(lat1, lon1, lat2, lon2) {
        const R = 6371; // 地球の半径 (km)
        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));
        return R * c;
    }

    if (btnNearMe) {
        btnNearMe.addEventListener("click", () => {
            if (navigator.geolocation) {
                const msgLocating = { en: "Locating...", cn: "定位中...", bm: "Sedang Mengesan...", jp: "位置情報を取得中..." };
                btnNearMe.innerText = msgLocating[currentLang];
                
                navigator.geolocation.getCurrentPosition((position) => {
                    const userLat = position.coords.latitude;
                    const userLng = position.coords.longitude;

                    let calculatedData = clinicData.map(clinic => {
                        return {
                            ...clinic,
                            distance: calculateDistance(userLat, userLng, clinic.lat, clinic.lng)
                        };
                    });

                    calculatedData.sort((a, b) => a.distance - b.distance);
                    
                    btnNearMe.classList.add("active");
                    btnNearMe.innerText = localDict[currentLang].btnNearMeActive;
                    renderClinics(calculatedData);
                }, () => {
                    const msgError = { en: "Geolocation failed.", cn: "无法获取位置信息。", bm: "Gagal mendapatkan lokasi.", jp: "位置情報の取得に失敗しました。" };
                    alert(msgError[currentLang]);
                    updateLanguageUI();
                });
            } else {
                alert("Geolocation not supported.");
            }
        });
    }

    if (langSelect) {
        langSelect.addEventListener("change", (e) => {
            currentLang = e.target.value;
            updateLanguageUI();
        });
    }

    if (filterLocation) {
        filterLocation.addEventListener("change", () => {
            if(btnNearMe) btnNearMe.classList.remove("active");
            renderClinics();
        });
    }

    updateLanguageUI();
});
