<script lang="ts">
  import { onMount } from 'svelte';
  import type { ClaudeSessionInfo } from './agent-store.svelte.ts';
  import { listProjectSessions, setPendingResume, getPendingResume, clearPendingResume, loadSessionHistory } from './agent-store.svelte.ts';
  import { t } from './i18n.svelte.ts';

  interface Props {
    projectId: string;
    provider: string;
    cwd: string;
    currentSessionId?: string;
    onNewSession?: (prompt: string) => void;
  }

  let {
    projectId,
    provider,
    cwd,
    currentSessionId,
    onNewSession,
  }: Props = $props();

  let open = $state(false);
  let sessions = $state<ClaudeSessionInfo[]>([]);
  let loading = $state(false);
  let containerEl: HTMLDivElement;

  onMount(() => {
    fetchSessions();
    // Close on outside click
    function handleClick(e: MouseEvent) {
      if (containerEl && !containerEl.contains(e.target as Node)) {
        open = false;
      }
    }
    document.addEventListener('mousedown', handleClick);
    return () => document.removeEventListener('mousedown', handleClick);
  });

  async function fetchSessions() {
    if (!cwd) return;
    loading = true;
    try {
      sessions = await listProjectSessions(projectId, cwd);
    } catch {
      sessions = [];
    }
    loading = false;
  }

  function toggle() {
    open = !open;
    if (open) fetchSessions();
  }

  function fmtDate(ms: number): string {
    const d = new Date(ms);
    const now = Date.now();
    const diffH = (now - ms) / 3_600_000;
    if (diffH < 1) return `${Math.max(1, Math.round(diffH * 60))}m ago`;
    if (diffH < 24) return `${Math.round(diffH)}h ago`;
    return d.toLocaleDateString(undefined, { month: 'short', day: 'numeric' });
  }

  function fmtSize(bytes: number): string {
    if (bytes < 1024) return `${bytes}B`;
    if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(0)}KB`;
    return `${(bytes / (1024 * 1024)).toFixed(1)}MB`;
  }

  function truncate(s: string, max: number): string {
    return s.length > max ? s.slice(0, max - 3) + '...' : s;
  }

  async function handleContinue() {
    open = false;
    setPendingResume(projectId, 'continue');
    // Load the most recent session's messages for display
    if (sessions.length > 0) {
      await loadSessionHistory(projectId, sessions[0].sessionId, cwd);
    }
  }

  async function handleResume(sdkSessionId: string) {
    open = false;
    setPendingResume(projectId, 'resume', sdkSessionId);
    // Load the selected session's messages for display
    await loadSessionHistory(projectId, sdkSessionId, cwd);
  }

  function handleNew() {
    open = false;
    clearPendingResume(projectId);
    // Don't start agent — just clear any pending resume so next Send creates fresh session
    // The user types their prompt, then hits Send
  }
</script>

<div class="session-picker" bind:this={containerEl}>
  <button
    class="picker-trigger"
    onclick={toggle}
    title="Session history"
    aria-label="Session history"
    aria-expanded={open}
  >
    <svg viewBox="0 0 16 16" fill="currentColor" aria-hidden="true">
      <path d="M8 3.5a.5.5 0 0 0-1 0V8a.5.5 0 0 0 .252.434l3.5 2a.5.5 0 0 0 .496-.868L8 7.71V3.5z"/>
      <path d="M8 16A8 8 0 1 0 8 0a8 8 0 0 0 0 16zm7-8A7 7 0 1 1 1 8a7 7 0 0 1 14 0z"/>
    </svg>
  </button>

  <div class="picker-dropdown" style:display={open ? 'flex' : 'none'}>
    <div class="dropdown-header">
      <span class="dropdown-title">Sessions</span>
      <button class="new-btn" onclick={handleNew}>
        + New
      </button>
    </div>

    {#if sessions.length > 0}
      <button class="continue-btn" onclick={handleContinue}>
        <svg viewBox="0 0 16 16" fill="currentColor" aria-hidden="true" class="continue-icon">
          <path d="M4 2l8 6-8 6V2z"/>
        </svg>
        Continue last session
      </button>
    {/if}

    <div class="dropdown-divider"></div>

    <div class="session-list">
      {#if loading}
        <div class="session-empty">Loading...</div>
      {:else if sessions.length === 0}
        <div class="session-empty">No previous sessions</div>
      {:else}
        {#each sessions as s (s.sessionId)}
          <button
            class="session-row"
            class:active={currentSessionId === s.sessionId}
            onclick={() => handleResume(s.sessionId)}
          >
            <div class="session-prompt">{truncate(s.firstPrompt || s.summary, 60)}</div>
            <div class="session-meta">
              <span class="meta-date">{fmtDate(s.lastModified)}</span>
              <span class="meta-sep" aria-hidden="true"></span>
              <span class="meta-size">{fmtSize(s.fileSize)}</span>
              <span class="meta-sep" aria-hidden="true"></span>
              <span class="meta-model">{s.model}</span>
            </div>
          </button>
        {/each}
      {/if}
    </div>
  </div>
</div>

<style>
  .session-picker {
    position: relative;
    display: flex;
    align-items: center;
  }

  .picker-trigger {
    display: flex;
    align-items: center;
    justify-content: center;
    width: 1.25rem;
    height: 1.25rem;
    padding: 0;
    background: transparent;
    border: 1px solid var(--ctp-surface1);
    border-radius: 0.2rem;
    color: var(--ctp-overlay1);
    cursor: pointer;
    transition: color 0.12s, border-color 0.12s;
  }

  .picker-trigger:hover {
    color: var(--ctp-text);
    border-color: var(--ctp-blue);
  }

  .picker-trigger svg {
    width: 10px;
    height: 10px;
  }

  .picker-dropdown {
    position: absolute;
    top: calc(100% + 0.25rem);
    right: 0;
    z-index: 100;
    flex-direction: column;
    width: 18rem;
    max-height: 20rem;
    background: var(--ctp-mantle);
    border: 1px solid var(--ctp-surface1);
    border-radius: 0.375rem;
    box-shadow: 0 4px 12px color-mix(in srgb, var(--ctp-crust) 60%, transparent);
    overflow: hidden;
  }

  .dropdown-header {
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 0.375rem 0.5rem;
    border-bottom: 1px solid var(--ctp-surface0);
  }

  .dropdown-title {
    font-size: 0.6875rem;
    font-weight: 600;
    color: var(--ctp-subtext1);
    text-transform: uppercase;
    letter-spacing: 0.04em;
  }

  .new-btn {
    font-size: 0.6875rem;
    font-weight: 500;
    color: var(--ctp-blue);
    background: transparent;
    border: none;
    cursor: pointer;
    padding: 0.125rem 0.375rem;
    border-radius: 0.2rem;
    transition: background 0.12s;
  }

  .new-btn:hover {
    background: color-mix(in srgb, var(--ctp-blue) 12%, transparent);
  }

  .continue-btn {
    display: flex;
    align-items: center;
    gap: 0.375rem;
    width: 100%;
    padding: 0.375rem 0.5rem;
    background: transparent;
    border: none;
    color: var(--ctp-green);
    font-size: 0.75rem;
    font-weight: 500;
    cursor: pointer;
    text-align: left;
    transition: background 0.12s;
  }

  .continue-btn:hover {
    background: color-mix(in srgb, var(--ctp-green) 10%, transparent);
  }

  .continue-icon {
    width: 10px;
    height: 10px;
    flex-shrink: 0;
  }

  .dropdown-divider {
    height: 1px;
    background: var(--ctp-surface0);
    flex-shrink: 0;
  }

  .session-list {
    overflow-y: auto;
    flex: 1;
    min-height: 0;
  }

  .session-list::-webkit-scrollbar {
    width: 0.25rem;
  }
  .session-list::-webkit-scrollbar-track {
    background: transparent;
  }
  .session-list::-webkit-scrollbar-thumb {
    background: var(--ctp-surface1);
    border-radius: 0.25rem;
  }

  .session-empty {
    padding: 1rem 0.5rem;
    text-align: center;
    font-size: 0.75rem;
    color: var(--ctp-overlay0);
  }

  .session-row {
    display: flex;
    flex-direction: column;
    gap: 0.125rem;
    width: 100%;
    padding: 0.375rem 0.5rem;
    background: transparent;
    border: none;
    cursor: pointer;
    text-align: left;
    transition: background 0.12s;
  }

  .session-row:hover {
    background: var(--ctp-surface0);
  }

  .session-row.active {
    background: color-mix(in srgb, var(--ctp-blue) 12%, transparent);
  }

  .session-prompt {
    font-size: 0.75rem;
    color: var(--ctp-text);
    line-height: 1.3;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
  }

  .session-meta {
    display: flex;
    align-items: center;
    gap: 0.25rem;
    font-size: 0.625rem;
    color: var(--ctp-overlay1);
  }

  .meta-sep {
    width: 1px;
    height: 0.5rem;
    background: var(--ctp-surface1);
  }

  .meta-model {
    color: var(--ctp-overlay0);
  }
</style>
