<!doctype html>
<html lang="tr">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width,initial-scale=1">
<title>Medine.net - Takvim</title>
<link rel="stylesheet" href="https://www.medine.net/takvim/wp-content/plugins/fprtr-plugin-religioustimes/style-fullpage.css">
<link href="https://fonts.googleapis.com/css2?family=Vazirmatn:wght@400;500;600;700&family=Inter:wght@400;500;600;700&display=swap" rel="stylesheet">
<script src="https://cdn.jsdelivr.net/npm/moment@2.29.4/min/moment.min.js">updateTimings();
</script>
<script src="https://cdn.jsdelivr.net/npm/moment-timezone@0.5.43/builds/moment-timezone-with-data.min.js"></script>
</head>
<body>
<div class="card-wrapper hijri-mode-api">
    <div class="card" role="main" aria-label="Takvim - Namaz Vakitleri">
        <div class="card-header">
            <div class="current" id="currentDisplay" aria-live="polite">
                <img src="https://www.medine.net/takvim/wp-content/plugins/fprtr-plugin-religioustimes/icons/sunrise.svg" class="icon" id="currentIcon" alt="">
                <div class="title" id="currentTitle">Medine.net - Takvim</div>
            </div>
            <div class="header-actions">
                <button class="hamburger-btn" id="tptHamburgerBtn" type="button" aria-label="Menu" aria-haspopup="true" aria-controls="tptDrawer">
                    <span></span><span></span><span></span>
                </button>
            </div>
        </div>

        <!-- Drawer menu (top-right) -->
        <div class="tpt-drawer-backdrop" id="tptDrawerBackdrop" hidden></div>
        <aside class="tpt-drawer" id="tptDrawer" aria-hidden="true">
            <div class="tpt-drawer-header">
                <div class="tpt-drawer-title">Menu</div>
                <button class="tpt-drawer-close" id="tptDrawerClose" type="button" aria-label="Close">&times;</button>
            </div>
            <nav class="tpt-drawer-nav" aria-label="Sample sections">
                <a href="https://kuran.medine.net">Kur'an-ı Kerim</a>
                <a href="https://www.medine.net/nehculbelaga/">Nehcü'l-Belağa</a>
                <a href="https://www.medine.net/mefatih/">Dualar (Mefatih)</a>
                <a href="https://www.medine.net">Medine.net</a>
                
            </nav>
            <div class="tpt-drawer-divider"></div>
<label class="tpt-switch" for="tptDarkToggle">
                <input type="checkbox" id="tptDarkToggle">
                <span class="tpt-slider" aria-hidden="true"></span>
                <span class="tpt-switch-label">حالت دارک</span>
            </label>
        </aside>
        <div class="heading">
      <div class="left">
    <div class="dates-container">
        <div class="tpt-gregorian-with-week">
            <div class="date weekday-name" id="displayWeekday"></div>
            <div class="date gregorian-short" id="displayGregorianShort"></div>
        </div>
        <div class="hijri-date-full" id="displayHijriFull"></div>
        <div class="hijri-date-full hijri-date-full-2" id="displayHijriFull2" style="display:none;"></div>
        <div class="tpt-top-boxes" id="tptTopBoxes">
            <div class="talkofday-banner" id="talkofdayRow" aria-live="polite">
                <div class="talkofday-banner-header">
                    <img src="https://www.medine.net/takvim/wp-content/plugins/fprtr-plugin-religioustimes/icons/writing.svg" class="talkofday-icon" alt="">
                    <div class="talkofday-tabs" role="tablist" aria-label="Günün metni">
                        <button type="button" class="talkofday-tab is-active" data-tab="ayet" role="tab" aria-selected="true">Günün Ayeti</button>
                        <button type="button" class="talkofday-tab" data-tab="hadis" role="tab" aria-selected="false">Günün Hadisi</button>
                    </div>
                </div>
                <div class="talkofday-text talkofday-panel is-active" id="talkofdayText" data-panel="ayet" role="tabpanel"></div>
                <div class="talkofday-text talkofday-panel" id="dayhadisText" data-panel="hadis" role="tabpanel" hidden></div>
            </div>

                    </div>

        <div class="city-name-with-namaz" id="displayCityWithNamaz"></div>
    </div>
</div>
            <div class="right">
                <div class="current-time" id="currentTime">--:--:--</div>
                <div class="countdown" id="countdown">Next: --:--:--</div>
            </div>
        </div>
        <div class="prayers" id="prayersArea">
            <!-- Day navigation moved ABOVE the prayer grid (user request) -->
            <div class="day-nav-bar" id="dayNavBar" aria-label="Gün gezinme">
                <button type="button" class="day-nav-btn" id="prevDayBtn" aria-label="Önceki gün">&lsaquo;</button>
                <button type="button" class="day-nav-btn" id="nextDayBtn" aria-label="Sonraki gün">&rsaquo;</button>
                <!-- Hidden by default; becomes visible + red when user is not on today -->
                <button type="button" id="resetDateBtn" class="reset-date-btn is-hidden" title="Bugüne dön" aria-label="Bugüne dön">
                    <span class="reset-icon" aria-hidden="true"><img src="https://www.medine.net/takvim/wp-content/plugins/fprtr-plugin-religioustimes/icons/rest.svg" alt=""></span>
                    <span class="reset-text">Bugüne Dön</span>
                </button>
            </div>
            <div class="grid" id="prayerGrid"></div>
            <div class="extra-times" id="extraTimes" aria-label="Ek vakitler"></div>
        </div>
        <div class="search-row">
            <label for="provinceSelect">İl</label>
            <div class="location-select-wrap">
                <select id="provinceSelect" class="location-select" aria-label="İl seç"></select>
            </div>

            <label for="citySelect">İlçe</label>
            <div class="location-select-wrap">
                <select id="citySelect" class="location-select" aria-label="İlçe seç"></select>
                <div class="loader" id="inputLoader" title="loading">
                    <div class="spinner"></div>
                </div>
            </div>

            <!-- Keep hidden input for backward-compatible JS logic -->
            <input type="text" id="cityInput" class="city-input city-input-hidden" value="Istanbul" aria-hidden="true" tabindex="-1">
            <label for="daySelect"></label>
           <div class="date-input-wrap">
                <select id="daySelect" class="date-select"></select>
                <select id="monthSelect" class="date-select"></select>
                <select id="yearSelect" class="date-select"></select>
           </div>
        </div>
        <div class="occasions-section" id="occasionsSection">
            <div class="occasion-row" id="occasionRow">
                <img src="https://www.medine.net/takvim/wp-content/plugins/fprtr-plugin-religioustimes/icons/occasion.svg" class="occasion-icon" alt="">
                <div class="occasion-text" id="occasionText"></div>
            </div>
            <div class="occasion-row" id="noticeRow">
                <img src="https://www.medine.net/takvim/wp-content/plugins/fprtr-plugin-religioustimes/icons/notice.svg" class="occasion-icon" alt="">
                <div class="occasion-text" id="noticeText"></div>
            </div>
        </div>
        <div class="bottom-sections">
            <div class="month-events-section" id="monthEventsSection">
                <div class="month-events-title" id="monthEventsTitle">Ayın özel günleri</div>
                <div class="month-events-list" id="monthEventsList"></div>
            </div>
            <div class="monthly-timings-section" id="monthlyTimingsSection">
                <div class="monthly-timings-title" id="monthlyTimingsTitle">Istanbul Namaz Vakitleri (Yükleniyor...)</div>
                <div class="monthly-timings-table-wrap" id="tableWrapper">
                    <table class="monthly-timings-table" id="monthlyTimingsTable">
                        <thead>
                            <tr>
                                <th>Miladi Tarih</th>
                                <th class="hijri-col">Hicri Tarih</th>
                                <th class="hijri2-col">Hicri</th>
                                <th>Sabah Namazı</th>
                                <th>Gün Doğumu</th>
                                <th>Öğle Namazı</th>
                                <th>İkindi Namazı</th>
                                <th>Gün Batımı</th>
                                <th>Akşam Namazı</th>
                                <th>Yatsı Namazı</th>
                                <th>Gece Yarısı</th>
                            </tr>
                        </thead>
                        <tbody></tbody>
                    </table>
                </div>
                <button type="button" class="monthly-more-btn" id="monthlyMoreBtn" hidden>Daha fazla</button>
                <div class="loader-wrap" id="monthlyTimingsLoader"><div class="spinner"></div></div>
            </div>
        </div>

        <!-- Today in History (Islamic / historical styled box) -->
        <div class="todayhistory-box" id="todayHistoryBox" aria-label="Tarihte Bugün" hidden>
            <div class="todayhistory-header">
                <span class="todayhistory-badge" aria-hidden="true">
                    <svg viewBox="0 0 24 24" width="18" height="18" xmlns="http://www.w3.org/2000/svg" fill="none">
                        <path d="M12 2a7.5 7.5 0 106.9 4.6 6.2 6.2 0 01-8.5 8.5A7.5 7.5 0 0012 2z" stroke="currentColor" stroke-width="1.6" stroke-linecap="round"/>
                        <path d="M12 7v5l3 2" stroke="currentColor" stroke-width="1.6" stroke-linecap="round" stroke-linejoin="round"/>
                    </svg>
                </span>
                <div class="todayhistory-title">Tarihte Bugün</div>
            </div>
            <div class="todayhistory-list" id="todayHistoryList"></div>
        </div>

        <!-- Popular cities shortcut (separate box, not inside the monthly list) -->
        <div class="popular-cities-box" id="popularCitiesBox" aria-label="Popüler şehirler">
            <div class="popular-cities-title">Popüler Şehirler</div>
            <div class="popular-cities-list" id="popularCitiesList">
                                    <button type="button" class="city-chip" data-city="Istanbul">
                        <span class="city-chip-icon" aria-hidden="true">
                            <svg viewBox="0 0 24 24" width="16" height="16" fill="none" xmlns="http://www.w3.org/2000/svg">
                                <path d="M12 22s7-4.5 7-11a7 7 0 10-14 0c0 6.5 7 11 7 11z" stroke="currentColor" stroke-width="1.6"/>
                                <path d="M12 12.5a2.5 2.5 0 100-5 2.5 2.5 0 000 5z" stroke="currentColor" stroke-width="1.6"/>
                            </svg>
                        </span>
                        <span class="city-chip-text">Istanbul</span>
                    </button>
                                    <button type="button" class="city-chip" data-city="Iğdır">
                        <span class="city-chip-icon" aria-hidden="true">
                            <svg viewBox="0 0 24 24" width="16" height="16" fill="none" xmlns="http://www.w3.org/2000/svg">
                                <path d="M12 22s7-4.5 7-11a7 7 0 10-14 0c0 6.5 7 11 7 11z" stroke="currentColor" stroke-width="1.6"/>
                                <path d="M12 12.5a2.5 2.5 0 100-5 2.5 2.5 0 000 5z" stroke="currentColor" stroke-width="1.6"/>
                            </svg>
                        </span>
                        <span class="city-chip-text">Iğdır</span>
                    </button>
                                    <button type="button" class="city-chip" data-city="Kars">
                        <span class="city-chip-icon" aria-hidden="true">
                            <svg viewBox="0 0 24 24" width="16" height="16" fill="none" xmlns="http://www.w3.org/2000/svg">
                                <path d="M12 22s7-4.5 7-11a7 7 0 10-14 0c0 6.5 7 11 7 11z" stroke="currentColor" stroke-width="1.6"/>
                                <path d="M12 12.5a2.5 2.5 0 100-5 2.5 2.5 0 000 5z" stroke="currentColor" stroke-width="1.6"/>
                            </svg>
                        </span>
                        <span class="city-chip-text">Kars</span>
                    </button>
                                    <button type="button" class="city-chip" data-city="Ankara">
                        <span class="city-chip-icon" aria-hidden="true">
                            <svg viewBox="0 0 24 24" width="16" height="16" fill="none" xmlns="http://www.w3.org/2000/svg">
                                <path d="M12 22s7-4.5 7-11a7 7 0 10-14 0c0 6.5 7 11 7 11z" stroke="currentColor" stroke-width="1.6"/>
                                <path d="M12 12.5a2.5 2.5 0 100-5 2.5 2.5 0 000 5z" stroke="currentColor" stroke-width="1.6"/>
                            </svg>
                        </span>
                        <span class="city-chip-text">Ankara</span>
                    </button>
                                    <button type="button" class="city-chip" data-city="İzmir">
                        <span class="city-chip-icon" aria-hidden="true">
                            <svg viewBox="0 0 24 24" width="16" height="16" fill="none" xmlns="http://www.w3.org/2000/svg">
                                <path d="M12 22s7-4.5 7-11a7 7 0 10-14 0c0 6.5 7 11 7 11z" stroke="currentColor" stroke-width="1.6"/>
                                <path d="M12 12.5a2.5 2.5 0 100-5 2.5 2.5 0 000 5z" stroke="currentColor" stroke-width="1.6"/>
                            </svg>
                        </span>
                        <span class="city-chip-text">İzmir</span>
                    </button>
                                    <button type="button" class="city-chip" data-city="Bursa">
                        <span class="city-chip-icon" aria-hidden="true">
                            <svg viewBox="0 0 24 24" width="16" height="16" fill="none" xmlns="http://www.w3.org/2000/svg">
                                <path d="M12 22s7-4.5 7-11a7 7 0 10-14 0c0 6.5 7 11 7 11z" stroke="currentColor" stroke-width="1.6"/>
                                <path d="M12 12.5a2.5 2.5 0 100-5 2.5 2.5 0 000 5z" stroke="currentColor" stroke-width="1.6"/>
                            </svg>
                        </span>
                        <span class="city-chip-text">Bursa</span>
                    </button>
                                    <button type="button" class="city-chip" data-city="Adana">
                        <span class="city-chip-icon" aria-hidden="true">
                            <svg viewBox="0 0 24 24" width="16" height="16" fill="none" xmlns="http://www.w3.org/2000/svg">
                                <path d="M12 22s7-4.5 7-11a7 7 0 10-14 0c0 6.5 7 11 7 11z" stroke="currentColor" stroke-width="1.6"/>
                                <path d="M12 12.5a2.5 2.5 0 100-5 2.5 2.5 0 000 5z" stroke="currentColor" stroke-width="1.6"/>
                            </svg>
                        </span>
                        <span class="city-chip-text">Adana</span>
                    </button>
                                    <button type="button" class="city-chip" data-city="Konya">
                        <span class="city-chip-icon" aria-hidden="true">
                            <svg viewBox="0 0 24 24" width="16" height="16" fill="none" xmlns="http://www.w3.org/2000/svg">
                                <path d="M12 22s7-4.5 7-11a7 7 0 10-14 0c0 6.5 7 11 7 11z" stroke="currentColor" stroke-width="1.6"/>
                                <path d="M12 12.5a2.5 2.5 0 100-5 2.5 2.5 0 000 5z" stroke="currentColor" stroke-width="1.6"/>
                            </svg>
                        </span>
                        <span class="city-chip-text">Konya</span>
                    </button>
                                    <button type="button" class="city-chip" data-city="Gaziantep">
                        <span class="city-chip-icon" aria-hidden="true">
                            <svg viewBox="0 0 24 24" width="16" height="16" fill="none" xmlns="http://www.w3.org/2000/svg">
                                <path d="M12 22s7-4.5 7-11a7 7 0 10-14 0c0 6.5 7 11 7 11z" stroke="currentColor" stroke-width="1.6"/>
                                <path d="M12 12.5a2.5 2.5 0 100-5 2.5 2.5 0 000 5z" stroke="currentColor" stroke-width="1.6"/>
                            </svg>
                        </span>
                        <span class="city-chip-text">Gaziantep</span>
                    </button>
                            </div>
        </div>

        <!-- Sample sections (anchors for hamburger menu) -->
        <div id="tpt-section-1"></div>
        <div id="tpt-section-2"></div>
        <div id="tpt-section-3"></div>
        <div id="tpt-section-4"></div>
        <div id="tpt-section-5"></div>

        <div class="tpt-footer">
            <span>Tüm hakları saklıdır</span>
        </div>

        <!-- Sample anchor targets (for the hamburger menu) -->
        <div id="tpt-section-1" style="height:1px"></div>
        <div id="tpt-section-2" style="height:1px"></div>
        <div id="tpt-section-3" style="height:1px"></div>
        <div id="tpt-section-4" style="height:1px"></div>
        <div id="tpt-section-5" style="height:1px"></div>

    </div>
