<head>
    <meta charset="utf-8">
    <meta content="width=device-width, initial-scale=1.0" name="viewport">

    <html lang="id">

    <!-- HEAD -->

    <head>

        <meta charset="utf-8">
        <meta content="width=device-width, initial-scale=1.0" name="viewport">

        <!-- Meta, title, CSS, favicons, etc. -->
        <meta charset="utf-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <meta name="description" content="BMKG Stasiun Meteorologi Frans Sales Lega">
        <meta name="author" content="0x35">
        <meta name="theme-color" content="#2A3F54" />
        <meta property="og:site_name" content="BMKG Stasiun Meteorologi Frans Sales Lega" />
        <meta property="og:title" content="BMKG Stasiun Meteorologi Frans Sales Lega" />
        <meta property="og:description" content="Website resmi BMKG Stamet Frans Sales Lega &copy; 2024" />
        <meta property="og:image" itemprop="image"
            content="https://stamet-juanda.bmkg.go.id/home/assets/img/logo_putih.png">
        <meta property="og:type" content="website" />
        <title>BMKG Stasiun Meteorologi Frans Sales Lega</title>

        <link rel="icon" type="image/png" href="https://stamet-juanda.bmkg.go.id/home/assets/img/logo_putih.png" />
        <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.2/css/all.min.css" integrity="sha512-SnH5WK+bZxgPHs44uWIX+LLJAJ9/2PkPKZ5QiAj6Ta86w+fsb2TkcmfRyVX3pBnMFcV7oQPJkl9QevSCWr3W6A==" crossorigin="anonymous" referrerpolicy="no-referrer" />
        <!-- LOGO TAB -->
        <link href="https://stamet-juanda.bmkg.go.id/home/assets/img/logobmkg.png" rel="icon">
        <link href="https://stamet-juanda.bmkg.go.id/home/assets/img/logobmkg.png" rel="apple-touch-icon">

        <!-- JUDUL TAB -->
        <title>BMKG FRANS SALES LEGA</title>
        <meta content="" name="description">
        <meta content="" name="keywords">

        <!-- FONTS -->
        <link
            href="https://fonts.googleapis.com/css?family=Open+Sans:300,300i,400,400i,600,600i,700,700i|Poppins:300,300i,400,400i,500,500i,600,600i,700,700i|Playfair+Display:400,400i,500,500i,600,600i,700,700i&subset=cyrillic"
            rel="stylesheet">

        <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/Swiper/8.3.2/swiper-bundle.css"
            integrity="sha512-ipO1yoQyZS3BeIuv2A8C5AwQChWt2Pi4KU3nUvXxc4TKr8QgG8dPexPAj2JGsJD6yelwKa4c7Y2he9TTkPM4Dg=="
            crossorigin="anonymous" referrerpolicy="no-referrer" />

        <!-- VENDOR CSS STYLE -->
        <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet"
            integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous">
        <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.8.3/font/bootstrap-icons.css"
            integrity="sha384-eoTu3+HydHRBIjnCVwsFyCpUDZHZSFKEJD0mc3ZqSBSb6YhZzRHeiomAUWCstIWo" crossorigin="anonymous">

        <link href='https://cdn.jsdelivr.net/npm/glightbox@3.2.0/dist/css/glightbox.min.css' rel='stylesheet'>
        <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/Swiper/8.3.2/swiper-bundle.min.css"
            integrity="sha512-T3xwtELy3dqQUajk2sl4V6x/VnT+WbXgAKIu/Go7L6oDDWf4A5dJbG49vKn0am3dTNh/KHAbU2+4Ih2vVioxSg=="
            crossorigin="anonymous" referrerpolicy="no-referrer" />

        <!-- carousel -->
        <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/OwlCarousel2/2.3.4/assets/owl.carousel.css"
            integrity="sha512-UTNP5BXLIptsaj5WdKFrkFov94lDx+eBvbKyoe1YAfjeRPC+gT5kyZ10kOHCfNZqEui1sxmqvodNUx3KbuYI/A=="
            crossorigin="anonymous" referrerpolicy="no-referrer" />
        <!-- iconify -->
        <script src="https://code.iconify.design/2/2.2.1/iconify.min.js"></script>
        <link rel="stylesheet" href="https://unpkg.com/leaflet@1.8.0/dist/leaflet.css"
            integrity="sha512-hoalWLoI8r4UszCkZ5kL8vayOGVae1oxXe/2A4AO6J9+580uKHDO3JdHb7NzwwzK5xr/Fs0W40kiNHxM9vyTtQ=="
            crossorigin="" />
        <!-- moment -->
        <link href='https://unpkg.com/boxicons@2.1.2/css/boxicons.min.css' rel='stylesheet'>
        <script src="https://code.jquery.com/jquery-3.6.0.js"
            integrity="sha256-H+K7U5CnXl1h5ywQfKtSj8PCmoN9aaq30gDh27Xc0jk=" crossorigin="anonymous"></script>
        <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/animate.css/4.1.1/animate.min.css" />
        <!-- MAIN CSS FILE -->
        <link href="https://stamet-juanda.bmkg.go.id/home/assets/css/main.css" rel="stylesheet">
        <link href="https://stamet-juanda.bmkg.go.id/home/assets/css/section.footer.css" rel="stylesheet">
        <link href="https://stamet-juanda.bmkg.go.id/home/assets/vendor/weather-icons/css/weather-icons.css" rel="stylesheet">
    <script nonce="7441f51c-e6aa-49f7-b788-b9a55d1df727">try{(function(w,d){!function(bk,bl,bm,bn){if(bk.zaraz)console.error("zaraz is loaded twice");else{bk[bm]=bk[bm]||{};bk[bm].executed=[];bk.zaraz={deferred:[],listeners:[]};bk.zaraz._v="5807";bk.zaraz._n="7441f51c-e6aa-49f7-b788-b9a55d1df727";bk.zaraz.q=[];bk.zaraz._f=function(bo){return async function(){var bp=Array.prototype.slice.call(arguments);bk.zaraz.q.push({m:bo,a:bp})}};for(const bq of["track","set","debug"])bk.zaraz[bq]=bk.zaraz._f(bq);bk.zaraz.init=()=>{var br=bl.getElementsByTagName(bn)[0],bs=bl.createElement(bn),bt=bl.getElementsByTagName("title")[0];bt&&(bk[bm].t=bl.getElementsByTagName("title")[0].text);bk[bm].x=Math.random();bk[bm].w=bk.screen.width;bk[bm].h=bk.screen.height;bk[bm].j=bk.innerHeight;bk[bm].e=bk.innerWidth;bk[bm].l=bk.location.href;bk[bm].r=bl.referrer;bk[bm].k=bk.screen.colorDepth;bk[bm].n=bl.characterSet;bk[bm].o=(new Date).getTimezoneOffset();if(bk.dataLayer)for(const bx of Object.entries(Object.entries(dataLayer).reduce(((by,bz)=>({...by[1],...bz[1]})),{})))zaraz.set(bx[0],bx[1],{scope:"page"});bk[bm].q=[];for(;bk.zaraz.q.length;){const bA=bk.zaraz.q.shift();bk[bm].q.push(bA)}bs.defer=!0;for(const bB of[localStorage,sessionStorage])Object.keys(bB||{}).filter((bD=>bD.startsWith("_zaraz_"))).forEach((bC=>{try{bk[bm]["z_"+bC.slice(7)]=JSON.parse(bB.getItem(bC))}catch{bk[bm]["z_"+bC.slice(7)]=bB.getItem(bC)}}));bs.referrerPolicy="origin";bs.src="/cdn-cgi/zaraz/s.js?z="+btoa(encodeURIComponent(JSON.stringify(bk[bm])));br.parentNode.insertBefore(bs,br)};["complete","interactive"].includes(bl.readyState)?zaraz.init():bk.addEventListener("DOMContentLoaded",zaraz.init)}}(w,d,"zarazData","script");window.zaraz._p=async j=>new Promise((k=>{if(j){j.e&&j.e.forEach((l=>{try{const m=d.querySelector("script[nonce]"),n=m?.nonce||m?.getAttribute("nonce"),o=d.createElement("script");n&&(o.nonce=n);o.innerHTML=l;o.onload=()=>{d.head.removeChild(o)};d.head.appendChild(o)}catch(p){console.error(`Error executing script: ${l}\n`,p)}}));Promise.allSettled((j.f||[]).map((q=>fetch(q[0],q[1]))))}k()}));zaraz._p({"e":["(function(w,d){})(window,document)"]});})(window,document)}catch(e){throw fetch("/cdn-cgi/zaraz/t"),e;};</script></head>
    <!-- END HEAD -->

    <!-- BODY -->

