window.PrayerTimes = function PrayerTimes() {
    const [data, setData] = React.useState(null);
    const [busy, setBusy] = React.useState(false);
    const [error, setError] = React.useState('');
    const [notice, setNotice] = React.useState('Izinkan lokasi untuk jadwal daerah Anda. Tanpa izin, jadwal menggunakan Jakarta.');
    const [clock, setClock] = React.useState(Date.now());
    const coords = React.useRef(null), sequence = React.useRef(0), lastLoad = React.useRef(0), currentData = React.useRef(null), pending = React.useRef(false);
    async function load(location) {
        const id = ++sequence.current;
        lastLoad.current = Date.now();
        pending.current = true;
        setBusy(true); setError(''); setData(null);
        try {
            const query = location ? '?' + new URLSearchParams(location) : '';
            const response = await fetch('/api/public/prayer-times' + query, {signal: AbortSignal.timeout(25000)});
            const body = await response.json();
            if (!response.ok || !body.success) throw new Error();
            if (id === sequence.current) { currentData.current = body.data; setData(body.data); }
        } catch (_) { if (id === sequence.current) setError('Jadwal belum dapat dimuat. Periksa internet lalu coba lagi.'); }
        finally { if (id === sequence.current) { pending.current = false; setBusy(false); } }
    }
    function locate() {
        if (!navigator.geolocation || !window.isSecureContext) {
            coords.current = null; setNotice('Lokasi tidak tersedia. Menggunakan Jakarta. Akses HTTPS diperlukan untuk izin lokasi.'); load(null); return;
        }
        const id = ++sequence.current; pending.current = true; setData(null); setBusy(true);
        navigator.geolocation.getCurrentPosition(position => {
            if (id !== sequence.current) return;
            coords.current = {latitude: position.coords.latitude.toFixed(3), longitude: position.coords.longitude.toFixed(3)};
            setNotice('Jadwal mengikuti koordinat dan zona waktu lokasi Anda.'); load(coords.current);
        }, () => {
            if (id !== sequence.current) return;
            coords.current = null; setNotice('Lokasi ditolak atau tidak tersedia. Menggunakan jadwal Jakarta.'); load(null);
        }, {enableHighAccuracy: false, timeout: 10000, maximumAge: 300000});
    }
    React.useEffect(() => {
        let active = true;
        load(null);
        // Reuse an existing permission; first-time permission is requested by the location button.
        if (navigator.permissions) navigator.permissions.query({name: 'geolocation'}).then(p => {
            if (active && p.state === 'granted') locate();
        }).catch(() => {});
        async function refresh() {
            if (!active || pending.current) return;
            if (coords.current && navigator.permissions) {
                try {
                    const permission = await navigator.permissions.query({name: 'geolocation'});
                    if (!active) return;
                    if (permission.state !== 'granted') {
                        coords.current = null; setNotice('Lokasi tidak diizinkan. Menggunakan jadwal Jakarta.');
                    } else {
                        locate(); return;
                    }
                } catch (_) {}
            }
            if (active) load(coords.current);
        }
        const timer = setInterval(() => {
            setClock(Date.now());
            const d = currentData.current;
            const today = d && new Intl.DateTimeFormat('en-CA', {timeZone: d.timezone, year: 'numeric', month: '2-digit', day: '2-digit'}).format(new Date());
            if ((d && today !== d.date) || Date.now() - lastLoad.current >= 300000) refresh();
        }, 30000);
        const onVisible = () => { if (document.visibilityState === 'visible') refresh(); };
        document.addEventListener('visibilitychange', onVisible);
        return () => { active = false; ++sequence.current; clearInterval(timer); document.removeEventListener('visibilitychange', onVisible); };
    }, []);
    const next = data?.prayers.find(p => p.key !== 'Sunrise' && Date.parse(p.at) > clock);
    return <section className="max-w-6xl mx-auto px-4" aria-label="Waktu shalat">
        <div className="rounded-2xl border border-emerald-200 bg-emerald-50 p-5 md:p-7">
            <div className="flex flex-wrap justify-between gap-4 items-start">
                <div><p className="text-xs tracking-widest font-bold text-emerald-700">PENGINGAT IBADAH</p><h2 className="text-2xl font-bold text-emerald-950 mt-1">Waktu shalat</h2>
                {data && <p className="text-sm text-emerald-800 mt-1">{data.location} · {data.timezone} · {data.date.split('-').reverse().join('/')}</p>}</div>
                <button disabled={busy} onClick={locate} className="rounded-lg bg-emerald-700 text-white px-4 py-2 font-semibold disabled:opacity-50">Gunakan lokasi saya</button>
            </div>
            <p className="text-sm text-gray-600 mt-3">{notice}</p>
            <div aria-live="polite">
                {busy && <p className="py-6 text-emerald-800">Memuat waktu shalat…</p>}
                {error && <div className="py-4"><p role="alert">{error}</p><button onClick={() => load(coords.current)} className="underline text-emerald-800 mt-2">Coba lagi</button></div>}
                {data && <><div className="grid grid-cols-2 sm:grid-cols-3 lg:grid-cols-6 gap-3 mt-5">{data.prayers.map(p => <div key={p.key} className={'rounded-xl p-4 ' + (next?.key === p.key ? 'bg-emerald-800 text-white' : 'bg-white text-emerald-950')}><p className="text-sm">{p.name}</p><p className="text-2xl font-bold mt-1">{p.time}</p>{next?.key === p.key && <p className="text-xs mt-1">Berikutnya</p>}</div>)}</div>
                <p className="text-xs text-gray-600 mt-4">Sumber: <a className="underline" href={data.sourceUrl} target="_blank" rel="noreferrer">Aladhan</a> · Metode Kemenag RI. Jadwal perhitungan dapat berbeda beberapa menit dari jadwal masjid setempat.</p></>}
            </div>
        </div>
    </section>;
};