</div>
<script>
// ------------------------------------------------------------
// Hamburger drawer + Dark mode toggle
// ------------------------------------------------------------
(function(){
    const drawer = document.getElementById('tptDrawer');
    const backdrop = document.getElementById('tptDrawerBackdrop');
    const openBtn = document.getElementById('tptHamburgerBtn');
    const closeBtn = document.getElementById('tptDrawerClose');
    const toggle = document.getElementById('tptDarkToggle');
    if(!drawer || !backdrop || !openBtn || !closeBtn) return;

    const setDrawer = (isOpen) => {
        drawer.classList.toggle('is-open', isOpen);
        drawer.setAttribute('aria-hidden', isOpen ? 'false' : 'true');
        backdrop.hidden = !isOpen;
        if (isOpen) {
            document.body.style.overflow = 'hidden';
        } else {
            document.body.style.overflow = '';
        }
    };

    openBtn.addEventListener('click', () => setDrawer(true));
    closeBtn.addEventListener('click', () => setDrawer(false));
    backdrop.addEventListener('click', () => setDrawer(false));
    document.addEventListener('keydown', (e) => {
        if (e.key === 'Escape') setDrawer(false);
    });
    drawer.querySelectorAll('a').forEach(a => a.addEventListener('click', () => setDrawer(false)));

    // --------------------------
    // Dark mode toggle (if enabled)
    // --------------------------
    if (toggle) {
        const applyDark = (enabled) => {
            document.body.classList.toggle('tpt-dark', !!enabled);
            try { localStorage.setItem('tpt_dark_mode', enabled ? '1' : '0'); } catch(e) {}
        };
        let saved = '0';
        try { saved = localStorage.getItem('tpt_dark_mode') || '0'; } catch(e) {}
        const initial = saved === '1';
        toggle.checked = initial;
        applyDark(initial);
        toggle.addEventListener('change', () => applyDark(toggle.checked));
    }
})();

