<script lang="ts">
  // PostCaptureCard — v0.1 UI-hardening deliverable (section 3: "Post-capture card").
  //
  // Display-only surface surfaced after every recording. Shows the cleaned
  // transcript, optionally the raw transcript behind a <details> disclosure,
  // extracted tasks (each clickable to reveal MicroSteps), and action
  // buttons for export / start-first-MicroStep / open-in-history.
  //
  // Intentionally scope-limited to what v0.1 ships:
  //   ✓  cleaned + raw transcript
  //   ✓  extracted tasks list
  //   ✓  MicroSteps for the selected task
  //   ✗  suggested title / type / folder / project / area / person / topic
  //   ✗  accept / edit / park / archive
  //   ✗  confidence scores
  //   ✗  related-notes / possible-links
  // All of the above are explicitly v0.2+.
  //
  // All data arrives via props — no store imports, no fetching, no mutations.

  import StatusPill from '$lib/components/StatusPill.svelte';

  type Props = {
    transcriptId: string;
    rawTranscript: string;
    cleanedTranscript: string;
    cleanedSource: 'llm' | 'rule-based';
    extractedTasks: string[];
    microSteps?: string[];
    onSelectTask?: (idx: number) => void;
    onExport?: () => void;
    onStartFirstMicroStep?: () => void;
    onOpenInHistory?: () => void;
  };

  let {
    transcriptId,
    rawTranscript,
    cleanedTranscript,
    cleanedSource,
    extractedTasks,
    microSteps,
    onSelectTask,
    onExport,
    onStartFirstMicroStep,
    onOpenInHistory,
  }: Props = $props();

  // Which task the user has selected (null = none). Drives MicroSteps reveal.
  let selectedTaskIdx: number | null = $state(null);

  // Bound elements for roving-tabindex keyboard navigation.
  let taskBtnEls: (HTMLButtonElement | null)[] = $state([]);

  function handleTaskClick(idx: number) {
    selectedTaskIdx = idx;
    onSelectTask?.(idx);
  }

  // Keyboard navigation on the task list (roving tabindex pattern).
  function handleTaskListKeydown(e: KeyboardEvent) {
    if (extractedTasks.length === 0) return;
    const current = selectedTaskIdx ?? 0;

    if (e.key === "ArrowDown") {
      e.preventDefault();
      const next = Math.min(current + 1, extractedTasks.length - 1);
      selectedTaskIdx = next;
      taskBtnEls[next]?.focus();
    } else if (e.key === "ArrowUp") {
      e.preventDefault();
      const prev = Math.max(current - 1, 0);
      selectedTaskIdx = prev;
      taskBtnEls[prev]?.focus();
    } else if (e.key === "Enter") {
      e.preventDefault();
      handleTaskClick(current);
      if (canStartMicroStep) {
        onStartFirstMicroStep?.();
      }
    }
  }

  // Keep focused button in sync when selectedTaskIdx changes via click.
  $effect(() => {
    if (selectedTaskIdx !== null) {
      taskBtnEls[selectedTaskIdx]?.focus();
    }
  });

  let hasMicroSteps = $derived(
    selectedTaskIdx !== null && microSteps !== undefined && microSteps.length > 0
  );

  let canStartMicroStep = $derived(
    microSteps !== undefined && microSteps.length > 0
  );
</script>