<body><!-- ======= HEADER ======= -->


<style>
    .loader {
        display: none;
        border: 5px solid #f3f3f3;
        /* Light grey */
        border-top: 5px solid #3498db;
        /* Blue */
        border-radius: 50%;
        width: 50px;
        height: 50px;
        animation: spin 1s linear infinite;
        position: absolute;
        top: "200px";
        left: 50%;
        margin-top: -25px;
        margin-left: -25px;
    }

    @keyframes spin {
        0% {
            transform: rotate(0deg);
        }

        100% {
            transform: rotate(360deg);
        }
    }

    #dateButtons {
        display: flex;
        justify-content: center;
        /* Memusatkan tombol secara horizontal */
        flex-wrap: wrap;
        /* Izinkan wrap jika tidak cukup ruang */
        padding: 10px 0;
    }

    #dateButtons button {
        margin: 5px;
        padding: 10px 20px;
        background-color: #8f8b8b;
        color: white;
        border: none;
        border-radius: 5px;
        cursor: pointer;
        transition: background-color 0.3s;
        /* Smooth transition untuk warna */
    }

    #dateButtons button:hover {
        background-color: #0056b3;
    }

    #dateButtons button.active {
        background-color: #ffc107;
        /* Warna untuk state aktif */
    }
</style>

