<script>
  let lat = $state(null);
  let lng = $state(null);
  let prayers = $state(null);
  let nextPrayer = $state(null);
  let loading = $state(true);
  let error = $state('');
  let method = $state(3);
  let geoLoading = $state(true);
  let notificationsEnabled = $state(false);
  let notificationPermission = $state('default');

  const methods = [
    { id: 3, name: 'Muslim World League' },
    { id: 2, name: 'ISNA (N. America)' },
    { id: 4, name: 'Umm al-Qura' },
    { id: 5, name: 'Egyptian' },
    { id: 1, name: 'Karachi University' },
  ];

  function loadSettings() {
    const savedMethod = localStorage.getItem('prayer_method');
    if (savedMethod) method = parseInt(savedMethod, 10);
    
    const savedLat = localStorage.getItem('prayer_lat');
    const savedLng = localStorage.getItem('prayer_lng');
    if (savedLat && savedLng) {
      lat = parseFloat(savedLat);
      lng = parseFloat(savedLng);
    }
    
    const savedNotifications = localStorage.getItem('prayer_notifications');
    if (savedNotifications !== null) {
      notificationsEnabled = savedNotifications === 'true';
    }
    
    if ('Notification' in window) {
      notificationPermission = Notification.permission;
    }
  }

  function saveMethod() {
    localStorage.setItem('prayer_method', String(method));
  }

  function saveLocation(latVal, lngVal) {
    localStorage.setItem('prayer_lat', String(latVal));
    localStorage.setItem('prayer_lng', String(lngVal));
  }

  function saveNotifications() {
    localStorage.setItem('prayer_notifications', String(notificationsEnabled));
  }

  async function requestNotificationPermission() {
    if (!('Notification' in window)) {
      error = 'Notifications not supported';
      return false;
    }
    
    if (Notification.permission === 'granted') {
      notificationPermission = 'granted';
      return true;
    }
    
    if (Notification.permission === 'denied') {
      error = 'Notifications blocked — enable in browser settings';
      return false;
    }
    
    const permission = await Notification.requestPermission();
    notificationPermission = permission;
    return permission === 'granted';
  }

  function schedulePrayerNotifications() {
    if (!prayers || !notificationsEnabled) return;
    
    if ('serviceWorker' in navigator) {
      navigator.serviceWorker.ready.then((registration) => {
        registration.active?.postMessage({
          type: 'SCHEDULE_PRAYERS',
          payload: { timings: prayers }
        });
      });
    }
    
    scheduleLocalNotifications();
  }

  function scheduleLocalNotifications() {
    const prayerNames = ['Fajr', 'Dhuhr', 'Asr', 'Maghrib', 'Isha'];
    const now = Date.parse(new Date().toISOString().split('T')[0] + 'T00:00:00');
    
    prayerNames.forEach((prayer) => {
      const timeStr = prayers[prayer];
      if (!timeStr) return;
      
      const [hours, minutes] = timeStr.split(':').map(Number);
      const prayerTime = now + hours * 3600000 + minutes * 60000;
      const notifyTime = prayerTime - 5 * 60 * 1000;
      const delay = notifyTime - Date.now();
      
      if (delay > 0 && delay < 24 * 60 * 60 * 1000) {
        setTimeout(() => {
          if (Notification.permission === 'granted') {
            new Notification(`Time for ${prayer}`, {
              body: `It's time for ${prayer} prayer (${timeStr})`,
              icon: '/icon-192.png',
              badge: '/icon-192.png',
              vibrate: [200, 100, 200],
              tag: `prayer-${prayer}`,
              renotify: true,
              requireInteraction: true
            });
          }
        }, delay);
      }
    });
  }

  function getLocation() {
    if (!navigator.geolocation) {
      error = 'Geolocation not supported';
      loading = false;
      geoLoading = false;
      return;
    }
    navigator.geolocation.getCurrentPosition(
      (pos) => {
        lat = pos.coords.latitude;
        lng = pos.coords.longitude;
        saveLocation(lat, lng);
        geoLoading = false;
        fetchPrayers();
      },
      () => {
        lat = 21.4225;
        lng = 39.8262;
        geoLoading = false;
        fetchPrayers();
      }
    );
  }

  async function fetchPrayers() {
    loading = true;
    error = '';
    try {
      const today = new Date().toISOString().split('T')[0];
      const url = `https://api.aladhan.com/v1/timings/${today}?latitude=${lat}&longitude=${lng}&method=${method}`;
      const res = await fetch(url);
      const data = await res.json();
      if (data.code === 200) {
        prayers = data.data.timings;
        nextPrayer = findNextPrayer(data.data.timings, data.data.meta.timezone);
        loading = false;
        schedulePrayerNotifications();
      } else {
        error = 'Could not load prayer times';
        loading = false;
      }
    } catch (e) {
      error = 'Network error — check connection';
      loading = false;
    }
  }

  function findNextPrayer(timings, tz) {
    const now = new Date();
    const names = ['Fajr', 'Sunrise', 'Dhuhr', 'Asr', 'Maghrib', 'Isha'];
    for (const name of names) {
      const [h, m] = timings[name].split(':').map(Number);
      const pt = new Date(now);
      pt.setHours(h, m, 0, 0);
      if (pt > now) return { name, time: timings[name] };
    }
    return { name: 'Fajr', time: timings['Fajr'] + ' (tomorrow)' };
  }

  async function toggleNotifications() {
    if (!notificationsEnabled) {
      const granted = await requestNotificationPermission();
      if (granted) {
        notificationsEnabled = true;
        saveNotifications();
        schedulePrayerNotifications();
      }
    } else {
      notificationsEnabled = false;
      saveNotifications();
    }
  }

  $effect(() => { loadSettings(); });
  $effect(() => { getLocation(); });
  $effect(() => { saveMethod(); });
  $effect(() => { saveNotifications(); });
  
  $effect(() => {
    if (prayers && notificationsEnabled) {
      schedulePrayerNotifications();
    }
  });