<article class="post-capture-card" aria-label="Captured transcript">
  <!-- Header: title + saved pill -->
  <header class="card-header">
    <span class="card-title">Captured</span>
    <StatusPill status="saved" />
  </header>

  <!-- Cleaned transcript — primary surface -->
  <section class="card-section cleaned-section">
    <p class="section-meta">
      {cleanedSource === 'llm' ? 'Cleaned by local model' : 'Cleaned by rules'}
    </p>
    <p class="transcript-text">{cleanedTranscript}</p>
  </section>

  <!-- Raw transcript — progressive disclosure -->
  <details class="raw-disclosure">
    <summary class="raw-summary">Show raw transcript</summary>
    <p class="transcript-text raw-text">{rawTranscript}</p>
  </details>

  <!-- Extracted tasks — only shown when there is at least one -->
  {#if extractedTasks.length > 0}
    <section class="card-section tasks-section">
      <h3 class="section-heading">Tasks</h3>
      <!-- Roving tabindex: first item in tab order; arrow keys move focus within the list. -->
      <!-- svelte-ignore a11y_interactive_supports_focus -->
      <ul
        class="task-list"
        role="listbox"
        aria-label="Extracted tasks"
        onkeydown={handleTaskListKeydown}
      >
        {#each extractedTasks as task, idx}
          <li class="task-item" role="option" aria-selected={selectedTaskIdx === idx}>
            <button
              class="task-btn"
              class:task-btn-selected={selectedTaskIdx === idx}
              onclick={() => handleTaskClick(idx)}
              type="button"
              tabindex={idx === 0 || selectedTaskIdx === idx ? 0 : -1}
              bind:this={taskBtnEls[idx]}
            >
              {task}
            </button>
          </li>
        {/each}
      </ul>
    </section>
  {/if}

  <!-- MicroSteps for selected task — only shown once a task is selected -->
  {#if hasMicroSteps}
    <section class="card-section microsteps-section">
      <h3 class="section-heading">MicroSteps</h3>
      <ol class="microstep-list">
        {#each microSteps! as step}
          <li class="microstep-item">{step}</li>
        {/each}
      </ol>
    </section>
  {/if}

  <!-- Action buttons -->
  <footer class="card-footer">
    <button class="action-btn" onclick={onExport} type="button">
      Export…
    </button>
    <button
      class="action-btn action-btn-primary"
      onclick={onStartFirstMicroStep}
      disabled={!canStartMicroStep}
      type="button"
    >
      Start first MicroStep
    </button>
    <button class="action-btn" onclick={onOpenInHistory} type="button">
      Open in History
    </button>
  </footer>
</article>

<style>
  /* === Card shell === */
  /* Mirrors bg-card · 1px subtle border · radius 20 · shadow-sm from
     components-cards.html and Card.svelte (rounded-2xl, border-border-subtle). */
  .post-capture-card {
    background: var(--color-bg-card);
    border: 1px solid var(--color-border-subtle);
    border-radius: 20px;
    box-shadow: 0 1px 3px rgba(0, 0, 0, 0.2);
    padding: 18px 20px;
    display: flex;
    flex-direction: column;
    gap: 14px;
    max-width: 520px;
    width: 100%;
  }

  /* === Header === */
  .card-header {
    display: flex;
    align-items: center;
    gap: 10px;
  }

  .card-title {
    font: 600 15px/1 var(--font-family-body);
    color: var(--color-text);
  }

  /* === Sections === */
  .card-section {
    display: flex;
    flex-direction: column;
    gap: 6px;
  }

  .section-meta {
    font-size: 11px;
    color: var(--color-text-tertiary);
    font-weight: 500;
    letter-spacing: 0.04em;
  }

  .section-heading {
    font: 600 12px/1 var(--font-family-body);
    color: var(--color-text-secondary);
    text-transform: uppercase;
    letter-spacing: 0.08em;
    margin: 0;
  }

  /* === Transcript text (shared by cleaned + raw) === */
  .transcript-text {
    font-size: 13px;
    color: var(--color-text-secondary);
    line-height: 1.55;
    margin: 0;
  }

  /* === Raw disclosure === */
  .raw-disclosure {
    border-top: 1px solid var(--color-border-subtle);
    padding-top: 10px;
  }

  .raw-summary {
    font-size: 12px;
    color: var(--color-text-tertiary);
    cursor: pointer;
    user-select: none;
    list-style: none;
    /* Remove default triangle — matches SettingsGroup pattern */
    padding: 0;
    border-radius: 4px;
  }

  .raw-summary::-webkit-details-marker {
    display: none;
  }

  .raw-summary:hover {
    color: var(--color-text-secondary);
  }

  .raw-summary:focus-visible {
    outline: 2px solid var(--color-accent);
    outline-offset: 2px;
  }

  .raw-text {
    margin-top: 8px;
    color: var(--color-text-tertiary);
    font-size: 12px;
  }

  /* === Task list === */
  .task-list {
    list-style: none;
    margin: 0;
    padding: 0;
    display: flex;
    flex-direction: column;
    gap: 4px;
  }

  .task-item {
    display: flex;
  }

  .task-btn {
    background: var(--color-bg-elevated);
    border: 1px solid var(--color-border-subtle);
    border-radius: 8px;
    padding: 6px 10px;
    font-size: 13px;
    color: var(--color-text-secondary);
    cursor: pointer;
    text-align: left;
    width: 100%;
    transition: background 100ms, border-color 100ms, color 100ms;
    line-height: 1.45;
  }

  .task-btn:hover {
    background: var(--color-hover);
    color: var(--color-text);
    border-color: var(--color-border);
  }

  .task-btn:focus-visible {
    outline: 2px solid var(--color-accent);
    outline-offset: 2px;
  }

  .task-btn-selected {
    background: color-mix(in oklch, var(--color-accent) 12%, var(--color-bg-elevated));
    border-color: color-mix(in oklch, var(--color-accent) 40%, var(--color-border-subtle));
    color: var(--color-text);
  }

  /* === MicroSteps === */
  .microstep-list {
    margin: 0;
    padding: 0 0 0 1.25em;
    display: flex;
    flex-direction: column;
    gap: 4px;
  }

  .microstep-item {
    font-size: 13px;
    color: var(--color-text-secondary);
    line-height: 1.5;
    padding-left: 4px;
  }

  /* === Footer actions === */
  .card-footer {
    display: flex;
    flex-wrap: wrap;
    gap: 8px;
    padding-top: 4px;
    border-top: 1px solid var(--color-border-subtle);
  }

  .action-btn {
    background: var(--color-bg-elevated);
    border: 1px solid var(--color-border-subtle);
    border-radius: 8px;
    padding: 6px 14px;
    font: 500 12px/1 var(--font-family-body);
    color: var(--color-text-secondary);
    cursor: pointer;
    transition: background 100ms, border-color 100ms, color 100ms;
    white-space: nowrap;
  }

  .action-btn:hover:not(:disabled) {
    background: var(--color-hover);
    color: var(--color-text);
    border-color: var(--color-border);
  }

  .action-btn:focus-visible {
    outline: 2px solid var(--color-accent);
    outline-offset: 2px;
  }

  .action-btn:disabled {
    opacity: 0.38;
    cursor: not-allowed;
  }

  /* Primary action gets brand accent treatment */
  .action-btn-primary {
    background: color-mix(in oklch, var(--color-accent) 14%, var(--color-bg-elevated));
    border-color: color-mix(in oklch, var(--color-accent) 35%, var(--color-border-subtle));
    color: var(--color-accent);
  }

  .action-btn-primary:hover:not(:disabled) {
    background: color-mix(in oklch, var(--color-accent) 20%, var(--color-bg-elevated));
    color: var(--color-text);
  }

  /* Honour prefers-reduced-motion for transitions */
  @media (prefers-reduced-motion: reduce) {
    .task-btn,
    .action-btn {
      transition: none;
    }
  }

  :global(html.reduce-motion) .task-btn,
  :global(html.reduce-motion) .action-btn {
    transition: none;
  }
</style>
