import type { TrackRef, RadioResponse } from '$lib/api/types';
import { untrack } from 'svelte';
import { api } from '$lib/api/client';
import { user } from '$lib/auth/store.svelte';
import { readPersistedQueue, writePersistedQueue } from './persisted';

export type PlayerState = 'idle' | 'loading' | 'playing' | 'paused' | 'error';
export type RepeatMode = 'off' | 'all' | 'one';

const VOLUME_KEY = 'minstrel.volume';

export function readStoredVolume(): number {
  try {
    const raw = localStorage.getItem(VOLUME_KEY);
    if (raw == null) return 1;
    const n = Number(raw);
    if (Number.isFinite(n) && n >= 0 && n <= 1) return n;
    return 1;
  } catch {
    return 1;
  }
}

let _queue    = $state<TrackRef[]>([]);
let _index    = $state(0);
let _state    = $state<PlayerState>('idle');
let _position = $state(0);
let _duration = $state(0);
let _volume   = $state(readStoredVolume());
let _shuffle  = $state(false);
let _repeat   = $state<RepeatMode>('off');
let _error    = $state<string | null>(null);
let _queueDrawerOpen = $state(false);

// M4c: track when the queue was seeded by a radio call so we can
// auto-refresh at 80% consumption. Cleared when the user enqueues
// from a non-radio source.
let _radioSeedId          = $state<string | null>(null);
let _radioRefreshInFlight = false;

let _audioEl: HTMLAudioElement | null = null;

export const player = {
  get queue()     { return _queue; },
  get index()     { return _index; },
  get current()   { return _queue[_index] as TrackRef | undefined; },
  get state()     { return _state; },
  get isPlaying() { return _state === 'playing'; },
  get position()  { return _position; },
  get duration()  { return _duration; },
  get volume()    { return _volume; },
  get shuffle()   { return _shuffle; },
  get repeat()    { return _repeat; },
  get error()     { return _error; },
  get queueDrawerOpen()   { return _queueDrawerOpen; }
};

export function registerAudioEl(el: HTMLAudioElement | null): void {
  _audioEl = el;
}

export function playQueue(tracks: TrackRef[], startIndex = 0): void {
  _radioSeedId = null;  // M4c: non-radio enqueue clears the radio refresh state
  _queue = tracks;
  if (tracks.length === 0) {
    _index = 0;
    _state = 'idle';
  } else {
    _index = Math.max(0, Math.min(startIndex, tracks.length - 1));
    _state = 'loading';
  }
  _position = 0;
  _duration = 0;
  _error = null;
}

export function togglePlay(): void {
  if (_queue.length === 0) return;
  // "Intent to play" (loading + playing) → paused. Anything else → loading (user
  // wants to play; audio will catch up).
  if (_state === 'playing' || _state === 'loading') {
    _state = 'paused';
  } else {
    _state = 'loading';
  }
}

export function skipNext(): void {
  if (_queue.length === 0) return;
  if (_index + 1 < _queue.length) {
    _index++;
    _position = 0;
    _duration = 0;
    _state = 'loading';
    return;
  }
  // At end of queue.
  if (_repeat === 'all') {
    _index = 0;
    _position = 0;
    _duration = 0;
    _state = 'loading';
  } else {
    // 'off' or 'one' both pause at end on EXPLICIT skip.
    _state = 'paused';
    _position = _duration;
  }
}

export function skipPrev(): void {
  if (_queue.length === 0) return;
  if (_position < 3 && _index > 0) {
    _index--;
    _position = 0;
    _duration = 0;
    _state = 'loading';
  } else {
    // Seek to 0 of the current track.
    _position = 0;
    if (_audioEl) _audioEl.currentTime = 0;
  }
}

export function seekTo(sec: number): void {
  _position = sec;
  if (_audioEl) _audioEl.currentTime = sec;
}

export function setVolume(v: number): void {
  const clamped = Math.max(0, Math.min(1, v));
  _volume = clamped;
  try { localStorage.setItem(VOLUME_KEY, String(clamped)); } catch { /* ignore */ }
}

export function reportTimeUpdate(sec: number): void {
  _position = sec;
}

