// Glossary.jsx — dotted-underline term with hover tooltip (dark).
const { useState, useRef } = React;

function Term({ children, term }) {
  const key = term || (typeof children === "string" ? children : null);
  const def = key && CONTENT.glossary[key];
  const [open, setOpen] = useState(false);
  const [pos, setPos] = useState({ x: 0, y: 0 });
  const ref = useRef(null);

  if (!def) return <>{children}</>;

  const handleEnter = () => {
    if (!ref.current) return;
    const r = ref.current.getBoundingClientRect();
    setPos({ x: r.left + r.width / 2, y: r.top });
    setOpen(true);
  };

  return (
    <>
      <abbr ref={ref} data-term={key}
        onMouseEnter={handleEnter} onMouseLeave={() => setOpen(false)}
        onFocus={handleEnter} onBlur={() => setOpen(false)} tabIndex={0}>
        {children}
      </abbr>
      {open && ReactDOM.createPortal(
        <div role="tooltip"
          style={{ position: "fixed", left: pos.x, top: pos.y - 10,
            transform: "translate(-50%, -100%)", zIndex: 100, maxWidth: 340 }}
          className="surface-solid rounded-lg shadow-2xl px-3.5 py-2.5 pointer-events-none text-[12.5px] leading-relaxed">
          <div className="font-mono uppercase tracking-[0.22em] text-[10px] text-[color:var(--ink-faint)] mb-1">
            {key}
          </div>
          <div className="text-[color:var(--ink)]">{def}</div>
        </div>,
        document.body
      )}
    </>
  );
}
window.Term = Term;
