// Small UI primitives used across the portfolio
const { useState, useEffect, useRef, useMemo, useCallback } = React;

function SectionHeader({ num, title, kicker }) {
  return (
    <div className="sec-header">
      <div className="sec-header-top">
        <span className="sec-num">// {num}</span>
        <span className="sec-title">{title}</span>
        {kicker && <span className="sec-kicker">— {kicker}</span>}
      </div>
      <div className="sec-rule" aria-hidden="true" />
    </div>
  );
}

function Tag({ children, active, onClick, as }) {
  const Cmp = as || (onClick ? "button" : "span");
  return (
    <Cmp className={"tag" + (active ? " tag-active" : "") + (onClick ? " tag-btn" : "")} onClick={onClick}>
      {children}
    </Cmp>
  );
}

function MetaRow({ label, children }) {
  return (
    <div className="meta-row">
      <span className="meta-label">{label}</span>
      <span className="meta-value">{children}</span>
    </div>
  );
}

function Prompt({ children, cursor }) {
  return (
    <span className="prompt">
      <span className="prompt-arrow">→</span> {children}
      {cursor && <span className="prompt-cursor" />}
    </span>
  );
}

function ThemeToggle({ theme, onToggle }) {
  return (
    <button className="theme-toggle" onClick={onToggle} aria-label="Toggle theme" title={theme === "dark" ? "Switch to light" : "Switch to dark"}>
      <span className="tt-label">{theme === "dark" ? "[ dark ]" : "[ light ]"}</span>
      <span className="tt-hint">↻</span>
    </button>
  );
}

function StatusDot({ children }) {
  return (
    <span className="status">
      <span className="status-dot" />
      <span>{children}</span>
    </span>
  );
}

// Typing effect for hero subtitle — picks from a rotating list
function Typewriter({ phrases, speed = 55, hold = 1800 }) {
  const [idx, setIdx] = useState(0);
  const [text, setText] = useState("");
  const [dir, setDir] = useState(1); // 1 typing, -1 deleting
  useEffect(() => {
    const cur = phrases[idx];
    if (dir === 1 && text === cur) {
      const t = setTimeout(() => setDir(-1), hold);
      return () => clearTimeout(t);
    }
    if (dir === -1 && text === "") {
      setDir(1);
      setIdx((idx + 1) % phrases.length);
      return;
    }
    const t = setTimeout(() => {
      setText((prev) => dir === 1 ? cur.slice(0, prev.length + 1) : prev.slice(0, -1));
    }, dir === 1 ? speed : speed / 2);
    return () => clearTimeout(t);
  }, [text, dir, idx, phrases, speed, hold]);
  return <span className="typewriter">{text}<span className="tw-caret" /></span>;
}

Object.assign(window, { SectionHeader, Tag, MetaRow, Prompt, ThemeToggle, StatusDot, Typewriter });
