<script>
  import { passes, trackedSat, watchlist, satList, passesViewMode, passesMinEl, passesAllCache } from '../stores/satstore.js'
  import { Go } from '../lib/wails.js'
  import { formatDuration, formatEl, formatAz, formatUTC, passQuality } from '../lib/utils.js'
  import PolarPlot from './PolarPlot.svelte'
  import { onMount, onDestroy } from 'svelte'

  export let currentAz = null
  export let currentEl = null

  let now = Date.now()
  let ticker
  let selectedPass = null
  let selectedPassSat = null

  // View mode and filter — persisted in stores so they survive tab switches
  $: viewMode = $passesViewMode
  $: minEl = $passesMinEl

  // All passes cache — persisted in store (in-memory, not localStorage)
  $: allPasses = $passesAllCache
  let loadingAll = false

  onMount(() => {
    ticker = setInterval(() => { now = Date.now() }, 1000)
  })
  onDestroy(() => clearInterval(ticker))

  async function loadAllPasses() {
    if (loadingAll) return
    loadingAll = true
    passesAllCache.set([])
    const wl = $watchlist
    const results = await Promise.all(
      wl.map(async name => {
        try {
          const ps = await Go.GetPasses(name, 24)
          return (ps || []).map(p => ({ ...p, satName: name }))
        } catch { return [] }
      })
    )
    passesAllCache.set(results.flat())
    loadingAll = false
  }

  $: if ($passesViewMode === 'all' && $passesAllCache.length === 0 && !loadingAll) {
    loadAllPasses()
  }

  // Source passes based on mode
  $: sourcePasses = $passesViewMode === 'single'
    ? ($passes || []).map(p => ({ ...p, satName: $trackedSat }))
    : $passesAllCache

  // Filter and sort
  $: filteredPasses = sourcePasses
    .filter(p => {
      if (new Date(p.los).getTime() <= now) return false
      if (p.maxEl < $passesMinEl) return false
      return true
    })
    .sort((a, b) => new Date(a.aos) - new Date(b.aos))

  $: if (filteredPasses.length > 0 && !selectedPass) {
    selectedPass = filteredPasses[0]
    selectedPassSat = filteredPasses[0].satName
  }

  function selectPass(p) {
    selectedPass = p
    selectedPassSat = p.satName
  }

  function isActive(p) {
    const aos = new Date(p.aos).getTime()
    const los = new Date(p.los).getTime()
    return now >= aos && now <= los
  }

  function countdown(p) {
    const aos = new Date(p.aos).getTime()
    const los = new Date(p.los).getTime()
    if (now >= aos && now <= los) {
      return { label: 'LOS in', secs: Math.floor((los - now) / 1000), live: true }
    }
    return { label: 'AOS in', secs: Math.floor((aos - now) / 1000), live: false }
  }

  function fmtCountdown(secs) {
    if (secs <= 0) return '00:00'
    const h = Math.floor(secs / 3600)
    const m = Math.floor((secs % 3600) / 60)
    const s = secs % 60
    if (h > 0) return `${h}h ${String(m).padStart(2,'0')}m`
    return `${String(m).padStart(2,'0')}:${String(s).padStart(2,'0')}`
  }

  function passProgress(p) {
    const aos = new Date(p.aos).getTime()
    const los = new Date(p.los).getTime()
    if (now < aos || now > los) return 0
    return Math.round((now - aos) / (los - aos) * 100)
  }

  async function trackSatFromPass(satName) {
    if (!satName) return
    trackedSat.set(satName)
    const ps = await Go.GetPasses(satName, 24)
    passes.set(ps || [])
    await Go.StartTracking(satName)
  }

  const EL_FILTERS = [
    { label: 'All', value: 0 },
    { label: '≥ 10°', value: 10 },
    { label: '≥ 30°', value: 30 },
    { label: '≥ 60° Excellent', value: 60 },
  ]
</script>

