<script>
  import { trackedSat, passes, settings, watchlist, trackFreqMode, trackAzimuth, trackedPosition } from '../stores/satstore.js'
  import { formatRange, formatEl, formatAz, formatFreq } from '../lib/utils.js'
  import { Go } from '../lib/wails.js'
  import { getFrequencies, getPrimaryFrequency, getSatType, TYPE_STYLE, getDisplayName } from '../lib/satdb.js'

  // Sync track toggles to Go backend
  $: Go.SetTrackFreqMode($trackFreqMode)
  $: Go.SetTrackAzimuth($trackAzimuth)

  let search = ''
  let loading = false
  let freqIndex = 0

  $: displayList = [...new Set($watchlist)]
    .filter(n => !search || n.toLowerCase().includes(search.toLowerCase()) || getDisplayName(n).toLowerCase().includes(search.toLowerCase()))
    .sort((a, b) => getDisplayName(a).localeCompare(getDisplayName(b)))

  $: satFreqs = getFrequencies($trackedSat)
  $: selectedFreq = satFreqs?.[freqIndex] || null
  $: hasFreqs = satFreqs && satFreqs.length > 0
  // Auto-disable Track Freq/Mode if satellite has no known frequencies
  $: if (!hasFreqs && $trackFreqMode) trackFreqMode.set(false)
  $: satDisplayName = getDisplayName($trackedSat)

  async function selectSat(name) {
    if ($trackedSat === name) return
    loading = true
    freqIndex = 0
    // Reset tracking toggles for new satellite
    trackFreqMode.set(false)
    trackAzimuth.set(false)
    trackedSat.set(name)
    const ps = await Go.GetPasses(name, 24)
    passes.set(ps || [])
    await Go.StartTracking(name)
    const freq = getPrimaryFrequency(name)
    if (freq) await applyFrequency(freq)
    loading = false
  }

  async function applyFrequency(freq) {
    const down = freq.downHz || 0
    const up   = freq.upHz   || 0
    // Always update the nominal frequencies for Doppler calculation
    settings.update(s => ({ ...s, downlinkHz: down, uplinkHz: up }))
    await Go.SetSatelliteFrequencies(down, up)
    // Only apply mode to radio if Track Freq/Mode is active
    if (freq.mode && $trackFreqMode) await Go.SetSatelliteMode(freq.mode)
  }

  async function stopTracking() {
    await Go.StopTracking()
    trackedSat.set('')
    passes.set([])
  }
</script>