const cityAndProvinces = {"Adana":["Alada\u011f","Ceyhan","\u00c7ukurova","Feke","\u0130mamo\u011flu","Karaisal\u0131","Karata\u015f","Kozan","Pozant\u0131","Saimbeyli","Seyhan","Tufanbeyli","Yumurtal\u0131k"],"Ad\u0131yaman":["Besni","\u00c7elikhan","Gerger","G\u00f6lba\u015f\u0131","Kahta","Merkez","Samsat","Sincik","Tut"],"Afyonkarahisar":["Ba\u015fmak\u00e7\u0131","Bayat","Bozk\u0131r","Buldan","\u00c7ay","\u00c7obanlar","Dazk\u0131r\u0131","Dinar","Dombay","Emirda\u011f","Evciler","Hocalar","\u0130hsaniye","\u0130scehisar","K\u0131z\u0131l\u00f6ren","Merkez","Sand\u0131kl\u0131","Sinanpa\u015fa","Sultanda\u011f\u0131","\u015euhut"],"A\u011fr\u0131":["Diyadin","Do\u011fubayaz\u0131t","Ele\u015fkirt","Hamur","Merkez","Patnos","Ta\u015fl\u0131\u00e7ay","Tutak"],"Aksaray":["A\u011fa\u00e7\u00f6ren","Eskil","G\u00fcla\u011fa\u00e7","G\u00fczelyurt","Merkez","Ortak\u00f6y","Sar\u0131yah\u015fi","Sultanhan\u0131"],"Amasya":["G\u00f6yn\u00fccek","G\u00fcm\u00fc\u015fhac\u0131k\u00f6y","Hamam\u00f6z\u00fc","Merkez","Merzifon","Samsun","Ta\u015fova","T\u00fcrkey"],"Ankara":["Akyurt","Alt\u0131nda\u011f","Aya\u015f","Bala","Beypazar\u0131","\u00c7aml\u0131dere","\u00c7ankaya","\u00c7ubuk","Elmada\u011f","Etimesgut","Evren","G\u00f6lba\u015f\u0131","G\u00fcd\u00fcl","Haymana","Kahramankazan","Kalecik","Ke\u00e7i\u00f6ren","K\u0131z\u0131lcahamam","Mamak","Nall\u0131han","Polatl\u0131","Purakkale","Sincan","\u015eerefliko\u00e7hisar","Yenimahalle"],"Antalya":["Akseki","Aksu","Alanya","Demre","D\u00f6\u015femalt\u0131","Elmal\u0131","Finike","Gazipa\u015fa","G\u00fcndo\u011fmu\u015f","\u0130brad\u0131","Ka\u015f","Kemer","Konyaalt\u0131","Korkuteli","Manavgat","Muratpa\u015fa","Serik"],"Ardahan":["\u00c7\u0131ld\u0131r","Damal","G\u00f6le","Hanak","Merkez","Yal\u00e7\u0131nkaya"],"Artvin":["Ardanu\u00e7","Arhavi","Bor\u00e7ka","Hopa","Kemalpasa","Merkez","Murgul","\u015eav\u015fat","Yusufeli"],"Ayd\u0131n":["Bozdo\u011fan","Buharkent","\u00c7ine","Didim","Efeler","Germencik","\u0130ncirliova","Karacasu","Karpuzlu","Ko\u00e7arl\u0131","K\u00f6\u015fk","Ku\u015fadas\u0131","Kuyucak","Nazilli","S\u00f6ke","Sultanhisar","Yenipazar"],"Bal\u0131kesir":["Alt\u0131eyl\u00fcl","Ayval\u0131k","Band\u0131rma","Bigadi\u00e7","Burhaniye","Dursunbey","Edremit","Erdek","G\u00f6nen","Havran","\u0130kizk\u00f6y","\u0130vrindi","Kepsut","Koca Seyit","Metropolis","Most","Most","Sava\u015ftepe","S\u0131nd\u0131rg\u0131","Susurluk"],"Bart\u0131n":["Kozca\u011f\u0131z","Merkez","Ulus"],"Batman":["Be\u015firi","Gerc\u00fc\u015f","Hasankeyf","Merkez","Sason"],"Bayburt":["Ayd\u0131ntepe","Demir\u00f6z\u00fc","Merkez"],"Bilecik":["Boz\u00fcy\u00fck","G\u00f6lpazar\u0131","\u0130nhisar","Merkez","Osmaneli","Pazaryeri","S\u00f6\u011f\u00fct","Yenipazar"],"Bing\u00f6l":["Gen\u00e7","Karl\u0131ova","K\u0131\u011f\u0131","Merkez","Solhan","Yayladere","Yedisu"],"Bitlis":["Adilcevaz","Ahlat","G\u00fcroymak","Hizan","Merkez","Mutki","Tatvan"],"Bolu":["D\u00f6rtdivan","Gerede","G\u00f6lk\u00f6y","K\u0131br\u0131sc\u0131k","Mengen","Merkez","Mudurnu","Seben","Yeni\u00e7a\u011fa"],"Burdur":["A\u011flasun","Alt\u0131nyayla","\u00c7avd\u0131r","G\u00f6lhisar","Karamanl\u0131","Kemer","Merkez","Tefenni","Ye\u015filova"],"Bursa":["B\u00fcy\u00fckorhan","Gemlik","G\u00fcrsu","Harmanc\u0131k","\u0130neg\u00f6l","\u0130znik","Karacabey","Keles","Kestel","Mudanya","Mustafakemalpa\u015fa","Nil\u00fcfer","Orhaneli","Orhangazi","Osmangazi","Yeni\u015fehir","Y\u0131ld\u0131r\u0131m"],"\u00c7anakkale":["Ayvac\u0131k","Bayrami\u00e7","Biga","Bozcaada","\u00c7an","Eceabat","Ezine","Gelibolu","G\u00f6k\u00e7eada","Lapseki","Merkez","Yenice"],"\u00c7ank\u0131r\u0131":["A\u011fl\u0131","Atkaracalar","Bayram\u00f6ren","\u00c7erke\u015f","Eldivan","Ilgaz","K\u0131z\u0131l\u0131rmak","Kur\u015funlu","Merkez","Orta","\u015eaban\u00f6z\u00fc","Yaprakl\u0131"],"\u00c7orum":["Alaca","Bayat","Bo\u011fazkale","Dodurga","Far\u0131ll\u0131","\u0130skilip","Karg\u0131","La\u00e7in","Merkez","Ortak\u00f6y","Osmanc\u0131k","Sungurlu","Sungurlu"],"Denizli":["Ac\u0131payam","Babada\u011f","Baklan","Bekilli","Beya\u011fa\u00e7","Bozkurt","Buldan","\u00c7ameli","\u00c7ardak","\u00c7ivril","Honaz","Kale","Merkezefendi","Pamukkale","Sarayk\u00f6y","Serinhisar","Tavas"],"Diyarbak\u0131r":["Ba\u011flar","Bismil","\u00c7ermik","\u00c7\u0131nar","\u00c7\u00fcng\u00fc\u015f","Dicle","E\u011fil","Ergani","Hani","Hazro","Kocak\u00f6y","Kulp","Lice","Silvan","Sur","Yeni\u015fehir"],"D\u00fczce":["Ak\u00e7akoca","Cumayeri","\u00c7ilimli","G\u00f6lorman\u0131","G\u00fcm\u00fc\u015fova","Kayna\u015fl\u0131","Merkez","Y\u0131\u011f\u0131lca"],"Edirne":["Enez","Haveza","\u0130psala","Ke\u015fan","Lalapa\u015fa","Merkez","Mer\u0131\u00e7","S\u00fclo\u011flu","Uzunk\u00f6pr\u00fc"],"Elaz\u0131\u011f":["A\u011f\u0131n","Alacakaya","Ar\u0131cak","Diyarbak\u0131r","Karako\u00e7an","Kovanc\u0131lar","Maden","Merkez","Palu","Sivrice"],"Erzincan":["\u00c7ay\u0131rl\u0131","\u0130li\u00e7","Kemah","Kemaliye","Merkez","Otlukbeli","Refahiye","Tercan","\u00dcz\u00fcml\u00fc"],"Erzurum":["A\u015fkale","Aziziye","\u00c7at","H\u0131n\u0131s","Horasan","\u0130li\u00e7","\u0130spir","Kara\u00e7oban","Karayaz\u0131","Korkut","K\u00f6pr\u00fck\u00f6y","Merkez","Narman","Oltu","Olur","Paland\u00f6ken","Pazaryolu","Tekman","Tortum","Yakutiye"],"Eski\u015fehir":["Alpu","Beylikova","\u00c7ifteler","\u0130n\u00f6n\u00fc","Mahmudiye","Merkez","Mihal\u0131\u00e7\u00e7\u0131k","Mihalgazi","Odunpazar\u0131","Sar\u0131cakaya","Seyhi\u015fehir","Sivrihisar"],"Gaziantep":["Araban","\u0130slahiye","Karkam\u0131\u015f","Nizip","Nurda\u011f\u0131","O\u011fuzeli","\u015eahinbey","\u015eehitkamil","Yavuzeli"],"Giresun":["Alucra","Bulancak","\u00c7amoluk","\u00c7anak\u00e7\u0131","Dereli","Do\u011fankent","Eynesil","Espiye","Etlik","G\u00f6rele","G\u00fcce","Merkez","Piraziz","\u015eebinkarahisar","Tirebolu","Ya\u011fl\u0131dere"],"G\u00fcm\u00fc\u015fhane":["Kelkit","K\u00f6se","K\u00fcmbet","Merkez","Ni\u015fanta\u015f\u0131","\u015eiran","Torul"],"Hakk\u00e2ri":["\u00c7ukurca","Derecik","Merkez","\u015eemdinli","Y\u00fcksekova"],"Hatay":["Alt\u0131n\u00f6z\u00fc","Arsuz","Belen","D\u00f6rtyol","Erzin","Hassa","\u0130skenderun","K\u0131r\u0131khan","Kuveytli","Merkez","Reyhanl\u0131","Samanda\u011f","Yaylada\u011f\u0131"],"I\u011fd\u0131r":["Aral\u0131k","Karakoyunlu","Merkez","Tuzluca"],"Isparta":["Aksu","Atabey","E\u011firdir","Gelendost","G\u00f6nen","Merkez","Senirkent","S\u00fct\u00e7\u00fcler","\u015earkikaraa\u011fa\u00e7","Uluborlu","Yalva\u00e7"],"\u0130stanbul":["Adalar","Arnavutk\u00f6y","Ata\u015fehir","Avc\u0131lar","Ba\u011fc\u0131lar","Bah\u00e7elievler","Bak\u0131rk\u00f6y","Ba\u015fak\u015fehir","Ba\u015f\u0131b\u00fcy\u00fck","Bayrampa\u015fa","Be\u015fikta\u015f","Beykoz","Beylikd\u00fcz\u00fc","Beyo\u011flu","B\u00fcy\u00fck\u00e7ekmece","\u00c7atalca","\u00c7ekmek\u00f6y","Esenler","Esenyurt","Ey\u00fcpsultan","Fatih","Gaziosmanpa\u015fa","G\u00fcng\u00f6ren","Kad\u0131k\u00f6y","Ka\u011f\u0131thane","K\u00fc\u00e7\u00fck\u00e7ekmece","Maltepe","Pendik","Sancaktepe","Sar\u0131yer","Silivri","Sultanbeyli","Sultangazi","\u015eile","\u015ei\u015fli","Tuzla","\u00dcmraniye","\u00dcsk\u00fcdar","Zeytinburnu"],"\u0130zmir":["Alia\u011fa","Alsancak","Bal\u00e7ova","Bay\u0131nd\u0131r","Bayrakl\u0131","Bergama","Bornova","Buca","\u00c7e\u015fme","\u00c7i\u011fli","Dickli","Dikili","Fo\u00e7a","Gaziemir","G\u00fczelbah\u00e7e","Karaba\u011flar","Karaburun","Kemalpa\u015fa","K\u0131n\u0131k","Kiraz","Konak","Menderes","Menemen","Narl\u0131dere","\u00d6demi\u015f","Seferihisar","Sel\u00e7uk","Tire","Torbal\u0131","Urla"],"Kahramanmara\u015f":["Af\u015fin","And\u0131r\u0131n","\u00c7a\u011flayancerit","Dulkadiro\u011flu","Ekin\u00f6z\u00fc","Elbistan","Merkez","Nurhak","Oniki\u015fubat","Pazarc\u0131k","Tipi","T\u00fcrko\u011flu"],"Karab\u00fck":["Eflani","Eskipazar","Merkez","Ovac\u0131k","Safranbolu","Yenice"],"Karaman":["Ayranc\u0131","Ba\u015fyayla","Ermenek","Kaz\u0131mkarabekir","Merkez","Sar\u0131veliler"],"Kars":["Akyaka","Arpa\u00e7ay","Digor","Ka\u011f\u0131zman","Merkez","Sar\u0131kam\u0131\u015f","Selim","Susuz"],"Kastamonu":["Abana","A\u011fl\u0131","Ara\u00e7","Aziziye","Bozkurt","Cide","\u00c7atalzeytin","Daday","Devrekani","Han\u00f6n\u00fc","\u0130hsangazi","\u0130nebolu","K\u00fcre","Merkez","P\u0131narba\u015f\u0131","Seydiler","Ta\u015fk\u00f6pr\u00fc","Tosya"],"Kayseri":["Akk\u0131\u015fla","B\u00fcnyan","Develi","Felahiye","Hac\u0131lar","Hisarc\u0131k","\u0130ncesu","Kocasinan","Melikgazi","\u00d6zvatan","P\u0131narba\u015f\u0131","Sar\u0131o\u011flan","Sar\u0131z","Talas","Tomarza","Yahyal\u0131","Ye\u015filhisar"],"Kilis":["Elbeyli","Merkez","Musabeyli","Polateli"],"K\u0131r\u0131kkale":["Bah\u015fili","Bal\u0131\u015feyh","\u00c7elebi","Delice","Karake\u00e7ili","Keskin","Merkez","Sulakyurt","Yah\u015fihan"],"K\u0131rklareli":["Babaeski","Demirk\u00f6y","Kof\u00e7az","L\u00fcleburgaz","Merkez","Pehlivank\u00f6y","P\u0131narhisar","Vize"],"K\u0131r\u015fehir":["Akp\u0131nar","Boztepe","\u00c7i\u00e7ekda\u011f\u0131","Kaman","Merkez","Mucur"],"Kocaeli":["Ba\u015fiskele","\u00c7ay\u0131rova","Dar\u0131ca","Derince","Dilovas\u0131","Gebze","G\u00f6lc\u00fck","\u0130zmit","Kand\u0131ra","Karam\u00fcrsel","K\u00f6rfez"],"Konya":["Ak\u00f6ren","Ak\u015fehir","Alt\u0131nekin","Bey\u015fehir","Bozk\u0131r","Cihanbeyli","\u00c7eltik","\u00c7umra","Derebucak","Do\u011fanhisar","Emirgazi","G\u00fcneys\u0131n\u0131r","Hadim","Halkap\u0131nar","H\u00fcy\u00fck","Ilg\u0131n","Kad\u0131nhan\u0131","Karap\u0131nar","Karatay","Kulu","Meram","Merkez","Seydi\u015fehir","Sel\u00e7uklu","Seydi\u015fehir","Ta\u015fkent","Tuzluk\u00e7u","Yal\u0131h\u00fcy\u00fck","Yunak"],"K\u00fctahya":["Alt\u0131nta\u015fa","Aslanapa","\u00c7avdarhisar","Doman","Domani\u00e7","Emet","Gediz","Hisarc\u0131k","K\u0131z\u0131lca\u00f6ren","Merkez","Muradiye","Pazar","\u015eaphane","Simav","Tav\u015fanl\u0131"],"Malatya":["Akalan","Arapgir","Arguvan","Battalgazi","Do\u011fan\u015fehir","Do\u011fanyol","Hekimhan","Kale","Kampana","Kuluncak","Merkez","P\u00fct\u00fcrge","Ye\u015filyurt","Y\u0131ld\u0131zhan"],"Manisa":["Ala\u015fehir","Demirci","G\u00f6rdes","G\u00fczelyurt","K\u0131rka\u011fa\u00e7","K\u00f6pr\u00fcba\u015f\u0131","Kula","Merkez","Salihli","Saruhanl\u0131","Sava\u015ftepe","Selendi","Soma","Sultanda\u011f\u0131","\u015eehzadeler","Turgutlu","Yunusemre"],"Mardin":["Artuklu","Darge\u00e7it","Derik","K\u0131z\u0131ltepe","Maz\u0131da\u011f\u0131","Merkez","Midyat","Nusaybin","\u00d6merli","Savur","Ye\u015filli"],"Mersin":["Aksaray","Anamur","Bozyaz\u0131","\u00c7aml\u0131yayla","Erdemli","G\u00fclnar","G\u00fcneys\u0131n\u0131r","Mezitli","Mut","Yeni\u015fehir","Silifke","Tarsus"],"Mu\u011fla":["Bodrum","Dalaman","Dat\u00e7a","Fethiye","Kavakl\u0131dere","K\u00f6yce\u011fiz","Marmaris","Merkez","Milas","Ortaca","Seydikemer","Ula","Yata\u011fan"],"Mu\u015f":["Bulan\u0131k","Hask\u00f6y","Korkut","Malazgirt","Merkez","Varto"],"Nev\u015fehir":["Acre","Avanos","Derinkuyu","G\u00fcl\u015fehir","Hac\u0131bekta\u015f","Kozakli","Merkez","\u00dcrg\u00fcp"],"Ni\u011fde":["Adana","Aksaray","Altunhisar","Bor","\u00c7iftlik","Merkez","Uluk\u0131\u015fla"],"Ordu":["Alt\u0131nordu","Aybast\u0131","\u00c7ama\u015f","\u00c7atalp\u0131nar","Fatma","G\u00f6lk\u00f6y","G\u00fclyal\u0131","G\u00fcrgentepe","Han\u00f6n\u00fc","Kabata\u015f","Kabad\u00fcz","Korgan","Mesudiye","Per\u015fembe","Ulubey","\u00dcnye"],"Osmaniye":["Bah\u00e7e","D\u00fczi\u00e7i","Hask\u00f6y","Kadirli","Merkez","Sumbas","Toprakkale","K\u0131ra\u00e7"],"Rize":["Arde\u015fen","\u00c7aml\u0131hem\u015fin","F\u0131nd\u0131kl\u0131","G\u00fcndo\u011fmu\u015f","Hem\u015fin","\u0130kizdere","Kalkandere","Merkez","Pazar"],"Sakarya":["Adapazar\u0131","Arifiye","Erenler","Eski\u015fehir","Ferizli","Geyve","Hendek","Karap\u00fcr\u00e7ek","Kocaali","Pamukova","Sapanca","Serdivan","Tarakl\u0131"],"Samsun":["19 May\u0131s","Ala\u00e7am","Asarc\u0131k","Atakum","Ayvac\u0131k","Bafra","Balli","Canik","\u00c7ar\u015famba","Havza","H\u0131rami","\u0130lkad\u0131m","Kavak","Ladik","Merkez","Ondokuzmay\u0131s","Sal\u0131pazar\u0131","Tekkek\u00f6y","Terme","Vezirk\u00f6pr\u00fc","Yakakent"],"\u015eanl\u0131urfa":["Ak\u00e7akale","Birecik","Bo\u011fazl\u0131yan","Ceylanp\u0131nar","Eyy\u00fcbiye","Halfeti","Harran","Hilvan","Karak\u00f6pr\u00fc","K\u0131z\u0131l\u00f6ren","Merkez","Siverek","Suru\u00e7","Virangehir"],"Siirt":["Baykan","Eruh","Kurtalan","Merkez","Pervari","\u015eirvan","Tillo"],"Sinop":["Ayanc\u0131k","Boyabat","Dikmen","Dura\u011fan","Erfelek","Gerze","Merkez","Sarayd\u00fcz\u00fc","T\u00fcrkeli"],"\u015e\u0131rnak":["Beyt\u00fc\u015f\u015febap","Cizre","G\u00fc\u00e7l\u00fckonak","\u0130dil","Merkez","Silopi","Uludere"],"Sivas":["Ak\u0131nc\u0131lar","Alt\u0131nyayla","Divri\u011fi","Do\u011fan\u015far","G\u00f6lova","G\u00fcr\u00fcn","Hafik","\u0130mranl\u0131","Kangal","Koyulhisar","Merkez","\u015eark\u0131\u015fla","Su\u015fehri","Ula\u015f","Y\u0131ld\u0131zeli","Zara"],"Tekirda\u011f":["\u00c7erkezk\u00f6y","\u00c7orlu","Ergene","Hayrabolu","Kapakl\u0131","Malkara","Marmaraere\u011flisi","Merkez","Sar\u0131ayvaz","\u015eark\u00f6y","S\u00fcleymanpa\u015fa"],"Tokat":["Almus","Artova","Ba\u015f\u00e7iftlik","Erbaa","Merkez","Niksar","Pazar","Re\u015fadiye","Sulusaray","Turhal","Ye\u015filyurt","Zile"],"Trabzon":["Ak\u00e7aabat","Arakl\u0131","Arsin","Be\u015fikd\u00fcz\u00fc","\u00c7ar\u015f\u0131ba\u015f\u0131","\u00c7aykara","Dernekpazar\u0131","D\u00fczk\u00f6y","Hayrat","K\u00f6pr\u00fcba\u015f\u0131","Ma\u00e7ka","Merkez","Of","Ortahisar","\u015ealpazar\u0131","S\u00fcrmene","Tonya","Vakf\u0131kebir","Yomra"],"Tunceli":["\u00c7emi\u015fgezek","Hozat","Mazgirt","Merkez","Naz\u0131miye","Ovac\u0131k","P\u00fcl\u00fcm\u00fcr"],"U\u015fak":["Banaz","E\u015fme","Karahall\u0131","Merkez","Sivasl\u0131","Ulubey"],"Van":["Bah\u00e7esaray","Ba\u015fkale","\u00c7ald\u0131ran","\u00c7atak","Erci\u015f","Geva\u015f","G\u00fcrp\u0131nar","\u0130pekyolu","Merkez","Muradiye","\u00d6zalp","Saray","Tu\u015fba"],"Yalova":["Alt\u0131nova","Armutlu","\u00c7iftlikk\u00f6y","Merkez","Termal"],"Yozgat":["Ayd\u0131nc\u0131k","Bozok","\u00c7and\u0131r","\u00c7ekerek","\u00c7i\u00e7ekda\u011f\u0131","Kad\u0131\u015fehri","Merkez","Sar\u0131kaya","Sorgun","\u015eefaatli","Yenifak\u0131l\u0131","Yozgat"],"Zonguldak":["Alapl\u0131","\u00c7aycuma","Devrek","Ere\u011fli","G\u00f6k\u00e7ebey","Kilimli","Merkez","Terakki"]};
const initialTimingsRaw = null;
const defaultMethod = 13;
const defaultCountry = "Turkey";
const timezone = 'Europe/Istanbul';
const ASSET_BASE = "https:\/\/www.medine.net\/takvim\/wp-content\/plugins\/fprtr-plugin-religioustimes";
// When this page is opened via a pretty permalink (e.g. /takvim),
// relative fetch("?action=...") requests will hit WordPress and won’t reach
// this PHP file. Always call back into this file for JSON endpoints.
const HIJRI_CALC_MODE = "api";
const AJAX_BASE =  "https:\/\/www.medine.net\/takvim\/wp-content\/plugins\/fprtr-plugin-religioustimes\/fullpage.php";
let intervalId = null;
let tomorrowTimings = null;
const provincesList = Object.keys(cityAndProvinces).sort();
let selectedProvince = null;
let suggestionsList = [];
for (const prov in cityAndProvinces) {
    const arr = cityAndProvinces[prov];
    if (Array.isArray(arr)) {
        arr.forEach(city => suggestionsList.push(city + ', ' + prov));
    }
}
if (!suggestionsList.includes('Istanbul, Istanbul')) suggestionsList.unshift('Istanbul, Istanbul');
const PRAYER_KEYS = [
    {key:'Fajr', name:'Sabah Namazı', icon: ASSET_BASE + '/icons/fajr.svg'},
    {key:'Sunrise', name:'Güneş Doğuşu', icon: ASSET_BASE + '/icons/sunrise.svg'},
    {key:'Dhuhr', name:'Öğle Namazı', icon: ASSET_BASE + '/icons/dhuhr.svg'},
    {key:'Asr', name:'İkindi Namazı', icon: ASSET_BASE + '/icons/asr.svg'},
    {key:'Maghrib', name:'Akşam Namazı', icon: ASSET_BASE + '/icons/maghrib.svg'},
    {key:'Isha', name:'Yatsı Namazı', icon: ASSET_BASE + '/icons/isha.svg'},
];

