/* global React, ReactDOM, SparkTrj, StripTrj, LedgerTrj */
// citation.jsx — citation chip + drawer
// Exposes window.Citation, window.CitationProvider, window.useCitation

const { createContext, useContext, useState, useEffect, useCallback } = React;

const CitationCtx = createContext(null);

function CitationProvider({ children }) {
  const [openKey, setOpenKey] = useState(null);
  const open = useCallback((key) => setOpenKey(key), []);
  const close = useCallback(() => setOpenKey(null), []);

  useEffect(() => {
    function onKey(e) { if (e.key === "Escape") setOpenKey(null); }
    window.addEventListener("keydown", onKey);
    return () => window.removeEventListener("keydown", onKey);
  }, []);

  const tx = openKey ? window.CCT_TRANSCRIPTS[openKey] : null;

  return (
    <CitationCtx.Provider value={{ open, close, openKey }}>
      {children}
      <div className={`drawer-scrim ${openKey ? "open" : ""}`} onClick={close}></div>
      <aside className={`drawer ${openKey ? "open" : ""}`} aria-hidden={!openKey}>
        <div className="drawer-head">
          <div>
            <span className="ticker">PERSISTENT</span>
            <span className="dim" style={{ marginLeft: 12 }}>· verbatim transcript</span>
          </div>
          <button className="close" onClick={close} aria-label="Close">[ESC]</button>
        </div>
        <div className="drawer-body">
          {tx ? (
            <>
              <div className="cite-meta">{tx.title}</div>
              <div className="dim mono" style={{ fontSize: "var(--fs-mono-xs)", marginBottom: "var(--s-4)", letterSpacing: "0.04em" }}>
                {tx.speaker}
              </div>
              <div className="transcript">
                {renderHighlighted(tx.body, tx.highlight)}
              </div>
            </>
          ) : null}
        </div>
        <div className="drawer-foot">
          <span>1 of 101 verified quotes</span>
          <div style={{ display: "flex", gap: "var(--s-2)" }}>
            <button className="btn ghost" onClick={() => navigator.clipboard && tx && navigator.clipboard.writeText(`"${tx.highlight}" — ${tx.title}`)}>
              ⧉ Copy w/ attribution
            </button>
          </div>
        </div>
      </aside>
    </CitationCtx.Provider>
  );
}

function renderHighlighted(body, highlight) {
  if (!highlight) return body;
  const idx = body.indexOf(highlight);
  if (idx < 0) return body;
  return (
    <>
      {body.slice(0, idx)}
      <mark>{highlight}</mark>
      {body.slice(idx + highlight.length)}
    </>
  );
}

function useCitation() {
  return useContext(CitationCtx);
}

// Citation chip
function Citation({ chunk, label, ck }) {
  const ctx = useCitation();
  const isOpen = ctx && ctx.openKey === ck;
  return (
    <button
      className={`cite ${isOpen ? "is-active" : ""}`}
      onClick={(e) => { e.preventDefault(); ctx && ctx.open(ck); }}
      title="Open verbatim transcript"
    >
      <span className="q">[{chunk}</span>
      <span className="arrow">›</span>
      <span className="q">{label}]</span>
    </button>
  );
}

Object.assign(window, { CitationProvider, Citation, useCitation });
