<script>
  import { onDestroy } from "svelte";
  import { invoke } from "@tauri-apps/api/core";
  import { history, saveHistory, deleteFromHistory } from "$lib/stores/page.svelte.js";
  import { convertFileSrc } from "@tauri-apps/api/core";
  import Card from "$lib/components/Card.svelte";
  import { formatTime, formatDuration } from "$lib/utils/time.js";
  import { PLAYBACK_SPEEDS, FEEDBACK_TIMEOUT_MS } from "$lib/utils/constants.js";

  let searchQuery = $state("");
  let selectedItem = $state(null);
  let playingId = $state(null);
  let audioEl = $state(null);
  let currentTime = $state(0);
  let duration = $state(0);
  let playbackRate = $state(1);
  let animFrameId = null;

  onDestroy(() => {
    stopPlayback();
  });

  let filtered = $derived(
    searchQuery
      ? history.filter((h) => {
          const q = searchQuery.toLowerCase();
          return (
            (h.text && h.text.toLowerCase().includes(q)) ||
            (h.preview && h.preview.toLowerCase().includes(q)) ||
            (h.source && h.source.toLowerCase().includes(q)) ||
            (h.title && h.title.toLowerCase().includes(q))
          );
        })
      : history
  );

  function clearAll() {
    history.splice(0);
    saveHistory();
    selectedItem = null;
    stopPlayback();
  }

  function openItem(item) {
    selectedItem = selectedItem === item ? null : item;
  }

  function copyItem(item) {
    navigator.clipboard.writeText(item.text).catch(() => {});
  }

  function removeItem(item) {
    const idx = history.indexOf(item);
    if (idx !== -1) {
      deleteFromHistory(idx);
      if (selectedItem === item) selectedItem = null;
      if (playingId === item.id) stopPlayback();
    }
  }

  function renameItem(item) {
    const name = prompt("Name this transcript:", item.title || "");
    if (name !== null) {
      item.title = name.trim();
      item.preview = name.trim() ? `${name.trim()} — ${item.text.slice(0, 80)}` : item.text.slice(0, 120);
      saveHistory();
    }
  }

  function togglePlay(item) {
    if (playingId === item.id) {
      if (audioEl && !audioEl.paused) {
        audioEl.pause();
        cancelAnimationFrame(animFrameId);
      } else if (audioEl) {
        audioEl.play();
        tickTime();
      }
      return;
    }
    stopPlayback();
    try {
      const src = convertFileSrc(item.audioPath);
      const audio = new Audio(src);
      audio.playbackRate = playbackRate;
      audio.onloadedmetadata = () => { duration = audio.duration; };
      audio.onended = () => { stopPlayback(); };
      audio.onerror = () => { stopPlayback(); };
      audio.play();
      audioEl = audio;
      playingId = item.id;
      tickTime();
    } catch {
      stopPlayback();
    }
  }

  function stopPlayback() {
    if (audioEl) { audioEl.pause(); audioEl.src = ""; audioEl = null; }
    playingId = null;
    currentTime = 0;
    duration = 0;
    cancelAnimationFrame(animFrameId);
  }

  function tickTime() {
    if (audioEl) {
      currentTime = audioEl.currentTime;
      if (!audioEl.paused) {
        animFrameId = requestAnimationFrame(tickTime);
      }
    }
  }

  function seekTo(e) {
    const val = parseFloat(e.target.value);
    if (audioEl) {
      audioEl.currentTime = val;
      currentTime = val;
    }
  }

  function setSpeed(speed) {
    playbackRate = speed;
    if (audioEl) audioEl.playbackRate = speed;
  }


  async function openViewer(item) {
    // Store item data for the viewer window
    try {
      localStorage.setItem("ramble_viewer_item", JSON.stringify(item));
      await invoke("open_viewer_window");
    } catch {
      // Fallback: open in browser tab (dev mode)
      localStorage.setItem("ramble_viewer_item", JSON.stringify(item));
      window.open("/viewer", "_blank", "width=600,height=700");
    }
  }
</script>