const WEEKDAYS_TR = {
  Sunday: 'Pazar', Monday: 'Pazartesi', Tuesday: 'Salı', Wednesday: 'Çarşamba',
  Thursday: 'Perşembe', Friday: 'Cuma', Saturday: 'Cumartesi'
};
const MONTHS_EN_TO_TR = {
  Jan:'Ocak', Feb:'Şubat', Mar:'Mart', Apr:'Nisan', May:'Mayıs', Jun:'Haziran',
  Jul:'Temmuz', Aug:'Ağustos', Sep:'Eylül', Oct:'Ekim', Nov:'Kasım', Dec:'Aralık'
};
const MONTHS_FULL_EN_TO_TR = {
  January:'Ocak', February:'Şubat', March:'Mart', April:'Nisan', May:'Mayıs', June:'Haziran',
  July:'Temmuz', August:'Ağustos', September:'Eylül', October:'Ekim', November:'Kasım', December:'Aralık'
};
const HIJRI_MONTHS_EN_TO_TR = {
  'Muḥarram':'Muharrem',
  'Ṣafar':'Safer',
  "Rabīʿ al-awwal":'Rebiülevvel',
  "Rabīʿ al-thānī":'Rebiülahir',
  'Jumādá al-ūlá':'Cemaziyelevvel',
  'Jumādá al-ākhirah':'Cemaziyelahir',
  'Rajab':'Recep',
  "Shaʿbān":'Şaban',
  'Ramaḍān':'Ramazan',
  'Shawwāl':'Şevval',
  "Dhū al-Qaʿdah":'Zilkade',
  'Dhū al-Ḥijjah':'Zilhicce'
};
// Normalize strings coming from the API (sometimes includes diacritics, e.g. "Muḥarram", "Ṣafar", "Dhū").
// Strip diacritics so our lookup keys match reliably.
function _normKey(s){
  return String(s||'')
    .normalize('NFD')
    .replace(/[\u0300-\u036f]/g,'')
    .toLowerCase()
    .replace(/[^a-z0-9]+/g,'');
}
const HIJRI_MONTHS_NORM = Object.fromEntries(Object.entries(HIJRI_MONTHS_EN_TO_TR).map(([k,v]) => [_normKey(k), v]));
function trWeekday(en){ return WEEKDAYS_TR[en] || en || ''; }
function trMonthAbbr(en){ return MONTHS_EN_TO_TR[en] || en || ''; }
function trMonth(en){ return MONTHS_FULL_EN_TO_TR[en] || MONTHS_EN_TO_TR[en] || en || ''; }
function trHijriMonth(en){ return HIJRI_MONTHS_EN_TO_TR[en] || HIJRI_MONTHS_NORM[_normKey(en)] || en || ''; }

