/**
 * Search-box.ai
 * Author: Simon-Pierre Boucher
 * Contact: contact@spboucher.ai
 * File: apps/web/components/AnswerPanel.tsx
 * Description: Streaming answer renderer — sanitized markdown, citation links, copy action.
 */

"use client";

import { useMemo, useState } from "react";
import { marked } from "marked";
import DOMPurify from "dompurify";
import { Pastille } from "./Pastille";

export function AnswerPanel({
  markdown,
  done,
  live
}: {
  markdown: string;
  done: boolean;
  live: boolean;
}) {
  const [copied, setCopied] = useState(false);

  const html = useMemo(() => {
    if (!markdown) return "";
    const raw = marked.parse(markdown, { async: false, gfm: true });
    const safe = DOMPurify.sanitize(raw, { USE_PROFILES: { html: true } });
    // Citations are mechanical [n] markers from state — link them to the sources board.
    return safe.replace(
      /\[(\d{1,3})\]/g,
      (_m, n: string) => `<sup class="cite"><a href="#src-${n}" title="source ${n}">[${n}]</a></sup>`
    );
  }, [markdown]);

  async function copy() {
    try {
      await navigator.clipboard.writeText(markdown);
      setCopied(true);
      setTimeout(() => setCopied(false), 1600);
    } catch {
      // clipboard unavailable — ignore
    }
  }

  return (
    <div className="answer-panel">
      <div className="answer-head">
        <Pastille kind="synthesis" size="sm" spinning={markdown.length > 0 && !done} />
        <span className="lbl">{done ? "final answer" : markdown ? "writing…" : "answer"}</span>
        {done && (
          <button className="btn-ghost" onClick={() => void copy()}>
            {copied ? "copied ✓" : "copy markdown"}
          </button>
        )}
      </div>
      <div className="answer-body">
        {!markdown ? (
          <div className="answer-waiting">
            <p>
              {live
                ? "The answer is written here, token by token, once the evidence base is ready."
                : "No answer was produced for this session."}
            </p>
            {live && (
              <>
                <span className="skel" style={{ width: "82%" }} />
                <span className="skel" style={{ width: "95%" }} />
                <span className="skel" style={{ width: "64%" }} />
              </>
            )}
          </div>
        ) : (
          <>
            <div className="answer-md" dangerouslySetInnerHTML={{ __html: html }} />
            {!done && <span className="caret" aria-hidden />}
          </>
        )}
      </div>
    </div>
  );
}