<div class="flex flex-col h-full overflow-y-auto animate-fade-in">
  <!-- Header -->
  <div class="flex items-center gap-4 px-7 pt-6 pb-4">
    <h2 class="font-display text-[24px] italic text-text">History</h2>
    <span class="text-[11px] text-text-tertiary mt-1">{history.length} saved</span>
    <div class="flex-1"></div>
    {#if history.length > 0}
      <button
        class="px-3 py-1.5 rounded-lg text-[12px] text-text-tertiary hover:text-danger hover:bg-hover"
        onclick={clearAll}
      >
        Clear All
      </button>
    {/if}
  </div>

  <!-- Search -->
  <div class="px-7 pb-4">
    <Card>
      <div class="flex items-center gap-3 px-4 py-2.5">
        <svg class="w-4 h-4 text-text-tertiary flex-shrink-0" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
          <circle cx="11" cy="11" r="8" /><path d="M21 21l-4.35-4.35" />
        </svg>
        <input
          class="flex-1 bg-transparent text-text text-[13px] placeholder:text-text-tertiary focus:outline-none"
          placeholder="Search all transcripts..."
          bind:value={searchQuery}
          data-no-transition
        />
        {#if searchQuery}
          <span class="text-[11px] text-text-tertiary mr-2">{filtered.length} results</span>
          <button
            class="text-[11px] text-text-tertiary hover:text-text"
            onclick={() => searchQuery = ""}
          >Clear</button>
        {/if}
      </div>
    </Card>
  </div>

  <!-- History list -->
  <div class="flex-1 px-7 pb-4 min-h-0">
    <Card classes="h-full flex flex-col">
      {#if filtered.length === 0}
        <div class="flex-1 flex flex-col items-center justify-center gap-3">
          <div class="w-12 h-12 rounded-full bg-bg-elevated flex items-center justify-center">
            <svg class="w-6 h-6 text-text-tertiary" viewBox="0 0 24 24" fill="currentColor">
              <path d="M12 2a10 10 0 1 0 0 20 10 10 0 0 0 0-20Zm0 18a8 8 0 1 1 0-16 8 8 0 0 1 0 16Zm.5-13H11v6l5.25 3.15.75-1.23-4.5-2.67V7Z" />
            </svg>
          </div>
          <p class="text-[13px] text-text-tertiary">
            {searchQuery ? "No matching transcripts" : "No history yet"}
          </p>
          <p class="text-[11px] text-text-tertiary">
            {searchQuery ? "Try a different search" : "Transcripts auto-save after recording"}
          </p>
        </div>
      {:else}
        <div class="flex-1 overflow-y-auto p-3 space-y-1">
          {#each filtered as item}
            <div
              class="w-full text-left p-3 rounded-xl hover:bg-hover cursor-pointer group"
              onclick={() => openItem(item)}
              onkeydown={(e) => { if (e.key === "Enter") openItem(item); }}
              role="button"
              tabindex="0"
            >
              <div class="flex items-center gap-2 mb-1">
                <!-- Play button -->
                {#if item.audioPath}
                  <button
                    class="w-7 h-7 rounded-full flex items-center justify-center flex-shrink-0
                      {playingId === item.id ? 'bg-accent/20 text-accent' : 'bg-accent/10 text-accent hover:bg-accent/20'}"
                    onclick={(e) => { e.stopPropagation(); togglePlay(item); }}
                    aria-label={playingId === item.id && audioEl && !audioEl.paused ? "Pause" : "Play"}
                  >
                    {#if playingId === item.id && audioEl && !audioEl.paused}
                      <svg class="w-3 h-3" viewBox="0 0 24 24" fill="currentColor">
                        <rect x="6" y="4" width="4" height="16" rx="1" />
                        <rect x="14" y="4" width="4" height="16" rx="1" />
                      </svg>
                    {:else}
                      <svg class="w-3 h-3 ml-0.5" viewBox="0 0 24 24" fill="currentColor">
                        <path d="M8 5v14l11-7z" />
                      </svg>
                    {/if}
                  </button>
                {/if}
                {#if item.title}
                  <span class="text-[12px] text-text font-medium">{item.title}</span>
                  <span class="text-[11px] text-text-tertiary">·</span>
                {/if}
                <span class="text-[11px] text-text-tertiary">{item.date}</span>
                <span class="text-[11px] text-text-tertiary">·</span>
                <span class="text-[11px] text-text-tertiary">{item.source}</span>
                {#if item.duration}
                  <span class="text-[11px] text-text-tertiary">· {formatDuration(item.duration)}</span>
                {/if}
                <div class="flex-1"></div>
                <!-- Viewer button -->
                {#if item.audioPath && item.segments && item.segments.length > 0}
                  <button
                    class="text-[11px] text-accent opacity-0 group-hover:opacity-100 hover:text-accent-hover"
                    onclick={(e) => { e.stopPropagation(); openViewer(item); }}
                  >Open viewer</button>
                {/if}
                <button
                  class="text-[11px] text-text-tertiary opacity-0 group-hover:opacity-100 hover:text-accent"
                  onclick={(e) => { e.stopPropagation(); renameItem(item); }}
                >Rename</button>
                <button
                  class="text-[11px] text-text-tertiary opacity-0 group-hover:opacity-100 hover:text-accent"
                  onclick={(e) => { e.stopPropagation(); copyItem(item); }}
                >Copy</button>
                <button
                  class="text-[11px] text-text-tertiary opacity-0 group-hover:opacity-100 hover:text-danger"
                  onclick={(e) => { e.stopPropagation(); removeItem(item); }}
                >Delete</button>
              </div>
              <p class="text-[13px] text-text-secondary line-clamp-2 leading-relaxed">
                {item.title ? item.text.slice(0, 120) : item.preview}
              </p>

              {#if selectedItem === item}
                <div class="mt-3 pt-3 border-t border-border-subtle animate-slide-up">
                  <!-- Media player (if audio exists) -->
                  {#if item.audioPath && playingId === item.id}
                    <div class="flex items-center gap-3 mb-3 px-1">
                      <!-- Time -->
                      <span class="text-[10px] text-text-tertiary tabular-nums w-[80px]">
                        {formatTime(currentTime)} / {formatTime(duration)}
                      </span>
                      <!-- Seek bar -->
                      <input
                        type="range"
                        min="0"
                        max={duration || 0}
                        step="0.1"
                        value={currentTime}
                        oninput={seekTo}
                        class="flex-1 accent-accent h-1"
                        data-no-transition
                        onclick={(e) => e.stopPropagation()}
                      />
                      <!-- Speed pills -->
                      <div class="flex gap-0.5">
                        {#each PLAYBACK_SPEEDS as speed}
                          <button
                            class="text-[9px] px-1.5 py-0.5 rounded-full
                              {playbackRate === speed
                                ? 'bg-accent/15 text-accent font-medium'
                                : 'text-text-tertiary hover:text-text-secondary'}"
                            onclick={(e) => { e.stopPropagation(); setSpeed(speed); }}
                          >{speed}x</button>
                        {/each}
                      </div>
                    </div>
                  {/if}
                  <p class="text-[13px] text-text leading-relaxed whitespace-pre-wrap">{item.text}</p>
                </div>
              {/if}
            </div>
          {/each}
        </div>
      {/if}
    </Card>
  </div>
</div>