const COUNTDOWN_KEYS = [
    {key:'Imsak', name:'İmsak'},
    {key:'Fajr', name:'Sabah Namazı'},
    {key:'Sunrise', name:'Güneş Doğuşu'},
    {key:'Dhuhr', name:'Öğle Namazı'},
    {key:'Asr', name:'İkindi Namazı'},
    {key:'Sunset', name:'Güneş Batışı'},
    {key:'Maghrib', name:'Akşam Namazı'},
    {key:'Isha', name:'Yatsı Namazı'},
    {key:'Midnight', name:'Gece Yarısı'},
];
function pad(num) { return num.toString().padStart(2, '0'); }
let currentHijriDate = null;
// Location selectors
const provinceSelect = document.getElementById('provinceSelect');
const citySelect = document.getElementById('citySelect');
// Keep a hidden city input so the rest of the page logic can continue to use `cityInput.value`
const cityInput = document.getElementById('cityInput');
const loader = document.getElementById('inputLoader');
const occasionsSection = document.getElementById('occasionsSection');
const occasionRow = document.getElementById('occasionRow');
const talkofdayRow = document.getElementById('talkofdayRow');
const noticeRow = document.getElementById('noticeRow');
const occasionText = document.getElementById('occasionText');
const talkofdayText = document.getElementById('talkofdayText');
const dayhadisText = document.getElementById('dayhadisText');
const talkofdayTabs = document.querySelectorAll('.talkofday-tab');
const noticeText = document.getElementById('noticeText');
const todayHistoryBox = document.getElementById('todayHistoryBox');
const todayHistoryList = document.getElementById('todayHistoryList');
const daySelect = document.getElementById('daySelect');
const monthSelect = document.getElementById('monthSelect');
const yearSelect = document.getElementById('yearSelect');
let suggestionVisible = false;
const initialProvinceValue = "İstanbul";
const initialCityValue = "Istanbul";
const initialDate = "05-07-2026";
let [initDay, initMonth, initYear] = initialDate.split('-');
cityInput.value = initialCityValue || '';
const months = ['01 - Ocak','02 - Şubat','03 - Mart','04 - Nisan','05 - Mayıs','06 - Haziran','07 - Temmuz','08 - Ağustos','09 - Eylül','10 - Ekim','11 - Kasım','12 - Aralık'];

// Verse/Hadith tabs (same box)
function setTalkTab(which) {
    const ayetBtn = document.querySelector('.talkofday-tab[data-tab="ayet"]');
    const hadisBtn = document.querySelector('.talkofday-tab[data-tab="hadis"]');
    const showAyet = (which === 'ayet');
    if (ayetBtn) {
        ayetBtn.classList.toggle('is-active', showAyet);
        ayetBtn.setAttribute('aria-selected', showAyet ? 'true' : 'false');
    }
    if (hadisBtn) {
        hadisBtn.classList.toggle('is-active', !showAyet);
        hadisBtn.setAttribute('aria-selected', !showAyet ? 'true' : 'false');
    }
    if (talkofdayText) {
        talkofdayText.classList.toggle('is-active', showAyet);
        talkofdayText.hidden = !showAyet;
    }
    if (dayhadisText) {
        dayhadisText.classList.toggle('is-active', !showAyet);
        dayhadisText.hidden = showAyet;
    }
}

if (talkofdayTabs && talkofdayTabs.length) {
    talkofdayTabs.forEach((btn) => {
        btn.addEventListener('click', () => {
            const t = btn.getAttribute('data-tab');
            if (t === 'ayet' || t === 'hadis') setTalkTab(t);
        });
    });
}
const currentYear = new Date().getFullYear();
for (let y = currentYear - 2; y <= currentYear + 2; y++) {
    const option = document.createElement('option');
    option.value = y; option.textContent = y; yearSelect.appendChild(option);
}
months.forEach(m => {
    const [num, name] = m.split(' - ');
    const option = document.createElement('option');
    option.value = num; option.textContent = m; monthSelect.appendChild(option);
});
for (let d = 1; d <= 31; d++) {
    const dayStr = d.toString().padStart(2, '0');
    const option = document.createElement('option');
    option.value = dayStr; option.textContent = dayStr; daySelect.appendChild(option);
}
daySelect.value = initDay.padStart(2, '0');
monthSelect.value = initMonth;
yearSelect.value = initYear;
// --- Province/City select logic ---
function buildProvinceOptions() {
    provinceSelect.innerHTML = '';
    provincesList.forEach(prov => {
        const opt = document.createElement('option');
        opt.value = prov;
        opt.textContent = prov;
        provinceSelect.appendChild(opt);
    });
}

function getCapitalCityValue(province) {
    // API-friendly special case for İstanbul (AlAdhan expects ASCII "Istanbul")
    if (province === 'İstanbul' || province === 'Istanbul') return 'Istanbul';
    return province;
}

function buildCityOptionsForProvince(province, preferredCityValue = '') {
    citySelect.innerHTML = '';
    const cities = Array.isArray(cityAndProvinces[province]) ? cityAndProvinces[province] : [];
    const capitalValue = getCapitalCityValue(province);

    // First option: the province center/capital (e.g., İstanbul -> Istanbul)
    const capOpt = document.createElement('option');
    capOpt.value = capitalValue;
    capOpt.textContent = province;
    citySelect.appendChild(capOpt);

    // Then districts
    cities.forEach(c => {
        const opt = document.createElement('option');
        opt.value = c;
        opt.textContent = c;
        citySelect.appendChild(opt);
    });

    // Select preferred city if present; otherwise keep capital
    const wanted = (preferredCityValue || '').trim();
    if (wanted) {
        const has = Array.from(citySelect.options).some(o => o.value === wanted);
        citySelect.value = has ? wanted : capitalValue;
    } else {
        citySelect.value = capitalValue;
    }
}

function syncHiddenCityInput() {
    cityInput.value = (citySelect.value || '').trim();
}

function initLocationSelects() {
    buildProvinceOptions();
    // Default province: İstanbul
    const defaultProv = (initialProvinceValue && initialProvinceValue.trim()) ? initialProvinceValue : (cityAndProvinces['İstanbul'] ? 'İstanbul' : (cityAndProvinces['Istanbul'] ? 'Istanbul' : provincesList[0]));
    provinceSelect.value = defaultProv;

    // Default city: "Istanbul" (center) when province is İstanbul; otherwise use provided city or province center
    let defaultCity = (initialCityValue && initialCityValue.trim()) ? initialCityValue.trim() : '';
    if ((defaultProv === 'İstanbul' || defaultProv === 'Istanbul') && !defaultCity) defaultCity = 'Istanbul';

    buildCityOptionsForProvince(defaultProv, defaultCity);
    syncHiddenCityInput();
}