export function reportDuration(sec: number): void {
  _duration = Number.isFinite(sec) ? sec : 0;
}

// --- Shuffle (with injectable RNG for tests) ---

let _rng: () => number = Math.random;
export function __setShuffleRng(fn: () => number): void { _rng = fn; }

export function toggleShuffle(): void {
  _shuffle = !_shuffle;
  if (_shuffle && _index + 1 < _queue.length) {
    // Fisher-Yates shuffle over _queue[_index+1 .. end].
    const arr = _queue.slice();
    for (let j = arr.length - 1; j > _index; j--) {
      const r = Math.floor(_rng() * (j - _index)) + _index + 1;
      [arr[j], arr[r]] = [arr[r], arr[j]];
    }
    _queue = arr;
  }
}

// --- Repeat ---

export function cycleRepeat(): void {
  _repeat = _repeat === 'off' ? 'all' : _repeat === 'all' ? 'one' : 'off';
}

export function reportStateFromAudio(
  event: 'playing' | 'paused' | 'waiting' | 'ended' | 'error',
  detail?: string
): void {
  switch (event) {
    case 'playing':
      _state = 'playing';
      _error = null;
      return;
    case 'paused':
      _state = 'paused';
      return;
    case 'waiting':
      _state = 'loading';
      return;
    case 'error':
      _state = 'error';
      _error = detail ?? 'Playback failed.';
      return;
    case 'ended':
      if (_repeat === 'one') {
        _position = 0;
        _state = 'loading';
        if (_audioEl) _audioEl.currentTime = 0;
        return;
      }
      if (_index + 1 < _queue.length) {
        _index++;
        _position = 0;
        _duration = 0;
        _state = 'loading';
        return;
      }
      if (_repeat === 'all') {
        _index = 0;
        _position = 0;
        _duration = 0;
        _state = 'loading';
      } else {
        _state = 'paused';
        _position = _duration;
      }
      return;
  }
}

export function enqueueTrack(t: TrackRef): void {
  _radioSeedId = null;  // M4c
  _queue = [..._queue, t];
  if (_state === 'idle') _index = 0;
}

/**
 * M7 #372: insert a track immediately after the currently-playing one
 * so it plays next. If the queue is empty, behaves like enqueueTrack
 * and starts the queue with this track at index 0.
 */
export function playNext(t: TrackRef): void {
  _radioSeedId = null; // M4c: any user-driven enqueue clears the radio refresh state
  if (_queue.length === 0) {
    _queue = [t];
    _index = 0;
    return;
  }
  const next = _index + 1;
  _queue = [..._queue.slice(0, next), t, ..._queue.slice(next)];
}

export function enqueueTracks(ts: TrackRef[]): void {
  _radioSeedId = null;  // M4c
  if (ts.length === 0) return;
  _queue = [..._queue, ...ts];
  if (_state === 'idle') _index = 0;
}

export async function playRadio(seedTrackId: string): Promise<void> {
  const resp = await api.get<RadioResponse>(
    `/api/radio?seed_track=${encodeURIComponent(seedTrackId)}`
  );
  if (resp.tracks.length === 0) return;
  playQueue(resp.tracks, 0);
  _radioSeedId = seedTrackId;  // M4c: set AFTER playQueue (which clears it)
}

export function moveQueueItem(from: number, to: number): void {
  if (from === to) return;
  if (from < 0 || from >= _queue.length) return;
  if (to < 0 || to >= _queue.length) return;
  const playingId = _queue[_index]?.id;
  const next = _queue.slice();
  const [moved] = next.splice(from, 1);
  next.splice(to, 0, moved);
  _queue = next;
  if (playingId) {
    const found = next.findIndex((x) => x.id === playingId);
    if (found >= 0) _index = found;
  }
}

