<script>
  let bearing = $state(0);
  let loading = $state(true);
  let error = $state('');
  let deviceAlpha = $state(0);
  let needsPermission = $state(false);

  const KAABA = { lat: 21.4225, lng: 39.8262 };

  function toRad(d) { return (d * Math.PI) / 180; }
  function toDeg(r) { return (r * 180) / Math.PI; }

  function calcBearing(lat, lng) {
    const dLng = toRad(KAABA.lng - lng);
    const y = Math.sin(dLng) * Math.cos(toRad(KAABA.lat));
    const x = Math.cos(toRad(lat)) * Math.sin(toRad(KAABA.lat))
            - Math.sin(toRad(lat)) * Math.cos(toRad(KAABA.lat)) * Math.cos(dLng);
    return (toDeg(Math.atan2(y, x)) + 360) % 360;
  }

  async function requestCompassPermission() {
    if ('DeviceOrientationEvent' in window && typeof DeviceOrientationEvent.requestPermission === 'function') {
      try {
        const permission = await DeviceOrientationEvent.requestPermission();
        if (permission === 'granted') {
          needsPermission = false;
          startCompass();
        } else {
          error = 'Compass permission denied';
          needsPermission = true;
          loading = false;
        }
      } catch (e) {
        error = 'Failed to request compass permission';
        loading = false;
      }
    } else {
      startCompass();
    }
  }

  function startCompass() {
    if (!navigator.geolocation) {
      error = 'Geolocation not supported';
      loading = false;
      return;
    }
    navigator.geolocation.getCurrentPosition(
      (pos) => {
        bearing = calcBearing(pos.coords.latitude, pos.coords.longitude);
        loading = false;
      },
      () => {
        bearing = calcBearing(3.1390, 101.6869);
        loading = false;
      }
    );

    if (window.DeviceOrientationEvent) {
      window.addEventListener('deviceorientation', (e) => {
        if (e.webkitCompassHeading !== undefined) {
          deviceAlpha = e.webkitCompassHeading;
        } else if (e.alpha !== null) {
          deviceAlpha = 360 - e.alpha;
        }
      });
    }
  }

  $effect(() => { requestCompassPermission(); });

  const needleAngle = $derived(bearing - deviceAlpha);
</script>

<div class="card">
  <h2>🧭 Qibla Finder</h2>

  {#if loading}
    <p class="loading">📍 Getting location…</p>
  {:else if error}
    <p class="error">{error}</p>
    {#if needsPermission}
      <button class="primary" onclick={requestCompassPermission}>Enable Compass</button>
    {:else}
      <button class="primary" onclick={requestCompassPermission}>Retry</button>
    {/if}
  {:else}
    <div class="compass-box">
      <div class="compass" style="transform: rotate({needleAngle}deg)">
        <div class="needle">
          <svg viewBox="0 0 60 80" width="40" height="60">
            <polygon points="30,0 0,80 30,60 60,80" fill="var(--gold)" />
          </svg>
        </div>
      </div>
      <div class="bearing-info">
        <span class="bearing-num">{Math.round(bearing)}°</span>
        <span class="bearing-dir">from North</span>
      </div>
      <p class="compass-hint">
        {deviceAlpha === 0 
          ? '🗺️ Move your device to calibrate compass' 
          : '↗️ Point the needle towards the Kaaba'}
      </p>
      <div class="kaaba-info">
        <span class="kaaba-label">Al-Masjid Al-Haram</span>
        <span class="kaaba-coords">21.4225° N, 39.8262° E</span>
      </div>
    </div>
  {/if}
</div>

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

  .compass-box {
    display: flex;
    flex-direction: column;
    align-items: center;
    gap: 16px;
    padding: 10px 0;
  }
  
  .compass {
    width: 180px;
    height: 180px;
    border-radius: 50%;
    background: var(--bg2);
    border: 2px solid var(--border);
    display: flex;
    align-items: center;
    justify-content: center;
    transition: transform 0.3s ease;
    position: relative;
  }
  
  .compass::before {
    content: '';
    position: absolute;
    inset: -2px;
    border-radius: 50%;
    background: linear-gradient(45deg, var(--gold), var(--green), var(--gold));
    opacity: 0;
    transition: opacity 0.3s;
    z-index: -1;
  }
  
  .compass:hover::before { opacity: 0.5; }
  
  .needle {
    display: flex;
    align-items: center;
    justify-content: center;
    filter: drop-shadow(0 4px 8px rgba(0,0,0,0.3));
  }
  
  .bearing-info {
    display: flex;
    flex-direction: column;
    align-items: center;
    gap: 4px;
  }
  
  .bearing-num { 
    font-family: 'Cinzel', serif;
    font-size: 2.5rem;
    font-weight: 900;
    color: var(--gold);
    text-shadow: 0 0 20px rgba(201,168,76,0.3);
  }
  
  .bearing-dir { 
    font-family: 'JetBrains Mono', monospace;
    font-size: 0.7rem;
    letter-spacing: 0.1em;
    text-transform: uppercase;
    color: var(--text-dim);
  }
  
  .compass-hint { 
    font-family: 'DM Sans', sans-serif;
    font-size: 0.75rem;
    color: var(--text-muted);
    text-align: center;
    max-width: 280px;
  }
  
  .kaaba-info {
    display: flex;
    flex-direction: column;
    align-items: center;
    gap: 2px;
    padding-top: 8px;
    border-top: 1px solid var(--border);
    width: 100%;
    max-width: 280px;
  }
  
  .kaaba-label {
    font-family: 'Cinzel', serif;
    font-size: 0.85rem;
    font-weight: 600;
    color: var(--text);
  }
  
  .kaaba-coords {
    font-family: 'JetBrains Mono', monospace;
    font-size: 0.6rem;
    letter-spacing: 0.05em;
    color: var(--text-dim);
  }
</style>