provinceSelect.addEventListener('change', () => {
    const prov = provinceSelect.value;
    buildCityOptionsForProvince(prov, getCapitalCityValue(prov));
    syncHiddenCityInput();
    updateTimings();
});
citySelect.addEventListener('change', () => {
    syncHiddenCityInput();
    updateTimings();
});

['change'].forEach(ev => { daySelect.addEventListener(ev, updateTimings); monthSelect.addEventListener(ev, updateTimings); yearSelect.addEventListener(ev, updateTimings); });

// Initialize province/city selects now
initLocationSelects();

// ------------------------------------------------------------
// "Bugüne Dön" button visibility + attention state
// - Hidden by default
// - Shows only when the selected date is NOT today
// - Turns red and animates the icon so users notice they're on another day
// ------------------------------------------------------------
const resetDateBtn = document.getElementById('resetDateBtn');
function syncResetBtnState() {
    if (!resetDateBtn) return;
    const onToday = isToday();
    resetDateBtn.classList.toggle('is-hidden', onToday);
    resetDateBtn.classList.toggle('is-active', !onToday);
}
function isToday() {
    const selected = getSelectedDate();
    const today = moment.tz(timezone).format('DD-MM-YYYY');
    return selected === today;
}

// Ensure the initial state is correct on first render
syncResetBtnState();
function updateHijriDate() { if (currentHijriDate) document.getElementById('hijriDate').textContent = currentHijriDate; }
function getSelectedDate() { return `${daySelect.value}-${monthSelect.value}-${yearSelect.value}`; }
function updateTimeAndCountdown() {
    const now = moment.tz(timezone);
    document.getElementById('currentTime').textContent = now.format('HH:mm:ss');
    const timingsObj = {};
    document.querySelectorAll('.prayer-item').forEach(el => {
        const k = el.dataset.prayerKey;
        const timeText = el.querySelector('.prayer-time').textContent.trim();
        if (k && timeText && timeText !== '—') timingsObj[k] = timeText;
    });
    // Also include extra (non-block) timings shown below the grid
    document.querySelectorAll('#extraTimes [data-prayer-key]').forEach(el => {
        const k = el.getAttribute('data-prayer-key');
        const v = (el.querySelector('.extra-time-val')?.textContent || '').trim();
        if (k && v && v !== '—') timingsObj[k] = v;
    });
    if (Object.keys(timingsObj).length === 0) { document.getElementById('countdown').textContent = 'Yükleniyor...'; return; }
    const candidates = COUNTDOWN_KEYS.map(item => ({ key: item.key, name: item.name, hhmm: timingsObj[item.key] || null })).filter(x => x.hhmm);
    let next = null; let minDiff = Infinity;
    for (let item of candidates) {
        const [h, m] = item.hhmm.split(':');
        let prayerMoment = moment.tz(timezone).hour(h).minute(m).second(0);
        if (prayerMoment.isBefore(now) || prayerMoment.isSame(now, 'minute')) prayerMoment = prayerMoment.add(1, 'day');
        const diff = prayerMoment.diff(now, 'seconds');
        if (diff > 0 && diff < minDiff) { minDiff = diff; next = { name: item.name, diff }; }
    }
    if (next) {
        const hours = Math.floor(next.diff / 3600);
        const mins = Math.floor((next.diff % 3600) / 60);
        const secs = next.diff % 60;
        document.getElementById('countdown').textContent = ` ${next.name} - Kalan Süre: ${pad(hours)}:${pad(mins)}:${pad(secs)}`;
    } else if (tomorrowTimings && tomorrowTimings.Fajr) {
        const [h, m] = tomorrowTimings.Fajr.split(':');
        const fajrTomorrow = moment.tz(timezone).add(1, 'day').hour(h).minute(m);
        const diff = fajrTomorrow.diff(now, 'seconds');
        const hours = Math.floor(diff / 3600);
        const mins = Math.floor((diff % 3600) / 60);
        const secs = diff % 60;
        document.getElementById('countdown').textContent = `Yarın Sabah Namazı: ${pad(hours)}:${pad(mins)}:${pad(secs)}`;
    } else {
        document.getElementById('countdown').textContent = 'Tüm vakitler geçti';
    }
}
function startUpdating() { if (intervalId) clearInterval(intervalId); updateTimeAndCountdown(); intervalId = setInterval(updateTimeAndCountdown, 1000); }
async function fetchMonthlyTimings(cityRaw, month, year) {
    try {
        const loader = document.getElementById('monthlyTimingsLoader');
        loader.style.display = 'flex';
        let city = cityRaw; if (cityRaw.includes(',')) city = cityRaw.split(',')[0].trim();
        const url = `${AJAX_BASE}?action=monthly_timings&city=${encodeURIComponent(city)}&month=${month}&year=${year}&method=${defaultMethod}`;
        const res = await fetch(url);
        const data = await res.json();
        loader.style.display = 'none';
        if (data && data.data) buildMonthlyTimingsTable(data.data, month, year);
        else document.getElementById('monthlyTimingsTable').querySelector('tbody').innerHTML = `<tr><td colspan="11">Hata: ${data.error || 'Bilinmeyen hata'}</td></tr>`;
    } catch (err) {
        document.getElementById('monthlyTimingsLoader').style.display = 'none';
        console.error(err);
        const tb = document.getElementById('monthlyTimingsTable')?.querySelector('tbody');
        if (tb) tb.innerHTML = `<tr><td colspan="11">API bağlantı hatası</td></tr>`;
    }
}

function buildMonthlyTimingsTable(data, month, year) {
    const tableBody = document.getElementById('monthlyTimingsTable').querySelector('tbody');
    tableBody.innerHTML = '';
    const monthName = monthSelect.options[monthSelect.selectedIndex].textContent.split(' - ')[1];
    const cityTitle = (cityInput.value || '').trim().split(',')[0].trim();
    document.getElementById('monthlyTimingsTitle').textContent = `${cityTitle ? cityTitle + ' ' : ''}Namaz Vakitleri (${monthName} ${year})`;
    const today = moment.tz('Europe/Istanbul');
    const todayWeekdayEn = today.format('dddd');
    const todayDay = today.format('DD');
    const todayMonthEn = today.format('MMMM'); 
    const todayYear = today.format('YYYY');
    const todayGregorianRawStr = `${todayWeekdayEn}, ${todayDay} ${todayMonthEn}<br>${todayYear}`;
    data.forEach(day => {
        const row = tableBody.insertRow();
        const fajrVal = (day.fajr ?? day.Fajr ?? '');
        const sunriseVal = (day.sunrise ?? day.Sunrise ?? '');
        const dhuhrVal = (day.dhuhr ?? day.Dhuhr ?? '');
        const asrVal = (day.asr ?? day.Asr ?? day.ilkindi ?? day.Ilkindi ?? day.ikindi ?? day.Ikindi ?? '—');
        const sunsetVal = (day.sunset ?? day.Sunset ?? '—');
        const maghribVal = (day.maghrib ?? day.Maghrib ?? '');
        const ishaVal = (day.isha ?? day.Isha ?? day.yatsi ?? day.Yatsi ?? day.yatsı ?? day.Yatsı ?? '—');
        const midnightVal = (day.midnight ?? day.Midnight ?? '—');
        const isToday = (day.gregorian_date_raw || day.gregorian_date || '') === todayGregorianRawStr;
        if (isToday) {
            row.classList.add('today-row');
        }
        row.innerHTML = `
            <td class="gregorian-col">${day.gregorian_date_tr || day.gregorian_date_raw || day.gregorian_date || ''}</td>
            <td class="hijri-col"><span class="hijri-day">${(day.hijri_date_tr || day.hijri_date_raw || day.hijri_date || '').split(' ')[0]}</span> ${(day.hijri_date_tr || day.hijri_date_raw || day.hijri_date || '').split(' ').slice(1).join(' ')}</td>
            <td class="hijri2-col"><span class="hijri-day">${(day.hijri2_date_tr || '').split(' ')[0]}</span> ${(day.hijri2_date_tr || '').split(' ').slice(1).join(' ')}</td>
            <td>${fajrVal}</td>
            <td>${sunriseVal}</td>
            <td>${dhuhrVal}</td>
            <td>${asrVal}</td>
            <td>${sunsetVal}</td>
            <td>${maghribVal}</td>
            <td>${ishaVal}</td>
            <td>${midnightVal}</td>
        `;
    });

    // Mobile UX: keep all rows visible, but allow vertical scrolling inside the box (without needing "Daha fazla").
    // The "Daha fazla" button only toggles the box height (collapsed/expanded).
    applyMonthlyMobileCollapse();

    // Hide API-based Hijri column when plugin-mode is active
    if (HIJRI_CALC_MODE === 'plugin') {
        document.querySelectorAll('#monthlyTimingsTable .hijri-col, #monthlyTimingsTable th.hijri-col').forEach(el => {
            el.style.display = 'none';
        });
    }

}

// ------------------------------------------------------------
// Mobile: show only first 7 rows of monthly timings by default
// ------------------------------------------------------------
const monthlyMoreBtn = document.getElementById('monthlyMoreBtn');
let monthlyExpanded = false;

function applyMonthlyMobileCollapse() {
    const wrap = document.getElementById('tableWrapper');
    const body = document.getElementById('monthlyTimingsTable')?.querySelector('tbody');
    if (!wrap || !body || !monthlyMoreBtn) return;

    const rows = Array.from(body.querySelectorAll('tr'));
    const isMobile = window.matchMedia('(max-width: 768px)').matches;

    // Always show all rows; we manage the visible area using CSS (max-height + overflow-y).
    rows.forEach(r => r.hidden = false);

    if (!isMobile) {
        wrap.classList.remove('monthly-collapsed', 'monthly-expanded');
        monthlyMoreBtn.hidden = true;
        monthlyExpanded = false;
        return;
    }

    // If the table is short, no need for the height toggle.
    if (rows.length <= 7) {
        wrap.classList.remove('monthly-collapsed', 'monthly-expanded');
        monthlyMoreBtn.hidden = true;
        monthlyExpanded = false;
        return;
    }

    monthlyMoreBtn.hidden = false;
    wrap.classList.toggle('monthly-expanded', !!monthlyExpanded);
    wrap.classList.toggle('monthly-collapsed', !monthlyExpanded);
    monthlyMoreBtn.textContent = monthlyExpanded ? 'Daha az' : 'Daha fazla';
}

