/**
 * SampleSessions — optional fixture-driven quick-start.
 *
 * The MVP collection list (pre-CE-WP-0005) ingested fixture PDFs over
 * `fetch`. After the session refactor that workflow is no longer the
 * default; it survives here as an optional way to seed the active
 * session with a sample document for demo and testing.
 *
 * Mounted by `SessionMenu` (T04) under a "Sample sessions ▸" entry
 * and by the integration tests under CE-WP-0002-T09 / -T05 that need
 * a known-good document.
 */

import { useCallback, useState } from "react";

import { ingestPdf } from "@source/index";
import type { DocumentId } from "@shared/ids";
import {
  useActiveDocumentId,
  useEngine,
  usePdfByteStore,
} from "@work/index";

import manifest from "../../../fixtures/pdfs/manifest.json";

interface Fixture {
  id: string;
  filename: string;
  description: string;
  page_count: number;
}

const FIXTURES: readonly Fixture[] = (manifest as { fixtures: Fixture[] }).fixtures;

export function SampleSessions() {
  const engine = useEngine();
  const byteStore = usePdfByteStore();
  const { id: activeId, setId } = useActiveDocumentId();
  const [loadingFixtureId, setLoadingFixtureId] = useState<string | null>(null);
  const [error, setError] = useState<string | null>(null);
  const [byFixture, setByFixture] = useState<Record<string, DocumentId>>({});

  const handleLoad = useCallback(
    async (fixture: Fixture) => {
      setError(null);
      const existing = byFixture[fixture.id];
      if (existing) {
        setId(existing);
        return;
      }
      setLoadingFixtureId(fixture.id);
      try {
        const url = `/fixtures/pdfs/${encodeURIComponent(fixture.filename)}`;
        const response = await fetch(url);
        if (!response.ok) {
          throw new Error(`fetch ${url} → ${response.status}`);
        }
        const buffer = await response.arrayBuffer();
        const bytes = new Uint8Array(buffer);
        const { document, representation } = await ingestPdf(bytes, {
          filename: fixture.filename,
        });
        // Push the bytes into the byte store so the viewer can mount them via
        // the same blob URL machinery used by the upload path. The document
        // record carries the blob URL on `uri` for the viewer adapter.
        const record = byteStore.put(document.id, bytes);
        engine.documents.register({
          document: { ...document, uri: record.blobUrl },
          representation,
        });
        setByFixture((prev) => ({ ...prev, [fixture.id]: document.id }));
        setId(document.id);
      } catch (err) {
        setError(err instanceof Error ? err.message : String(err));
      } finally {
        setLoadingFixtureId(null);
      }
    },
    [byFixture, byteStore, engine, setId],
  );

  return (
    <div data-testid="sample-sessions">
      <p style={{ fontSize: 12, color: "#555", margin: "0 0 6px" }}>
        Load a fixture PDF as a sample document for the active session.
      </p>
      {error && (
        <p style={{ fontSize: 12, color: "#b00020", background: "#fff4f4", padding: 6 }}>
          {error}
        </p>
      )}
      <ul style={{ listStyle: "none", padding: 0, margin: 0 }}>
        {FIXTURES.map((f) => {
          const isLoading = loadingFixtureId === f.id;
          const documentId = byFixture[f.id];
          const isActive = documentId !== undefined && documentId === activeId;
          return (
            <li key={f.id} style={{ marginBottom: 6 }}>
              <button
                onClick={() => void handleLoad(f)}
                disabled={isLoading}
                style={{
                  display: "block",
                  width: "100%",
                  textAlign: "left",
                  background: isActive ? "#e8f0ff" : "white",
                  border: "1px solid #ccc",
                  padding: 6,
                  cursor: isLoading ? "wait" : "pointer",
                  fontSize: 12,
                }}
              >
                <div style={{ fontWeight: 600 }}>{f.id}</div>
                <div style={{ color: "#666", fontSize: 11 }}>
                  {f.page_count} page{f.page_count === 1 ? "" : "s"}
                  {isLoading ? " · loading…" : isActive ? " · open" : ""}
                </div>
              </button>
            </li>
          );
        })}
      </ul>
    </div>
  );
}