export function removeFromQueue(idx: number): void {
  if (idx < 0 || idx >= _queue.length) return;
  const next = _queue.slice();
  next.splice(idx, 1);
  if (idx < _index) {
    _queue = next;
    _index = _index - 1;
    return;
  }
  if (idx > _index) {
    _queue = next;
    return;
  }
  // idx === _index — removing the currently-playing track.
  _queue = next;
  if (next.length === 0) {
    _index = 0;
    _state = 'idle';
    _position = 0;
    _duration = 0;
    _error = null;
    return;
  }
  if (_index >= next.length) {
    // Removed the last track. Mirror skipNext end-of-queue behaviour:
    // pause on the now-last remaining track at position 0 — don't
    // auto-play a track the user already heard.
    _index = next.length - 1;
    _state = 'paused';
    _position = 0;
    _duration = 0;
    _error = null;
    return;
  }
  // _index stays — now points at what was the next track. Advance into it.
  _position = 0;
  _duration = 0;
  _state = 'loading';
  _error = null;
}

export function playFromQueueIndex(idx: number): void {
  if (idx < 0 || idx >= _queue.length) return;
  _radioSeedId = null;
  _index = idx;
  _position = 0;
  _duration = 0;
  _state = 'loading';
  _error = null;
}

export function toggleQueueDrawer(): void {
  _queueDrawerOpen = !_queueDrawerOpen;
}

export function closeQueueDrawer(): void {
  _queueDrawerOpen = false;
}

export function restoreQueue(userId: string): void {
  if (!userId) return;
  const persisted = readPersistedQueue(userId);
  if (!persisted) return;
  if (persisted.queue.length === 0) return;
  _queue = persisted.queue;
  _index = Math.max(0, Math.min(persisted.index, persisted.queue.length - 1));
  _position = persisted.position;
  _duration = 0;
  _state = 'paused';
  _error = null;
  _radioSeedId = null;
}

// M4c: auto-refresh radio queue when 80% consumed.
// Fires whenever the consumption ratio crosses 80% AND the queue was
// seeded by playRadio() AND no refresh is currently in-flight.
$effect.root(() => {
  $effect(() => {
    if (_radioSeedId === null) return;
    if (_radioRefreshInFlight) return;
    if (_queue.length === 0) return;
    const consumedRatio = (_index + 1) / _queue.length;
    if (consumedRatio < 0.8) return;

    _radioRefreshInFlight = true;
    const seed = _radioSeedId;
    const exclude = _queue.map((t) => t.id).join(',');
    api
      .get<RadioResponse>(
        `/api/radio?seed_track=${encodeURIComponent(seed)}&exclude=${exclude}`
      )
      .then((resp) => {
        // Strip the seed at index 0 (already in our queue) and any other
        // tracks that happen to match the original seed id.
        const newTracks = resp.tracks.slice(1).filter((t) => t.id !== seed);
        if (newTracks.length > 0) {
          // Append directly without calling enqueueTracks — that would
          // clear _radioSeedId and prevent further refreshes.
          _queue = [..._queue, ...newTracks];
        }
      })
      .catch(() => {
        // Swallow; next track-advance can retry.
      })
      .finally(() => {
        _radioRefreshInFlight = false;
      });
  });
});

// Persistence (M7 #364): split-effect shape. Queue/index changes write
// immediately (rare, user-driven); position changes throttle to once
// per 5s during steady playback. See spec section "Persistence write
// effect" for the alternative debounce shape.
$effect.root(() => {
  let lastPositionWriteAt = 0;

  // Immediate write on queue or index changes. Position is read via
  // untrack so this effect doesn't fire on every position tick — only
  // queue/index changes drive it. The throttled-write effect below
  // covers position drift.
  $effect(() => {
    const userId = user.value?.id;
    if (!userId) return;
    // Reading these registers the reactive dependency; the values
    // themselves are unused — writePersistedQueue re-reads live state.
    _queue;
    _index;
    writePersistedQueue(userId, {
      queue: _queue,
      index: _index,
      position: untrack(() => _position)
    });
    lastPositionWriteAt = Date.now();
  });

  // Throttled write on position changes.
  $effect(() => {
    const userId = user.value?.id;
    if (!userId) return;
    const _p = _position;
    void _p;
    const now = Date.now();
    if (now - lastPositionWriteAt < 5000) return;
    writePersistedQueue(userId, {
      queue: _queue,
      index: _index,
      position: _position
    });
    lastPositionWriteAt = now;
  });
});