if (monthlyMoreBtn) {
    monthlyMoreBtn.addEventListener('click', () => {
        monthlyExpanded = !monthlyExpanded;
        applyMonthlyMobileCollapse();
    });
}
window.addEventListener('resize', () => applyMonthlyMobileCollapse());

async function fetchTimings(cityRaw, dateStr) {
    try {
        loader.style.display = 'block';
        let city = cityRaw; if (cityRaw.includes(',')) city = cityRaw.split(',')[0].trim();
        const url = `${AJAX_BASE}?action=timings&city=${encodeURIComponent(city)}&method=${defaultMethod}&date=${encodeURIComponent(dateStr)}`;
        const res = await fetch(url);
        const data = await res.json();
        loader.style.display = 'none';
        return data;
    } catch (err) {
        loader.style.display = 'none';
        console.error(err);
        return { code:500, status:'ERROR', message: err.message || String(err) };
    }
}
async function fetchMonthEvents(month, year) {
    try {
        const res = await fetch(`${AJAX_BASE}?action=month_events&month=${month}&year=${year}`);
        const data = await res.json();
        return data.events || [];
    } catch (err) { console.error(err); return []; }
}


function navigateWithSelection() {
    let cityRaw = cityInput.value.trim();
    if (!cityRaw) return;
    cityRaw = cityRaw.split(',')[0].trim();
    const provinceRaw = (provinceSelect && provinceSelect.value) ? provinceSelect.value.trim() : '';
    const day = String(daySelect.value).padStart(2,'0');
    const month = String(monthSelect.value).padStart(2,'0');
    const year = String(yearSelect.value);
    const dateStr = `${day}-${month}-${year}`;
    const provinceParam = provinceRaw ? `&province=${encodeURIComponent(provinceRaw)}` : '';
    window.location.href = `?city=${encodeURIComponent(cityRaw)}${provinceParam}&date=${encodeURIComponent(dateStr)}`;
}

// ------------------------------------------------------------
// Popular cities shortcuts (below monthly timings)
// ------------------------------------------------------------
function navigateToCity(cityName) {
    const day = String(daySelect.value).padStart(2,'0');
    const month = String(monthSelect.value).padStart(2,'0');
    const year = String(yearSelect.value);
    const dateStr = `${day}-${month}-${year}`;
    // For major cities, we use the city name as province as well.
    window.location.href = `?city=${encodeURIComponent(cityName)}&province=${encodeURIComponent(cityName)}&date=${encodeURIComponent(dateStr)}`;
}
document.querySelectorAll('#popularCitiesList .city-chip').forEach(btn => {
    btn.addEventListener('click', () => {
        const c = (btn.getAttribute('data-city') || '').trim();
        if (c) navigateToCity(c);
    });
});

async function updateTimings() {
    // AJAX updates were causing the bottom monthly list not to refresh reliably.
    // To keep the full page consistent, we disable AJAX behavior here and force a full reload
    // with a fresh URL whenever city/date selection changes.
    navigateWithSelection();
}

function buildGridFromTimings(timingsObj, gregorianShort, hijriFull, custom = {occasion:'', talkofday:'', notice:''}, weekday = '', cityDisplay = '', hijriFull2 = '') {
    // If plugin Hijri calculation is enabled, hide API-based Hijri display.
    if (HIJRI_CALC_MODE === 'plugin') {
        const h1 = document.getElementById('displayHijriFull');
        if (h1) h1.style.display = 'none';
    }

    const grid = document.getElementById('prayerGrid');
    grid.innerHTML = '';
    PRAYER_KEYS.forEach(item => {
        const time = timingsObj[item.key];
        const el = document.createElement('div');
        el.className = 'prayer-item';
        el.dataset.prayerKey = item.key;
        el.innerHTML = `<img class="small-icon" src="${item.icon}" alt="${item.name}"><div class="prayer-time">${time ?? '—'}</div><div class="prayer-name">${item.name}</div>`;
        grid.appendChild(el);
    });

    // Show Sunset + Midnight below the grid (plain, non-block)
    const extraBox = document.getElementById('extraTimes');
    if (extraBox) {
        const sunset = timingsObj['Sunset'] ?? '—';
        const midnight = timingsObj['Midnight'] ?? '—';
        extraBox.innerHTML = `
            <span class="extra-time-item" data-prayer-key="Sunset"><strong>Güneş Batışı:</strong> <span class="extra-time-val">${sunset}</span></span>
            <span class="extra-time-item" data-prayer-key="Midnight"><strong>Gece Yarısı:</strong> <span class="extra-time-val">${midnight}</span></span>
        `;
    }

    if (weekday) {
        document.getElementById('displayWeekday').textContent = weekday;
    } else {
        document.getElementById('displayWeekday').textContent = '';
    }
    if (gregorianShort) {
        document.getElementById('displayGregorianShort').textContent = gregorianShort;
    }
    if (hijriFull) {
        document.getElementById('displayHijriFull').textContent = hijriFull;
    }
    const h2el = document.getElementById('displayHijriFull2');
    if (h2el) {
        if (hijriFull2) { h2el.style.display = 'block'; h2el.textContent = hijriFull2; }
        else { h2el.style.display = 'none'; h2el.textContent = ''; }
    }
    if (cityDisplay) {
        document.getElementById('displayCityWithNamaz').textContent = `${cityDisplay} - Namaz Vakitleri`;
    }

    const toArr = (v) => {
        if (!v) return [];
        if (Array.isArray(v)) return v.map(x => String(x)).filter(x => x.trim() !== '');
        const s = String(v).trim();
        if (!s) return [];
        return s.split(/\r\n|\r|\n/).map(x => x.trim()).filter(Boolean);
    };
    const renderLines = (el, items) => {
        if (!el) return;
        el.innerHTML = '';
        items.forEach((t, idx) => {
            const line = document.createElement('div');
            line.className = 'occasion-line';
            line.textContent = t;
            el.appendChild(line);
        });
    };

    const renderTodayHistory = (items) => {
        if (!todayHistoryBox || !todayHistoryList) return;
        const arr = Array.isArray(items) ? items : [];
        todayHistoryList.innerHTML = '';
        if (!arr.length) {
            todayHistoryBox.hidden = true;
            return;
        }
        arr.forEach((it) => {
            const text = (typeof it === 'string') ? it : (it?.text ?? '');
            const link = (typeof it === 'object' && it) ? (it.link ?? '') : '';
            const t = String(text).trim();
            if (!t) return;

            const line = document.createElement('div');
            line.className = 'todayhistory-line';
            const span = document.createElement('span');
            span.className = 'todayhistory-text';
            span.textContent = t;
            line.appendChild(span);
            const href = String(link || '').trim();
            if (href) {
                const a = document.createElement('a');
                a.className = 'todayhistory-more';
                a.href = href;
                a.target = '_blank';
                a.rel = 'noopener noreferrer';
                a.textContent = 'devamı...';
                line.appendChild(a);
            }
            todayHistoryList.appendChild(line);
        });
        todayHistoryBox.hidden = (todayHistoryList.children.length === 0);
    };

    const occArr = toArr(custom.occasion);
    const talkArr = toArr(custom.talkofday);
    const hadisArr = toArr(custom.dayhadis);
    const noticeArr = toArr(custom.notice);

    if (occArr.length || talkArr.length || hadisArr.length || noticeArr.length) {
        occasionsSection.classList.add('visible');
        occasionRow.classList.toggle('visible', occArr.length > 0);
        talkofdayRow.classList.toggle('visible', (talkArr.length > 0 || hadisArr.length > 0));
        noticeRow.classList.toggle('visible', noticeArr.length > 0);
        renderLines(occasionText, occArr);
        renderLines(talkofdayText, talkArr);
        if (dayhadisText) renderLines(dayhadisText, hadisArr);
        renderLines(noticeText, noticeArr);

        // Tabs: default to Ayet if present, otherwise show Hadis
        const ayetBtn = document.querySelector('.talkofday-tab[data-tab="ayet"]');
        const hadisBtn = document.querySelector('.talkofday-tab[data-tab="hadis"]');
        if (ayetBtn) { ayetBtn.disabled = (talkArr.length === 0); ayetBtn.classList.toggle('is-disabled', talkArr.length === 0); }
        if (hadisBtn) { hadisBtn.disabled = (hadisArr.length === 0); hadisBtn.classList.toggle('is-disabled', hadisArr.length === 0); }
        if (talkArr.length > 0) {
            setTalkTab('ayet');
        } else if (hadisArr.length > 0) {
            setTalkTab('hadis');
        }
    } else {
        occasionsSection.classList.remove('visible');
    }

    // Render Today in History box (above Popüler Şehirler)
    renderTodayHistory(custom?.todayhistory);

    highlightCurrentPrayers(timingsObj);
}

