import { writable } from 'svelte/store'

// All satellite positions (updated every second from backend)
export const satPositions = writable([])

// List of available satellite names
export const satList = writable([])

// Currently selected/tracked satellite name
export const trackedSat = writable('')

// Upcoming passes for tracked satellite
export const passes = writable([])

// Current position of tracked satellite - derived + refreshed every tick
export const trackedPosition = writable(null)

// Update trackedPosition whenever positions update
let _lastPositions = []
let _lastTracked = ''

satPositions.subscribe(positions => {
  _lastPositions = positions
  if (!_lastTracked) { trackedPosition.set(null); return }
  const pos = positions.find(p => p.name === _lastTracked) || null
  trackedPosition.set(pos)
})

trackedSat.subscribe(name => {
  _lastTracked = name
  if (!name) { trackedPosition.set(null); return }
  const pos = _lastPositions.find(p => p.name === name) || null
  trackedPosition.set(pos)
})

// Connection states
export const flexConnected = writable(false)
export const skycatConnected = writable(false)
export const dopplerEnabled = writable(true)

// Passes panel state — persisted in memory so tab switches don't reset filters
export const passesViewMode = writable('single')  // 'single' | 'all'
export const passesMinEl = writable(0)            // 0 | 10 | 30 | 60
export const passesAllCache = writable([])        // cached all-watchlist passes
export const rotorEnabled = writable(true)
export const soundEnabled = writable(true)  // AOS voice alerts

// Per-session tracking toggles (not persisted — reset on startup)
export const trackFreqMode = writable(false)  // Track frequency+mode for current sat
export const trackAzimuth = writable(false)   // Track azimuth for current sat

export const rotorConnected = writable(false)

// Default settings
const DEFAULT_SETTINGS = {
  qthLat: 48.7,
  qthLon: 2.55,
  qthAlt: 100,
  radioType: 'flex',           // 'flex' | 'skycat'
  flexHost: '192.168.1.100',
  flexPort: 4992,
  skycatHost: '127.0.0.1',
  skycatPort: 4532,
  skycatSatMode: 'Duplex',     // 'Duplex' | 'Split' | 'Simplex'
  autoConnectSkycat: false,
  rotorHost: '127.0.0.1',
  rotorPort: 12000,
  rotorAzOnly: true,
  downlinkHz: 145800000,
  uplinkHz: 145200000,
  minElFilter: 5,
  autoConnectFlex: false,
  autoConnectRotor: false,
  rxSlice: 0,
  txSlice: 1,
}

// Settings version — bump this to force reset of specific fields
const SETTINGS_VERSION = 4

// Load persisted settings from localStorage
function loadSettings() {
  try {
    const saved = localStorage.getItem('satmaster_settings')
    if (saved) {
      const parsed = JSON.parse(saved)
      // If version mismatch, force slice config reset to new defaults
      if (parsed._version !== SETTINGS_VERSION) {
        return {
          ...DEFAULT_SETTINGS,
          ...parsed,
          rxSlice: DEFAULT_SETTINGS.rxSlice,
          txSlice: DEFAULT_SETTINGS.txSlice,
          radioType: DEFAULT_SETTINGS.radioType,
          skycatHost: DEFAULT_SETTINGS.skycatHost,
          skycatPort: DEFAULT_SETTINGS.skycatPort,
          skycatSatMode: DEFAULT_SETTINGS.skycatSatMode,
          _version: SETTINGS_VERSION,
        }
      }
      return { ...DEFAULT_SETTINGS, ...parsed }
    }
  } catch(e) {}
  return { ...DEFAULT_SETTINGS, _version: SETTINGS_VERSION }
}

// Persist settings to localStorage on every change
function createPersistedSettings() {
  const store = writable(loadSettings())
  store.subscribe(val => {
    try {
      localStorage.setItem('satmaster_settings', JSON.stringify(val))
    } catch(e) {}
  })
  return store
}

export const settings = createPersistedSettings()

// Watchlist - satellites to display on map (persisted)
function createPersistedWatchlist() {
  const DEFAULT = ['ISS (ZARYA)','AO-7','AO-27','SO-50','RS-44','AO-91','FO-29']
  let initial = DEFAULT
  try {
    const saved = localStorage.getItem('satmaster_watchlist')
    if (saved) initial = JSON.parse(saved)
  } catch(e) {}
  const store = writable(initial)
  store.subscribe(val => {
    try { localStorage.setItem('satmaster_watchlist', JSON.stringify(val)) } catch(e) {}
  })
  return store
}
export const watchlist = createPersistedWatchlist()

// TLE info
export const tleAge = writable(null)
export const tleLoaded = writable(false)

// Doppler display values
export const dopplerInfo = writable({
  downShiftHz: 0,
  upShiftHz: 0,
  correctedDownHz: 0,
  correctedUpHz: 0,
})