<div class="panel">
  <!-- Pass list -->
  <div class="pass-list">

    <!-- Toolbar -->
    <div class="toolbar">
      <div class="view-toggle">
        <button class="vbtn {$passesViewMode==='single'?'on':''}" on:click={() => { passesViewMode.set('single'); selectedPass=null }}>
          This satellite
        </button>
        <button class="vbtn {$passesViewMode==='all'?'on':''}" on:click={() => { passesViewMode.set('all'); selectedPass=null; loadAllPasses() }}>
          All watchlist
        </button>
      </div>

      <div class="el-filters">
        {#each EL_FILTERS as f}
          <button class="elfbtn {$passesMinEl===f.value?'on':''}" on:click={() => { passesMinEl.set(f.value); selectedPass=null }}>
            {f.label}
          </button>
        {/each}
      </div>
    </div>

    <!-- Header -->
    <div class="list-hdr">
      <span class="hdr-title">
        {$passesViewMode === 'single' ? `PASSES — ${$trackedSat || '—'}` : 'ALL PASSES — WATCHLIST'}
      </span>
      <span class="hdr-count">
        {#if loadingAll}
          <span class="loading">Loading…</span>
        {:else}
          {filteredPasses.length} passes / 24h
        {/if}
      </span>
    </div>

    {#if $passesViewMode === 'single' && !$trackedSat}
      <div class="empty">Select a satellite to view its passes</div>
    {:else if filteredPasses.length === 0 && !loadingAll}
      <div class="empty">No pass{$passesMinEl > 0 ? ` with elevation ≥ ${$passesMinEl}°` : ''} in the next 24 hours</div>
    {:else}
      <div class="pass-rows">
        {#each filteredPasses as pass (pass.aos + pass.satName)}
          {@const q = passQuality(pass.maxEl)}
          {@const active = isActive(pass)}
          {@const cd = countdown(pass)}
          {@const progress = passProgress(pass)}
          {@const sel = selectedPass?.aos === pass.aos && selectedPassSat === pass.satName}

          <div class="pass-row {sel?'selected':''} {active?'active':''}"
               on:click={() => selectPass(pass)}
               on:dblclick={() => trackSatFromPass(pass.satName)}>

            <!-- Sat name (only in multi mode) -->
            {#if $passesViewMode === 'all'}
              <div class="pass-sat">{pass.satName} <span class="dbl-hint">double-click to track</span></div>
            {/if}

            <div class="pass-body">
              <!-- Left -->
              <div class="pass-left">
                <span class="pass-time">{formatUTC(pass.aos)} UTC</span>
                <div class="countdown {cd.live?'live':cd.secs<300?'soon':''}">
                  {#if cd.live}<span class="live-dot"></span>{/if}
                  <span>{cd.label}</span>
                  <span class="cd-val">{fmtCountdown(cd.secs)}</span>
                </div>
                {#if active && progress > 0}
                  <div class="progress-bar">
                    <div class="progress-fill" style="width:{progress}%"></div>
                  </div>
                {/if}
              </div>

              <!-- Center -->
              <div class="pass-center">
                <span class="max-el {q.cls}">▲ {formatEl(pass.maxEl)}</span>
                <span class="duration">⏱ {formatDuration(pass.duration)}</span>
                <span class="quality-badge {q.cls}">{q.label}</span>
              </div>

              <!-- Right -->
              <div class="pass-right">
                <div class="az-row"><span class="az-lbl">AOS</span><span class="az-val">{formatAz(pass.aosAz)}</span></div>
                <div class="az-row"><span class="az-lbl">MAX</span><span class="az-val">{formatAz(pass.maxElAz)}</span></div>
                <div class="az-row"><span class="az-lbl">LOS</span><span class="az-val">{formatAz(pass.losAz)}</span></div>
              </div>
            </div>
          </div>
        {/each}
      </div>
    {/if}
  </div>

  <!-- Detail panel -->
  <div class="pass-detail">
    <div class="polar-wrap">
      <PolarPlot
        points={selectedPass?.points || []}
        currentAz={currentAz}
        currentEl={currentEl}
        satName={selectedPassSat || $trackedSat}
        size={220}
      />
    </div>

    {#if selectedPass}
      {@const q = passQuality(selectedPass.maxEl)}
      {@const cd = countdown(selectedPass)}
      <div class="detail-box">
        {#if $passesViewMode === 'all'}
          <div class="detail-satname">{selectedPassSat}</div>
        {/if}
        <div class="detail-title">{formatUTC(selectedPass.aos)} UTC</div>

        <div class="detail-countdown {cd.live?'live':cd.secs<300?'soon':''}">
          {#if cd.live}<span class="live-dot"></span>{/if}
          <span class="cd-label">{cd.label}</span>
          <span class="cd-big">{fmtCountdown(cd.secs)}</span>
        </div>

        <div class="detail-grid">
          <span class="dk">AOS</span>       <span class="dv">{formatUTC(selectedPass.aos)} UTC</span>
          <span class="dk">LOS</span>       <span class="dv">{formatUTC(selectedPass.los)} UTC</span>
          <span class="dk">Duration</span>     <span class="dv">{formatDuration(selectedPass.duration)}</span>
          <span class="dk">Max El</span>    <span class="dv {q.cls}">{formatEl(selectedPass.maxEl)}</span>
          <span class="dk">Az Max El</span> <span class="dv">{formatAz(selectedPass.maxElAz)}</span>
          <span class="dk">AOS Az</span>    <span class="dv">{formatAz(selectedPass.aosAz)}</span>
          <span class="dk">LOS Az</span>    <span class="dv">{formatAz(selectedPass.losAz)}</span>
          <span class="dk">Quality</span>   <span class="dv {q.cls}">{q.label}</span>
        </div>
      </div>
    {:else}
      <div class="empty" style="padding:20px;text-align:center">
        Select a pass
      </div>
    {/if}
  </div>
</div>

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

  /* Toolbar */
  .toolbar { display:flex; flex-direction:column; gap:8px; padding:10px 14px; background:#f8fafc; border-bottom:1px solid #e8edf2; flex-shrink:0; }

  .view-toggle { display:flex; gap:4px; background:#f0f4f8; border-radius:8px; padding:3px; width:fit-content; }
  .vbtn { background:none; border:none; color:#7a9ab8; font-family:'Inter',sans-serif; font-size:12px; font-weight:500; padding:5px 12px; border-radius:6px; cursor:pointer; transition:all .15s; }
  .vbtn.on { background:white; color:#1a5a9a; font-weight:700; box-shadow:0 1px 3px rgba(0,0,0,0.1); }

  .el-filters { display:flex; gap:4px; flex-wrap:wrap; }
  .elfbtn { background:#f0f4f8; border:1.5px solid #e0e8f0; color:#6a8aa8; font-family:'Inter',sans-serif; font-size:11px; font-weight:500; padding:4px 10px; border-radius:20px; cursor:pointer; transition:all .15s; }
  .elfbtn:hover { border-color:#1a5a9a; color:#1a5a9a; }
  .elfbtn.on { background:#1a5a9a; border-color:#1a5a9a; color:white; font-weight:700; }

  /* List */
  .pass-list { flex:1; display:flex; flex-direction:column; border-right:1px solid #e8edf2; overflow:hidden; min-width:0; }
  .list-hdr { display:flex; justify-content:space-between; align-items:center; padding:8px 14px; background:white; border-bottom:1px solid #e8edf2; flex-shrink:0; }
  .hdr-title { font-size:11px; font-weight:700; color:#1a5a9a; letter-spacing:.04em; }
  .hdr-count { font-size:11px; color:#9ab0c8; }
  .loading { color:#9ab0c8; font-style:italic; font-size:11px; animation:pulse 1.5s infinite; }
  @keyframes pulse { 0%,100%{opacity:1} 50%{opacity:.4} }

  .empty { padding:40px 20px; text-align:center; color:#9ab0c8; font-size:13px; line-height:1.8; }

  .pass-rows { flex:1; overflow-y:auto; }
  .pass-rows::-webkit-scrollbar { width:4px; }
  .pass-rows::-webkit-scrollbar-thumb { background:#d0dce8; border-radius:2px; }

  .pass-row { border-bottom:1px solid #f0f4f8; cursor:pointer; transition:background .1s; }
  .pass-row:active { background:#e8f0fa; }
  .pass-row:hover { background:#f8fafc; }
  .pass-row.selected { background:#f0f6ff; border-left:3px solid #1a5a9a; }
  .pass-row.active   { background:#f0f9f4; border-left:3px solid #1a9a50; }

  .pass-sat { font-size:11px; font-weight:700; color:#1a5a9a; padding:6px 14px 0; }
  .dbl-hint { font-size:9px; color:#b0c4d8; font-weight:400; margin-left:6px; }

  .pass-body { display:flex; gap:12px; align-items:flex-start; padding:8px 14px; }

  .pass-left { display:flex; flex-direction:column; gap:3px; min-width:110px; }
  .pass-time { font-size:13px; color:#1a2a3a; font-weight:600; }
  .countdown { display:flex; align-items:center; gap:5px; font-size:11px; color:#7a9ab8; }
  .countdown.live { color:#1a9a50; }
  .countdown.soon { color:#e07030; }
  .cd-val { font-weight:700; font-size:13px; }
  .live-dot { width:7px; height:7px; border-radius:50%; background:#1a9a50; box-shadow:0 0 5px #1a9a50; animation:blink 1.2s infinite; flex-shrink:0; }
  .progress-bar { height:3px; background:#e0f0e8; border-radius:2px; margin-top:4px; }
  .progress-fill { height:100%; background:#1a5a9a; border-radius:2px; transition:width .5s; }

  .pass-center { display:flex; flex-direction:column; gap:3px; align-items:center; min-width:80px; }
  .max-el { font-size:15px; font-weight:700; }
  .duration { font-size:10px; color:#9ab0c8; }
  .quality-badge { font-size:9px; padding:2px 7px; border-radius:10px; font-weight:700; }

  .q-excellent { color:#1a7a40; }
  .q-excellent.quality-badge { background:#e0f7ee; }
  .q-good { color:#1a5a9a; }
  .q-good.quality-badge { background:#e0eeff; }
  .q-fair { color:#9a6010; }
  .q-fair.quality-badge { background:#fff4e0; }
  .q-poor { color:#c03030; }
  .q-poor.quality-badge { background:#fff0f0; }

  .pass-right { display:flex; flex-direction:column; gap:2px; margin-left:auto; }
  .az-row { display:flex; gap:6px; align-items:baseline; }
  .az-lbl { font-size:9px; color:#9ab0c8; width:24px; font-weight:700; }
  .az-val { font-size:11px; color:#4a6a8a; }

  /* Detail */
  .pass-detail { width:300px; flex-shrink:0; display:flex; flex-direction:column; background:#f8fafc; overflow-y:auto; }
  .pass-detail::-webkit-scrollbar { width:4px; }
  .pass-detail::-webkit-scrollbar-thumb { background:#d0dce8; }

  .polar-wrap { padding:16px; display:flex; justify-content:center; border-bottom:1px solid #e8edf2; }

  .detail-box { padding:14px 16px; display:flex; flex-direction:column; gap:10px; }
  .detail-satname { font-size:12px; font-weight:700; color:#1a5a9a; }
  .detail-title { font-size:12px; color:#4a6a8a; font-weight:600; }

  .detail-countdown { display:flex; align-items:center; gap:8px; background:white; border:1.5px solid #e0e8f0; border-radius:10px; padding:10px 14px; }
  .detail-countdown.live { border-color:#1a5a9a; background:#f0f6ff; }
  .detail-countdown.soon { border-color:#e07030; background:#fff8f0; }
  .cd-label { font-size:10px; color:#9ab0c8; font-weight:600; text-transform:uppercase; letter-spacing:.06em; }
  .cd-big { font-size:22px; font-weight:700; color:#1a2a3a; margin-left:auto; }
  .detail-countdown.live .cd-big { color:#1a5a9a; }
  .detail-countdown.soon .cd-big { color:#e07030; }

  .detail-grid { display:grid; grid-template-columns:auto 1fr; gap:5px 12px; }
  .dk { font-size:10px; color:#9ab0c8; text-transform:uppercase; letter-spacing:.06em; align-self:center; font-weight:600; }
  .dv { font-size:12px; color:#1a2a3a; font-weight:600; }

  @keyframes blink { 0%,100%{opacity:1} 50%{opacity:.3} }
</style>