<script lang="ts">
  // 문서 상세 좌측 절(section) 목차 (PR-DocSrv-Hier-Section-UI-1).
  // - groupOrFlat 로 per-doc 동적 (top-segment 1단 그룹 vs flat).
  // - 항목 클릭 → 인라인 아코디언으로 요약/section_type/heading_path breadcrumb 표시.
  // - 본문 스크롤 점프 없음(§Q2, deep-link 는 follow-up). summary=NULL 은 "요약 없음" 문구.
  import Badge from '$lib/components/ui/Badge.svelte';
  import {
    cleanHeading,
    pathSegments,
    groupOrFlat,
    sectionTypeLabel,
    type DocumentSection,
    type OutlineItem,
  } from '$lib/utils/headingPath';

  interface Props {
    sections: DocumentSection[];
    /** 항목 클릭 시 본문 점프 콜백(부모가 #sec-{chunkId} scrollIntoView). 없으면 아코디언만. */
    onJump?: (chunkId: number) => void;
    /** scroll-spy 현재 절(chunk_id) — 강조용. */
    activeKey?: number | null;
  }
  let { sections, onJump, activeKey = null }: Props = $props();

  let layout = $derived(groupOrFlat(sections));
  let total = $derived(sections.length);
  let selectedId = $state<number | null>(null);

  function toggle(item: OutlineItem) {
    const id = item.section.chunk_id;
    selectedId = selectedId === id ? null : id;
  }
  function title(s: DocumentSection): string {
    return cleanHeading(s.section_title) || pathSegments(s.heading_path).at(-1) || '(제목 없음)';
  }
  function isLowConf(s: DocumentSection): boolean {
    return s.confidence != null && s.confidence < 0.5;
  }
</script>

{#snippet itemRow(item: OutlineItem)}
  {@const s = item.section}
  {@const open = selectedId === s.chunk_id}
  {@const active = activeKey != null && activeKey === s.chunk_id}
  {@const typeLabel = sectionTypeLabel(s.section_type)}
  <li>
    <button
      type="button"
      onclick={() => { toggle(item); onJump?.(s.chunk_id); }}
      aria-expanded={open}
      aria-current={active ? 'true' : undefined}
      class={[
        'w-full text-left px-2 py-1.5 rounded-md text-xs flex items-start gap-1.5 transition-colors border-l-2',
        open ? 'bg-surface-active text-text border-accent' : active ? 'bg-surface text-accent-hover border-accent' : 'text-dim hover:bg-surface hover:text-text border-transparent',
      ].join(' ')}
    >
      <span class="flex-1 min-w-0 leading-snug break-words">{title(s)}</span>
      <span class="flex items-center gap-1 shrink-0">
        {#if item.fragmentCount > 1}
          <Badge tone="neutral" size="sm">{item.fragmentCount}조각</Badge>
        {/if}
        {#if typeLabel}
          <Badge tone="accent" size="sm">{typeLabel}</Badge>
        {/if}
      </span>
    </button>
    {#if open}
      <div class="px-2 pb-2 pt-1 text-xs">
        {#if pathSegments(s.heading_path).length}
          <div class="text-faint mb-1 leading-snug break-words">
            {pathSegments(s.heading_path).join(' › ')}
          </div>
        {/if}
        {#if s.summary}
          <p class="text-text leading-relaxed whitespace-pre-line">{s.summary}</p>
          {#if isLowConf(s)}
            <div class="mt-1.5">
              <Badge tone="warning" size="sm">저신뢰 — 표 추출이 불완전할 수 있음</Badge>
            </div>
          {/if}
        {:else}
          <p class="text-faint italic">요약 없음 — 짧은 절이거나 아직 분석되지 않았습니다.</p>
        {/if}
      </div>
    {/if}
  </li>
{/snippet}

<div class="text-xs">
  <h3 class="text-xs font-semibold text-dim uppercase mb-2 flex items-center justify-between">
    <span>절 목차</span>
    <span class="text-faint font-normal">{total}</span>
  </h3>

  {#if layout.mode === 'group'}
    <div class="space-y-3">
      {#each layout.groups as g (g.key)}
        <div>
          <div
            class={[
              'px-2 mb-1 text-[11px] font-semibold uppercase tracking-wide',
              g.isOther ? 'text-faint' : 'text-dim',
            ].join(' ')}
          >
            {g.key}
            <span class="font-normal text-faint">({g.items.length})</span>
          </div>
          <ul class="space-y-0.5">
            {#each g.items as item (item.section.chunk_id)}
              {@render itemRow(item)}
            {/each}
          </ul>
        </div>
      {/each}
    </div>
  {:else}
    <ul class="space-y-0.5">
      {#each layout.items as item (item.section.chunk_id)}
        {@render itemRow(item)}
      {/each}
    </ul>
  {/if}
</div>
