<script lang="ts">
  import { playback } from '$lib/stores/playback';
  import { audioPlayer } from '$lib/services/audioPlayer';
  import LyricsDisplay from '$lib/components/LyricsDisplay.svelte';
  import TriangleVolumeSlider from '$lib/components/TriangleVolumeSlider.svelte';

  function handlePlayPause() {
    playback.togglePlayPause();
  }

  function handlePrevious() {
    playback.previous();
  }

  function handleNext() {
    playback.next();
  }

  function handleProgressChange(e: Event) {
    const target = e.target as HTMLInputElement;
    const time = parseFloat(target.value);
    audioPlayer.seek(time);
    playback.setCurrentTime(time);
  }

  function handleVolumeChange(volume: number) {
    playback.setVolume(volume);
  }

  function formatTime(seconds: number): string {
    if (!isFinite(seconds)) return '0:00';
    const mins = Math.floor(seconds / 60);
    const secs = Math.floor(seconds % 60);
    return `${mins}:${secs.toString().padStart(2, '0')}`;
  }

  const hasTrack = $derived($playback.currentTrack !== null);
  const progressPercent = $derived(
    $playback.duration > 0 ? ($playback.currentTime / $playback.duration) * 100 : 0
  );
</script>

<div class="now-playing">
  <div class="player-main">
    <div class="track-info">
      <div class="track-title-row">
        <img src="/icons/play.svg" alt="" class="track-icon" />
        <div class="track-text-content">
          <div class="track-title">
            {#if hasTrack && $playback.currentTrack}
              {$playback.currentTrack.metadata.title || $playback.currentTrack.filename}
            {:else}
              No track playing
            {/if}
          </div>
          <div class="track-artist">
            {#if hasTrack && $playback.currentTrack}
              {$playback.currentTrack.metadata.artist || 'Unknown Artist'}
            {/if}
          </div>
        </div>
      </div>
    </div>

    <div class="player-controls-container">
      <div class="progress-section">
        <span class="time-display">{formatTime($playback.currentTime)}</span>
        <div class="progress-bar-container">
          <div class="progress-indicator">
            <span class="progress-indicator-bar" style="width: {progressPercent}%;"></span>
          </div>
          <input
            type="range"
            min="0"
            max={$playback.duration || 0}
            step="0.1"
            value={$playback.currentTime}
            oninput={handleProgressChange}
            disabled={!hasTrack}
            class="progress-slider"
          />
        </div>
        <span class="time-display">{formatTime($playback.duration)}</span>
      </div>

      <div class="controls-row">
        <div class="controls">
          <button
            class="control-button"
            onclick={handlePrevious}
            disabled={!hasTrack}
            title="Previous"
          >
            <img src="/icons/player-skip-back.svg" alt="Previous" />
          </button>

          <button
            class="control-button play-pause"
            onclick={handlePlayPause}
            disabled={!hasTrack}
            title={$playback.isPlaying ? 'Pause' : 'Play'}
          >
            {#if $playback.isPlaying}
              <img src="/icons/player-pause.svg" alt="Pause" />
            {:else}
              <img src="/icons/player-play.svg" alt="Play" />
            {/if}
          </button>

          <button
            class="control-button"
            onclick={() => playback.stop()}
            disabled={!hasTrack}
            title="Stop"
          >
            <img src="/icons/player-stop.svg" alt="Stop" />
          </button>

          <button
            class="control-button"
            onclick={handleNext}
            disabled={!hasTrack}
            title="Next"
          >
            <img src="/icons/player-skip-forward.svg" alt="Next" />
          </button>
        </div>

        <div class="volume-section">
          <TriangleVolumeSlider bind:value={$playback.volume} onchange={handleVolumeChange} />
        </div>
      </div>
    </div>
  </div>

  <LyricsDisplay lrcPath={$playback.lrcPath} currentTime={$playback.currentTime} />
</div>

<style>
  .now-playing {
    display: flex;
    flex-direction: row;
    justify-content: center;
    gap: 12px;
    padding: 8px;
    height: 100%;
    font-family: "Pixelated MS Sans Serif", Arial;
    font-size: 11px;
  }

  .player-main {
    display: flex;
    flex-direction: column;
    gap: 8px;
  }

  .controls-row {
    display: flex;
    align-items: center;
    justify-content: space-between;
    gap: 12px;
  }

  .controls {
    display: flex;
    flex-shrink: 0;
  }

  .control-button {
    padding: 6px 20px;
    min-width: auto;
    min-height: auto;
    display: flex;
    align-items: center;
    justify-content: center;
    border-radius: 0;
    margin: 0 -1px 0 0;
  }

  .control-button:first-child {
    margin-left: 0;
  }

  .control-button img {
    width: 12px;
    height: 12px;
    filter: light-dark(none, invert(1));
  }

  .play-pause {
    padding: 6px 20px;
  }

  .play-pause img {
    width: 12px;
    height: 12px;
  }

  .track-info {
    min-width: 0;
    overflow: hidden;
  }

  .track-title-row {
    display: flex;
    gap: 6px;
    min-width: 0;
  }

  .track-icon {
    width: 16px;
    height: 16px;
    filter: light-dark(none, invert(1));
    flex-shrink: 0;
  }

  .track-text-content {
    flex: 1;
    min-width: 0;
    display: flex;
    flex-direction: column;
    gap: 2px;
  }

  .track-title {
    font-weight: bold;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
    display: flex;
    align-items: center;
    min-height: 16px;
  }

  .track-artist {
    opacity: 0.7;
    font-size: 10px;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
  }

  .player-controls-container {
    display: flex;
    flex-direction: column;
    gap: 8px;
    max-width: 400px;
    width: 100%;
  }

  .progress-section {
    display: flex;
    align-items: center;
    gap: 8px;
    min-width: 0;
  }

  .time-display {
    font-family: monospace;
    font-size: 10px;
    min-width: 40px;
    text-align: center;
  }

  .progress-bar-container {
    position: relative;
    flex: 1;
    height: 20px;
    display: flex;
    align-items: center;
  }

  .progress-indicator {
    position: absolute;
    width: 100%;
    height: 12px;
    pointer-events: none;
  }

  .progress-slider {
    position: absolute;
    width: 100%;
    opacity: 0;
    cursor: pointer;
    height: 100%;
  }

  .progress-slider:disabled {
    cursor: not-allowed;
  }

  .volume-section {
    flex-shrink: 0;
  }

  /* Responsive: hide lyrics panel when not enough space */
  @media (max-width: 800px) {
    .now-playing :global(.lyrics-display) {
      display: none;
    }

    .player-main {
      width: 100%;
      max-width: 600px;
    }

    .player-controls-container {
      max-width: none;
    }
  }

  /* Responsive: simplify track info on very small widths */
  @media (max-width: 600px) {
    .track-artist {
      display: none;
    }
  }
</style>
