<!--
  /ask — Phase 3.4 Ask Pipeline Frontend.

  URL-driven: `/ask?q=<encoded>` 가 진입점. $effect 로 q 변화 감지 →
  `/api/search/ask` 호출 → 3-panel 렌더 (Answer / Evidence / Results).

  중복 호출 방지: lastQuery 가드 (hydration + reactive trigger 시 같은 q 2번 발동 방지).
-->
<script lang="ts">
  import { page } from '$app/stores';
  import { goto } from '$app/navigation';
  import { api, type ApiError } from '$lib/api';
  import { addToast } from '$lib/stores/toast';
  import EmptyState from '$lib/components/ui/EmptyState.svelte';
  import AskAnswer from '$lib/components/ask/AskAnswer.svelte';
  import AskEvidence from '$lib/components/ask/AskEvidence.svelte';
  import AskResults from '$lib/components/ask/AskResults.svelte';
  import { Sparkles, Search } from 'lucide-svelte';
  import type { AskResponse } from '$lib/types/ask';

  // ── state ───────────────────────────────────────────
  let queryInput = $state('');
  let data = $state<AskResponse | null>(null);
  let loading = $state(false);

  // 중복 호출 방지 가드 (hydration + reactive trigger 이중 발동 방지)
  let lastQuery = '';

  // citation scroll 연동: Answer 가 [n] 클릭 → Evidence 카드로 이동 + highlight
  const citationNodes = new Map<number, HTMLElement>();
  let activeCitation = $state<number | null>(null);

  function registerCitation(n: number, node: HTMLElement) {
    citationNodes.set(n, node);
    return {
      destroy() {
        citationNodes.delete(n);
      },
    };
  }

  function scrollToCitation(n: number) {
    activeCitation = n;
    const node = citationNodes.get(n);
    node?.scrollIntoView({ behavior: 'smooth', block: 'center' });
  }

  // ── submit (URL-driven, back 자동) ──────────────────
  function submit() {
    const q = queryInput.trim();
    if (!q) return;
    goto(`/ask?q=${encodeURIComponent(q)}`);
  }

  function handleKeydown(e: KeyboardEvent) {
    if (e.key === 'Enter' && !e.isComposing) {
      e.preventDefault();
      submit();
    }
  }

  // ── API 호출 ───────────────────────────────────────
  async function runAsk(q: string) {
    loading = true;
    activeCitation = null;
    try {
      data = await api<AskResponse>(
        `/search/ask?q=${encodeURIComponent(q)}&limit=10`,
      );
    } catch (err) {
      const apiErr = err as ApiError;
      addToast('error', apiErr.detail || '답변 생성 실패');
      data = null;
    } finally {
      loading = false;
    }
  }

  // ── URL → runAsk (중복 가드) ────────────────────────
  $effect(() => {
    const q = $page.url.searchParams.get('q') ?? '';
    queryInput = q;
    if (!q) {
      data = null;
      loading = false;
      lastQuery = '';
      return;
    }
    if (q === lastQuery) return;
    lastQuery = q;
    runAsk(q);
  });
</script>

<svelte:head>
  <title>질문 - PKM</title>
</svelte:head>

<div class="h-full overflow-auto">
  <!-- 상단 검색바 (sticky) -->
  <div class="sticky top-0 z-10 bg-bg/80 backdrop-blur border-b border-default px-4 py-3">
    <div class="flex items-center gap-2 max-w-5xl mx-auto">
      <div class="relative flex-1">
        <Search
          size={14}
          class="absolute left-3 top-1/2 -translate-y-1/2 text-dim pointer-events-none"
        />
        <input
          data-search-input
          type="text"
          bind:value={queryInput}
          onkeydown={handleKeydown}
          placeholder="질문을 입력하세요 (/ 키로 포커스)"
          class="w-full pl-9 pr-3 py-2 bg-surface border border-default rounded-lg text-text text-sm focus:border-accent outline-none"
        />
      </div>
    </div>
  </div>

  <!-- 본문 -->
  <div class="max-w-5xl mx-auto p-4">
    {#if !queryInput && !loading && !data}
      <div class="py-16">
        <EmptyState
          icon={Sparkles}
          title="근거 기반 답변을 받아보세요"
          description="질문을 입력하면 문서에서 근거를 찾아 인용 기반 답변을 생성합니다."
        />
      </div>
    {:else}
      <div class="grid gap-4 lg:grid-cols-[1.2fr_0.9fr] items-start">
        <!-- 좌: Answer + Results -->
        <div class="flex flex-col gap-4 min-w-0">
          <AskAnswer {data} {loading} onCitationClick={scrollToCitation} />
          <AskResults {data} {loading} />
        </div>

        <!-- 우: Evidence (lg 이상 sticky) -->
        <div class="lg:sticky lg:top-20 lg:self-start min-w-0">
          <AskEvidence
            {data}
            {loading}
            {activeCitation}
            {registerCitation}
          />
        </div>
      </div>
    {/if}
  </div>
</div>