<main id="main">
    <section>
        <div class="fluid-container">
            <div class="card p-4 box-shadow">
                <div class="card mb-4">
                    <div class="card-header">
                    <h4 class="card-title text-center">
                            PRAKIRAAN CUACA KABUPATEN <span id="kabupatenTitle"></span>
                        </h4>
                    </div>
                    <div class="card-body">
                        
                        <div class="loader" id="loader"></div>
                        <div id="dateButtons" style="margin-bottom: 20px;"></div>
                        <div class="d-flex justify-content-center">
                            <img src="https://stamet-juanda.bmkg.go.id/home/assets/img/legend_sus.png" height="120px" alt="Image Description">
                        </div>
                        <table class="table table-striped" id="weatherTable">
                            <thead>
                                <tr id="mainHeader">
                                    <th scope="col" rowspan="2">Kec (Pilih)</th>
                                    <th scope="col" colspan="" id="timeHeader" style="text-align: center;"> Jam (UTC)</th>
                                    <th scope="col" rowspan="2">RH</th>
                                    <th scope="col" rowspan="2">T</th>
                                    <th scope="col" rowspan="2">Angin <br> KM/Jam</th>

                                </tr>
                                <tr id="weatherHeader">
                                    <!-- Time headers will be populated here -->
                                </tr>
                            </thead>
                            <tbody>
                                <!-- Data will be populated here -->
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>
        </div>
    </section>
</main>
<script>