<div class="sel">
  <div class="search-bar">
    <span class="sico">🔍</span>
    <input type="text" bind:value={search} placeholder="Filter…" class="sinput"/>
    {#if search}<button class="clr" on:click={()=>search=''}>×</button>{/if}
  </div>

  {#if $trackedSat}
    <div class="tracked-bar">
      <div class="tracked-info">
        <span class="live-dot"></span>
        <span class="tname">{satDisplayName || $trackedSat}</span>
      </div>
      <button class="stop-btn" on:click={stopTracking}>Stop</button>
    </div>

    <!-- Track toggles -->
    <div class="track-row">
      <button class="track-btn {$trackFreqMode ? 'track-on' : ''} {!hasFreqs ? 'track-disabled' : ''}"
        on:click={() => hasFreqs && trackFreqMode.update(v => !v)}
        title={!hasFreqs ? 'No known frequencies for this satellite' : ''}>
        <span class="track-dot {$trackFreqMode ? 'on' : ''}"></span>
        Track Freq/Mode
      </button>
      <button class="track-btn {$trackAzimuth ? 'track-on' : ''}"
        on:click={() => trackAzimuth.update(v => !v)}>
        <span class="track-dot {$trackAzimuth ? 'on' : ''}"></span>
        Track Azimuth
      </button>
    </div>

    {#if satFreqs && satFreqs.length > 0}
      <div class="freq-section">
        <div class="freq-title">Frequencies</div>
        {#each satFreqs as freq, i}
          <button class="freq-card {freqIndex === i ? 'active' : ''}"
            on:click={() => { freqIndex = i; applyFrequency(freq) }}>
            <div class="freq-head">
              <span class="freq-mode">{freq.mode}</span>
              {#if freqIndex === i}<span class="freq-check">✓ Active</span>{/if}
            </div>
            <div class="freq-rx">↓ {formatFreq(freq.downHz)}</div>
            {#if freq.upHz > 0}
              <div class="freq-tx">↑ {formatFreq(freq.upHz)}</div>
            {:else}
              <div class="freq-tx muted">Simplex / RX only</div>
            {/if}
            {#if freq.notes}<div class="freq-notes">{freq.notes}</div>{/if}
          </button>
        {/each}
      </div>
    {:else}
      <div class="no-freq">No known frequencies for this satellite</div>
    {/if}
  {/if}

  {#if !$trackedSat && !search}
    <div class="sec-lbl">FAVORITES</div>
    <div class="faves">
      {#each $watchlist.slice(0,8) as f}
        <button class="fave" on:click={() => selectSat(f)}>
          {f.replace(' (ZARYA)','').replace(' (FM)','')}
        </button>
      {/each}
    </div>
  {/if}

  <div class="sec-lbl">WATCHLIST ({displayList.length})</div>
  <div class="sat-list">
    {#if displayList.length === 0}
      <div class="empty">Use the 🛰 button on the map to add satellites</div>
    {:else}
      {#each displayList as name}
        <button class="sitem {$trackedSat === name ? 'on' : ''}" on:click={() => selectSat(name)}>
          <span class="sdot {$trackedSat === name ? 'active' : ''}"></span>
          <span class="sname">{getDisplayName(name)}</span>
          {#if getSatType(name)}
            {@const t = getSatType(name)}
            {@const s = TYPE_STYLE[t]}
            <span class="type-badge" style="background:{s.bg};color:{s.color};border-color:{s.border}">{t}</span>
          {/if}
        </button>
      {/each}
    {/if}
  </div>
  <!-- Satellite info panel — always visible when satellite is tracked -->
  {#if $trackedSat && $trackedPosition}
    {@const pos = $trackedPosition}
    <div class="sat-info-panel">
      <div class="sip-row">
        <span class="sip-k">AZ</span><span class="sip-v">{pos.az?.toFixed(1)}°</span>
        <span class="sip-k">EL</span><span class="sip-v {pos.el >= 0 ? 'up' : ''}">{pos.el?.toFixed(1)}°</span>
      </div>
      <div class="sip-row">
        <span class="sip-k">Range</span><span class="sip-v">{formatRange(pos.range)}</span>
        <span class="sip-k">Alt</span><span class="sip-v">{pos.alt?.toFixed(0)} km</span>
      </div>
      <div class="sip-row">
        <span class="sip-k">Radial</span>
        <span class="sip-v {pos.rangeRate < 0 ? 'approach' : 'recede'}">
          {pos.rangeRate < 0 ? '▼' : '▲'} {Math.abs(Math.round(pos.rangeRate * 3600)).toLocaleString('en-US')} km/h
        </span>
      </div>
    </div>
  {/if}
</div>

<style>
  .sel { display:flex; flex-direction:column; height:100%; overflow:hidden; background:white; font-family:'Inter',sans-serif; }

  .search-bar { display:flex; align-items:center; gap:8px; padding:10px 12px; border-bottom:1px solid #e8edf2; }
  .sico { color:#9ab0c8; font-size:13px; }
  .sinput { flex:1; background:transparent; border:none; color:#1a2a3a; font-family:'Inter',sans-serif; font-size:13px; outline:none; }
  .sinput::placeholder { color:#b0c4d8; }
  .clr { background:none; border:none; color:#9ab0c8; cursor:pointer; font-size:16px; padding:0; }

  .tracked-bar { display:flex; align-items:center; justify-content:space-between; padding:8px 12px; background:#f0f6ff; border-bottom:1px solid #d0e0f0; }
  .tracked-info { display:flex; align-items:center; gap:7px; }
  .live-dot { width:8px; height:8px; border-radius:50%; background:#1a5a9a; box-shadow:0 0 6px rgba(26,90,154,0.5); animation:blink 1.5s infinite; flex-shrink:0; }
  .tname { font-size:12px; font-weight:600; color:#1a5a9a; overflow:hidden; text-overflow:ellipsis; white-space:nowrap; }
  .stop-btn { background:none; border:1px solid #e0a0a0; color:#c03030; font-size:11px; padding:3px 8px; cursor:pointer; border-radius:5px; font-family:'Inter',sans-serif; }
  .stop-btn:hover { background:#fff0f0; }

  .freq-section { padding:10px 12px; border-bottom:1px solid #e8edf2; display:flex; flex-direction:column; gap:6px; }
  .freq-title { font-size:10px; font-weight:600; color:#9ab0c8; text-transform:uppercase; letter-spacing:.08em; }
  .freq-card { background:#f8fafc; border:1.5px solid #e0e8f0; border-radius:8px; padding:8px 10px; cursor:pointer; text-align:left; display:flex; flex-direction:column; gap:2px; transition:all .15s; font-family:'Inter',sans-serif; }
  .freq-card:hover { border-color:#5a9ad5; background:#f0f6ff; }
  .freq-card.active { border-color:#1a5a9a; background:#e8f0fa; }
  .freq-head { display:flex; justify-content:space-between; align-items:center; }
  .freq-mode { font-size:12px; font-weight:700; color:#1a2a3a; }
  .freq-check { font-size:10px; color:#1a7a40; font-weight:600; }
  .freq-rx { font-size:13px; font-weight:700; color:#1a5a9a; }
  .freq-tx { font-size:12px; color:#e07030; }
  .freq-tx.muted { color:#9ab0c8; font-style:italic; }
  .freq-notes { font-size:10px; color:#9ab0c8; }

  .no-freq { padding:10px 12px; font-size:11px; color:#9ab0c8; font-style:italic; border-bottom:1px solid #e8edf2; }

  .sec-lbl { font-size:10px; font-weight:600; color:#9ab0c8; letter-spacing:.08em; padding:8px 12px 4px; text-transform:uppercase; }

  .faves { display:flex; flex-wrap:wrap; gap:4px; padding:4px 12px 8px; }
  .fave { background:#f0f4f8; border:1px solid #d0dce8; color:#4a7a9a; font-family:'Inter',sans-serif; font-size:11px; font-weight:500; padding:3px 8px; border-radius:5px; cursor:pointer; transition:all .15s; }
  .fave:hover { background:#1a5a9a; color:white; border-color:#1a5a9a; }

  .sat-list { flex:1; overflow-y:auto; }
  .sat-list::-webkit-scrollbar { width:3px; }
  .sat-list::-webkit-scrollbar-thumb { background:#d0dce8; border-radius:2px; }

  .sitem { display:flex; align-items:center; gap:8px; width:100%; background:none; border:none; border-bottom:1px solid #f0f4f8; color:#4a6a8a; font-family:'Inter',sans-serif; font-size:12px; padding:8px 12px; text-align:left; cursor:pointer; transition:background .1s; }
  .sitem:hover { background:#f5f8fc; color:#1a2a3a; }
  .sitem.on { background:#e8f0fa; color:#1a5a9a; font-weight:600; border-left:3px solid #1a5a9a; }

  .sdot { width:9px; height:9px; border-radius:50%; background:#d0dce8; flex-shrink:0; }
  .sdot.active { background:#1a9a50; box-shadow:0 0 6px #1a9a50; }
  .sname { flex:1; overflow:hidden; text-overflow:ellipsis; white-space:nowrap; }
  .type-badge {
    font-size:9px; font-weight:700; padding:1px 6px;
    border-radius:10px; border:1px solid; white-space:nowrap;
    flex-shrink:0; letter-spacing:.02em;
  }
  .empty { padding:20px 12px; text-align:center; color:#9ab0c8; font-size:11px; line-height:1.7; }

  @keyframes blink { 0%,100%{opacity:1} 50%{opacity:.3} }

  .sat-info-panel {
    border-top:1px solid #e8edf2; background:#f8fafc;
    padding:8px 12px; display:flex; flex-direction:column; gap:4px;
    flex-shrink:0;
  }
  .sip-row { display:flex; align-items:center; gap:8px; flex-wrap:wrap; }
  .sip-k { font-size:10px; font-weight:600; color:#9ab0c8; text-transform:uppercase; letter-spacing:.06em; min-width:36px; }
  .sip-v { font-size:12px; font-weight:700; color:#1a2a3a; flex:1; }
  .sip-v.up { color:#1a9a50; }
  .sip-v.approach { color:#1a9a50; }
  .sip-v.recede { color:#1a5a9a; }

  .track-row { display:flex; gap:6px; padding:8px 12px; border-bottom:1px solid #e8edf2; }
  .track-btn {
    flex:1; display:flex; align-items:center; gap:6px;
    background:#f8fafc; border:1.5px solid #e0e8f0;
    color:#7a9ab8; font-family:'Inter',sans-serif;
    font-size:10px; font-weight:600; padding:5px 8px;
    border-radius:6px; cursor:pointer; transition:all .15s;
  }
  .track-btn:hover:not(.track-disabled) { border-color:#1a5a9a; color:#1a5a9a; }
  :global(.track-disabled) { opacity:0.4 !important; cursor:not-allowed !important; }
  .track-btn.track-on { background:#e8f0fa; border-color:#1a5a9a; color:#1a5a9a; }
  .track-dot { width:6px; height:6px; border-radius:50%; background:#d0dce8; flex-shrink:0; transition:all .15s; }
  .track-dot.on { background:#1a5a9a; box-shadow:0 0 4px rgba(26,90,154,0.5); animation:blink 1.5s infinite; }
</style>