function buildMonthEvents(events) {
    const list = document.getElementById('monthEventsList');
    list.innerHTML = '';
    const section = document.getElementById('monthEventsSection');
    section.style.display = 'block';
    const monthName = monthSelect.options[monthSelect.selectedIndex].textContent.split(' - ')[1];
    document.getElementById('monthEventsTitle').textContent = `(${monthName}) ayın özel günleri `;
    if (events.length === 0) {
        list.innerHTML = '<div class="no-events">Bu ay etkinlik yok!</div>';
        return;
    }
    const monthNames = ['Ocak', 'Şubat', 'Mart', 'Nisan', 'Mayıs', 'Haziran',
                        'Temmuz', 'Ağustos', 'Eylül', 'Ekim', 'Kasım', 'Aralık'];
    const currentMonthIndex = parseInt(monthSelect.value, 10) - 1;
    const monthAbbr = monthNames[currentMonthIndex];
    events.forEach(ev => {
        const row = document.createElement('div');
        row.className = 'event-row';
        const daySpan = document.createElement('span');
        daySpan.className = 'event-day';
        daySpan.textContent = ev.gregorian_day + ' ' + monthAbbr;
        if (ev.dayoff === 'yes') daySpan.style.color = 'red';
        const textSpan = document.createElement('span');
        textSpan.className = 'event-text';
        textSpan.textContent = ev.occasion;
        const hijriSpan = document.createElement('span');
        hijriSpan.className = 'textmhejri';
        hijriSpan.textContent = ev.hijri_prefix || '';
        row.appendChild(daySpan);
        row.appendChild(textSpan);
        row.appendChild(hijriSpan);
        list.appendChild(row);
    });
}
function highlightCurrentPrayers(timingsObj) {
    const now = new Date();
    function timeToDate(hhmm, baseDate, addDay = false) {
        const parts = hhmm.split(':');
        if (parts.length < 2) return null;
        const d = new Date(baseDate);
        d.setHours(parseInt(parts[0],10));
        d.setMinutes(parseInt(parts[1],10));
        d.setSeconds(0); d.setMilliseconds(0);
        if (addDay) d.setDate(d.getDate() + 1);
        return d;
    }
    const arr = PRAYER_KEYS.map(p => ({key:p.key, name:p.name, hhmm:timingsObj[p.key] || ''})).filter(a => a.hhmm);
    const dateObjs = arr.map(a => ({ ...a, dateObj: timeToDate(a.hhmm, now) }));
    for (let i = 1; i < dateObjs.length; i++) {
        if (dateObjs[i].dateObj.getTime() <= dateObjs[i-1].dateObj.getTime()) dateObjs[i].dateObj.setDate(dateObjs[i].dateObj.getDate() + 1);
    }
    let activeKey = null;
    const nowTime = now.getTime();
    for (let i = 0; i < dateObjs.length; i++) {
        const start = dateObjs[i].dateObj.getTime();
        const end = (i+1 < dateObjs.length ? dateObjs[i+1].dateObj.getTime() : start + 24*3600*1000);
        if (nowTime >= start && nowTime < end) { activeKey = dateObjs[i].key; break; }
    }
    document.querySelectorAll('.prayer-item').forEach(el => el.classList.toggle('active', el.dataset.prayerKey === activeKey));
    // Keep the top title fixed (user request). We only update the icon highlight.
    const mapping = PRAYER_KEYS.find(p => p.key === activeKey);
    if (mapping) {
        document.getElementById('currentIcon').src = mapping.icon;
    } else {
        document.getElementById('currentIcon').src = ASSET_BASE + '/icons/sunrise.svg';
    }
}

if (initialTimingsRaw && initialTimingsRaw.code === 200 && initialTimingsRaw.data && initialTimingsRaw.data.timings) {
    const t = initialTimingsRaw.data.timings;
    const obj = {};
    PRAYER_KEYS.forEach(p => {
        obj[p.key] = t[p.key] || t[p.key.charAt(0).toUpperCase() + p.key.slice(1)] || t[p.key];
    });

    

    // Extra (non-block) times displayed under the top grid
    obj['Sunset'] = t['Sunset'] || t['sunset'] || '—';
    obj['Midnight'] = t['Midnight'] || t['midnight'] || '—';
const g = initialTimingsRaw.data.date.gregorian;
    const gregorianShort = `${g.day} ${trMonth(g.month.en)} ${g.year}`;
    const h = initialTimingsRaw.data.date.hijri;
    const hijriFull = `${h.day} ${trHijriMonth(h.month.en)} ${h.year}`;
    const hijriFull2 = (initialTimingsRaw.data && initialTimingsRaw.data.date && initialTimingsRaw.data.date.hijri2_full) ? initialTimingsRaw.data.date.hijri2_full : '';
    const weekday = trWeekday(g.weekday.en);
    const cityDisplay = "Istanbul, İstanbul";
    const custom = initialTimingsRaw.custom || {occasion:'', talkofday:'', dayhadis:'', notice:''};

    buildGridFromTimings(obj, gregorianShort, (HIJRI_CALC_MODE === 'plugin' ? '' : hijriFull), custom, weekday, cityDisplay, hijriFull2);
} else {
    // ------------------------------------------------------------
    // Fallback: when opened through a WordPress pretty permalink
    // (e.g. /takvim), server-side prefetch ($init_timings) may be
    // empty due to different execution context. In that case, fetch
    // the selected day timings via our own AJAX endpoint and render
    // the top widgets.
    // ------------------------------------------------------------
    const fallbackDateStr = (typeof getSelectedDate === 'function') ? getSelectedDate() : null;
    const fallbackCity = (cityInput && cityInput.value) ? cityInput.value : 'Istanbul';
    if (fallbackDateStr) {
        fetchTimings(fallbackCity, fallbackDateStr).then((resp) => {
            if (!resp || resp.code !== 200 || !resp.data || !resp.data.timings) return;
            const t = resp.data.timings;
            const obj = {};
            PRAYER_KEYS.forEach(p => {
                obj[p.key] = t[p.key] || t[p.key.charAt(0).toUpperCase() + p.key.slice(1)] || t[p.key];
            });
            

    // Extra (non-block) times displayed under the top grid
    obj['Sunset'] = t['Sunset'] || t['sunset'] || '—';
    obj['Midnight'] = t['Midnight'] || t['midnight'] || '—';
const g = resp.data.date && resp.data.date.gregorian ? resp.data.date.gregorian : null;
            const h = resp.data.date && resp.data.date.hijri ? resp.data.date.hijri : null;
            const gregorianShort = g ? `${g.day} ${trMonth(g.month.en)} ${g.year}` : '';
            const hijriFull = h ? `${h.day} ${trHijriMonth(h.month.en)} ${h.year}` : '';
            const hijriFull2 = (resp.data && resp.data.date && resp.data.date.hijri2_full) ? resp.data.date.hijri2_full : '';
            const weekday = g ? trWeekday(g.weekday.en) : '';
            const cityDisplay = (fallbackCity || '').includes(',') ? fallbackCity : (fallbackCity || '');
            const custom = resp.custom || {occasion:'', talkofday:'', dayhadis:'', notice:''};
            buildGridFromTimings(obj, gregorianShort, (HIJRI_CALC_MODE === 'plugin' ? '' : hijriFull), custom, weekday, cityDisplay, hijriFull2);
        }).catch(() => {});
    }
}

async function initMonthEvents() {
    const month = parseInt(initMonth, 10);
    const year = parseInt(initYear, 10);
    const events = await fetchMonthEvents(month, year);
    buildMonthEvents(events);
}
setTimeout(async () => {
    const month = parseInt(monthSelect.value, 10);
    const year = parseInt(yearSelect.value, 10);
    const city = cityInput.value.trim() || 'Istanbul';
    if (month >= 1 && month <= 12 && year) {
        await fetchMonthlyTimings(city, month, year);
        const events = await fetchMonthEvents(month, year);
        buildMonthEvents(events);
    }
}, 200);
startUpdating();
const tomorrow = moment(getSelectedDate(), 'DD-MM-YYYY').add(1, 'day').format('DD-MM-YYYY');
fetchTimings(cityInput.value || 'Istanbul', tomorrow).then(d => {
    if (d && d.code === 200) tomorrowTimings = d.data.timings;
});
const tableWrapper = document.getElementById('tableWrapper');
let isDown = false;
let startX;
let scrollLeft;
tableWrapper.addEventListener('mousedown', e => {
    isDown = true;
    tableWrapper.classList.add('active');
    startX = e.pageX - tableWrapper.offsetLeft;
    scrollLeft = tableWrapper.scrollLeft;
});
tableWrapper.addEventListener('mouseleave', () => { isDown = false; tableWrapper.classList.remove('active'); });
tableWrapper.addEventListener('mouseup', () => { isDown = false; tableWrapper.classList.remove('active'); });
tableWrapper.addEventListener('mousemove', e => {
    if (!isDown) return;
    e.preventDefault();
    const x = e.pageX - tableWrapper.offsetLeft;
    const walk = (x - startX) * 2;
    tableWrapper.scrollLeft = scrollLeft - walk;
});
function resetToToday() {
    const today = moment.tz(timezone);
    const day = today.format('DD');
    const month = today.format('MM');
    const year = today.format('YYYY');
    daySelect.value = day;
    monthSelect.value = month;
    yearSelect.value = year;
    // Make sure the UI reflects that we're back on today (before reload)
    syncResetBtnState();
    navigateWithSelection();
}
if (resetDateBtn) resetDateBtn.addEventListener('click', resetToToday);

// --- Day navigation arrows (prev/next) ---
function shiftSelectedDate(deltaDays) {
    try {
        const m = moment.tz(getSelectedDate(), 'DD-MM-YYYY', timezone).add(deltaDays, 'day');
        daySelect.value = m.format('DD');
        monthSelect.value = m.format('MM');
        yearSelect.value = m.format('YYYY');
        syncResetBtnState();
        navigateWithSelection();
    } catch (e) {
        // no-op
    }
}
const prevDayBtn = document.getElementById('prevDayBtn');
const nextDayBtn = document.getElementById('nextDayBtn');
if (prevDayBtn) prevDayBtn.addEventListener('click', () => shiftSelectedDate(-1));
if (nextDayBtn) nextDayBtn.addEventListener('click', () => shiftSelectedDate(1));
</script>
</body>
</html>{"id":89,"date":"2026-02-24T12:44:24","date_gmt":"2026-02-24T12:44:24","guid":{"rendered":"https:\/\/www.medine.net\/worktr\/?page_id=89"},"modified":"2026-02-24T12:44:24","modified_gmt":"2026-02-24T12:44:24","slug":"takvim-tr","status":"publish","type":"page","link":"https:\/\/www.medine.net\/takvim\/","title":{"rendered":"takvim-tr"},"content":{"rendered":"\n","protected":false},"excerpt":{"rendered":"","protected":false},"author":1,"featured_media":0,"parent":0,"menu_order":0,"comment_status":"closed","ping_status":"closed","template":"","meta":{"footnotes":""},"class_list":["post-89","page","type-page","status-publish","hentry"],"_links":{"self":[{"href":"https:\/\/www.medine.net\/takvim\/wp-json\/wp\/v2\/pages\/89","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/www.medine.net\/takvim\/wp-json\/wp\/v2\/pages"}],"about":[{"href":"https:\/\/www.medine.net\/takvim\/wp-json\/wp\/v2\/types\/page"}],"author":[{"embeddable":true,"href":"https:\/\/www.medine.net\/takvim\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/www.medine.net\/takvim\/wp-json\/wp\/v2\/comments?post=89"}],"version-history":[{"count":2,"href":"https:\/\/www.medine.net\/takvim\/wp-json\/wp\/v2\/pages\/89\/revisions"}],"predecessor-version":[{"id":91,"href":"https:\/\/www.medine.net\/takvim\/wp-json\/wp\/v2\/pages\/89\/revisions\/91"}],"wp:attachment":[{"href":"https:\/\/www.medine.net\/takvim\/wp-json\/wp\/v2\/media?parent=89"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}