</script>

<div class="card">
  <h2>🕌 Prayer Times</h2>

  {#if geoLoading}
    <p class="loading">📍 Getting location…</p>
  {:else if loading}
    <p class="loading">⏳ Loading prayer times…</p>
  {:else if error}
    <p class="error">{error}</p>
    <button class="primary" onclick={fetchPrayers}>Retry</button>
  {:else if prayers}
    {#if nextPrayer}
      <div class="next-prayer">
        <span class="next-label">Next Prayer</span>
        <div class="next-info">
          <span class="next-name">{nextPrayer.name}</span>
          <span class="next-time">{nextPrayer.time}</span>
        </div>
      </div>
    {/if}

    <div class="prayer-grid">
      {#each ['Fajr', 'Sunrise', 'Dhuhr', 'Asr', 'Maghrib', 'Isha'] as name}
        <div class="prayer-row" class:active={nextPrayer?.name === name}>
          <span class="prayer-name">{name}</span>
          <span class="prayer-time">{prayers[name]}</span>
        </div>
      {/each}
    </div>

    <div class="method-select">
      <label for="method">Calculation Method</label>
      <select id="method" bind:value={method} onchange={fetchPrayers}>
        {#each methods as m}
          <option value={m.id}>{m.name}</option>
        {/each}
      </select>
    </div>

    <div class="notification-toggle">
      <label class="toggle-label">
        <input 
          type="checkbox" 
          checked={notificationsEnabled} 
          onchange={toggleNotifications}
          disabled={notificationPermission === 'denied'}
        />
        <span class="toggle-slider"></span>
        <span class="toggle-text">
          {notificationPermission === 'denied' 
            ? '🔔 Blocked — enable in settings' 
            : notificationsEnabled 
              ? '🔔 Prayer notifications ON' 
              : '🔔 Enable prayer notifications'}
        </span>
      </label>
    </div>
  {/if}
</div>

<style>
  .loading { color: var(--text-dim); text-align: center; padding: 20px; }
  .error { color: #FF6B6B; text-align: center; padding: 10px; }

  .next-prayer {
    background: linear-gradient(135deg, rgba(201,168,76,0.15), rgba(46,204,113,0.1));
    border: 1px solid var(--border);
    border-radius: 12px;
    padding: 16px;
    display: flex;
    flex-direction: column;
    align-items: center;
    gap: 8px;
    margin-bottom: 16px;
  }
  
  .next-label {
    font-family: 'JetBrains Mono', monospace;
    font-size: 0.62rem;
    letter-spacing: 0.15em;
    text-transform: uppercase;
    color: var(--gold);
  }
  
  .next-info { display: flex; flex-direction: column; align-items: center; gap: 4px; }
  .next-name { font-family: 'Cinzel', serif; font-size: 0.9rem; font-weight: 700; color: var(--text); }
  .next-time { font-family: 'Cinzel', serif; font-size: 1.8rem; font-weight: 900; color: var(--gold); font-variant-numeric: tabular-nums; }

  .prayer-grid {
    display: flex;
    flex-direction: column;
    gap: 6px;
    margin-bottom: 16px;
  }
  
  .prayer-row {
    display: flex;
    justify-content: space-between;
    padding: 12px 16px;
    background: var(--bg2);
    border: 1px solid var(--border);
    border-radius: 10px;
    transition: all 0.2s;
  }
  
  .prayer-row:hover { border-color: var(--gold); background: var(--gold-dim); }
  
  .prayer-row.active {
    background: var(--gold-dim);
    border-color: var(--gold);
    font-weight: 600;
  }
  
  .prayer-name { 
    font-family: 'DM Sans', sans-serif;
    font-weight: 500;
    color: var(--text); 
  }
  
  .prayer-time { 
    font-family: 'Cinzel', serif;
    font-weight: 700;
    font-variant-numeric: tabular-nums;
    color: var(--gold);
  }

  .method-select {
    display: flex;
    gap: 12px;
    align-items: center;
    font-family: 'JetBrains Mono', monospace;
    font-size: 0.65rem;
    letter-spacing: 0.08em;
    text-transform: uppercase;
    color: var(--text-dim);
    margin-bottom: 16px;
  }
  
  .method-select select {
    font-family: 'JetBrains Mono', monospace;
    font-size: 0.65rem;
    letter-spacing: 0.05em;
    border: 1px solid var(--border);
    border-radius: 6px;
    padding: 6px 10px;
    color: var(--text);
    background: var(--bg2);
    cursor: pointer;
  }
  
  .method-select select:focus {
    outline: none;
    border-color: var(--gold);
  }

  .notification-toggle { margin-top: 8px; }
  
  .toggle-label {
    display: flex;
    align-items: center;
    gap: 10px;
    cursor: pointer;
    font-family: 'JetBrains Mono', monospace;
    font-size: 0.65rem;
    letter-spacing: 0.05em;
    text-transform: uppercase;
    color: var(--text-dim);
  }
  
  .toggle-label input { display: none; }
  
  .toggle-slider {
    width: 44px;
    height: 24px;
    border-radius: 12px;
    background: var(--border);
    position: relative;
    transition: background 0.2s;
    flex-shrink: 0;
  }
  
  .toggle-label input:checked + .toggle-slider { background: linear-gradient(135deg, var(--gold), var(--gold-light)); }
  .toggle-label input:disabled + .toggle-slider { background: var(--text-muted); opacity: 0.5; }
  
  .toggle-slider::after {
    content: '';
    position: absolute;
    top: 2px;
    left: 2px;
    width: 20px;
    height: 20px;
    border-radius: 50%;
    background: var(--text);
    transition: transform 0.2s, background 0.2s;
    box-shadow: 0 1px 3px rgba(0,0,0,0.3);
  }
  
  .toggle-label input:checked + .toggle-slider::after { transform: translateX(20px); background: var(--bg); }
  
  .toggle-text { font-weight: 500; }
  .toggle-label input:disabled ~ .toggle-text { color: var(--text-muted); }
</style>