function convertDirection(abbreviation) {
    const directions = {
        'N': 'Utara',
        'S': 'Selatan',
        'E': 'Timur',
        'W': 'Barat',
        'NE': 'Timur Laut',
        'NW': 'Barat Laut',
        'SE': 'Tenggara',
        'SW': 'Barat Daya'
    };

    return directions[abbreviation.toUpperCase()] || 'Arah tidak diketahui';
}


    function showLoader(show) {
        const loader = document.getElementById('loader');
        loader.style.display = show ? 'block' : 'none';
    }

    function updateTable(data,date,adm1) {
        let mainHeader = $('#mainHeader');
        let weatherHeader = $('#weatherHeader');
        let tbody = $('#weatherTable tbody');
        tbody.empty();
        weatherHeader.empty();
        let times = new Set();
        data.forEach(item => {
            item.cuaca.forEach(cuaca => {
                times.add(cuaca.datetime.split("T")[1].split(":")[0]);
            });
        });
        times.forEach(time => {
            weatherHeader.append(`<th scope="col">${time}</th>`);
        });
        data.forEach(item => {
            let rowWeather = `<tr><td><a href='desa.php?adm1=${item.adm1}&adm2=${item.adm2}&adm3=${item.adm3}&date=${date}&kec=${item.kecamatan}'>${item.kecamatan}</a></td>`;
            let cuacaMap = new Map();
            item.cuaca.forEach(cuaca => {
                time = cuaca.datetime.split("T")[1].split(":")[0]
                cuacaMap.set(time, `<img src='${cuaca.image}' alt='${cuaca.weather_desc}' title='${cuaca.weather_desc}' height='40' width='40'/>`);
            });
            times.forEach(time => {
                rowWeather += `<td>${cuacaMap.get(time) || ''}</td>`;
            });
            rowWeather += `<td>${item.kelembaban_min} - ${item.kelembaban_maks}</td>`;
            rowWeather += `<td>${item.suhu_min} - ${item.suhu_maks}</td>`;
            rowWeather += `<td>${convertDirection(item.wd)} - ${item.ws_max}</td>`;
            rowWeather += '</tr>';
            tbody.append(rowWeather);
        });
        $("#timeHeader").attr("colspan", times.size);
    }
    document.addEventListener('DOMContentLoaded', function () {
        const dateButtonsContainer = document.getElementById('dateButtons');
        let currentDate = new Date();
        let activeButton = null;
        let urlParams = new URLSearchParams(window.location.search);
        let activeDate = urlParams.get('date');  // Dapatkan tanggal dari URL
        let adm2 = urlParams.get('adm2');
        let adm1 = urlParams.get('adm1');
        let kab = urlParams.get('kab');
        $("#kabupatenTitle").text(kab.toUpperCase())

        for (let i = 0; i < 10; i++) {
            const button = document.createElement('button');

            const date = new Date(currentDate.getTime());
            date.setDate(currentDate.getDate() + i);
            let day = date.getDate().toString().padStart(2, '0');
            let month = (date.getMonth() + 1).toString().padStart(2, '0');
            let year = date.getFullYear();
            let buttonDate = `${year}-${month}-${day}`;

            button.textContent = `${day}-${month}-${year}`;
            button.setAttribute('data-date', buttonDate);  // Set atribut data-date

            button.onclick = function () {
                if (activeButton) {
                    activeButton.classList.remove('active');
                }
                button.classList.add('active');
                activeButton = button;

                showLoader(true);
                fetch(`https://stamet-juanda.bmkg.go.id/flask/api/sus/kecamatan?adm1=${adm1}&adm2=${adm2}&date=${buttonDate}`)
                    .then(response => response.json())
                    .then(data => {
                        updateTable(data, buttonDate, adm1);
                        showLoader(false);
                    })
                    .catch(error => {
                        console.error('Error fetching data:', error);
                        showLoader(false);
                    });
            };

            dateButtonsContainer.appendChild(button);

            // Jika tanggal pada button sama dengan tanggal aktif, klik button ini
            if (buttonDate === activeDate) {
                activeButton = button;  // Set button ini sebagai aktif
                button.classList.add('active');
            }
        }

        // Jika ada button aktif, panggil event onclick
        if (activeButton) {
            activeButton.onclick();
        } else {
            // Jika tidak ada tanggal yang cocok, default ke button pertama
            dateButtonsContainer.firstChild.onclick();
        }
    });

</script>

  <!-- ======= FOOTER ======= -->
  <div style="height: 100px;"></div>
  <footer id="footer">
    <div class="container">
      <div class="copyright">
        &copy; Copyright© <strong><span>2024 Web Developer BMKG Manggarai.</span></strong> All Rights Reserved. 
      </div>
    </div>
  </footer>