/* global React */
const { useState, useEffect, useRef } = React;

// ───────── Pill ─────────
function Pill({ children, dot = true }) {
  return (
    <span className="pill">
      {dot && <span className="dot"></span>}
      {children}
    </span>
  );
}

// ───────── Type-on prompt line ─────────
function TypeLine({ prompt, command, delay = 0, speed = 30, onDone }) {
  const [out, setOut] = useState("");
  const [done, setDone] = useState(false);
  useEffect(() => {
    let cancelled = false;
    let i = 0;
    const start = setTimeout(() => {
      const tick = setInterval(() => {
        if (cancelled) return;
        i++;
        setOut(command.slice(0, i));
        if (i >= command.length) {
          clearInterval(tick);
          setDone(true);
          onDone && onDone();
        }
      }, speed);
    }, delay);
    return () => { cancelled = true; clearTimeout(start); };
  }, [command]);
  return (
    <div style={{ fontFamily: "JetBrains Mono, monospace", fontSize: 13 }}>
      <span style={{ color: "var(--accent)" }}>{prompt}</span>{" "}
      <span style={{ color: "var(--ink)" }}>{out}</span>
      {!done && <span className="cursor">_</span>}
    </div>
  );
}

// ───────── Copy button ─────────
function CopyBtn({ text }) {
  const [ok, setOk] = useState(false);
  return (
    <button
      className={"copy-btn" + (ok ? " ok" : "")}
      onClick={() => {
        try {
          navigator.clipboard.writeText(text);
          setOk(true);
          setTimeout(() => setOk(false), 1200);
        } catch (e) {}
      }}
    >
      {ok ? "✓ copied" : "copy"}
    </button>
  );
}

// ───────── Section header (terminal command style) ─────────
function SectionHead({ id, cmd, title, meta }) {
  return (
    <div className="section-head" id={id}>
      <span className="cmd mono" style={{ fontSize: 13 }}>{cmd}</span>
      <h2 className="h">{title}</h2>
      {meta && <span className="meta">{meta}</span>}
    </div>
  );
}

// ───────── Brackets wrapper ─────────
function Brackets({ children, style }) {
  return (
    <div className="brackets" style={style}>
      <span className="bl"></span>
      <span className="br"></span>
      {children}
    </div>
  );
}

// ───────── Side rail nav ─────────
function SideRail({ sections }) {
  const [active, setActive] = useState(sections[0]?.id);
  useEffect(() => {
    const obs = new IntersectionObserver(
      (entries) => {
        entries.forEach((e) => {
          if (e.isIntersecting) setActive(e.target.id);
        });
      },
      { rootMargin: "-40% 0px -50% 0px", threshold: 0 }
    );
    sections.forEach((s) => {
      const el = document.getElementById(s.id);
      if (el) obs.observe(el);
    });
    return () => obs.disconnect();
  }, []);
  return (
    <nav className="rail" aria-label="Sections">
      {sections.map((s) => (
        <a
          key={s.id}
          href={"#" + s.id}
          className={active === s.id ? "active" : ""}
          onClick={(e) => {
            e.preventDefault();
            const el = document.getElementById(s.id);
            if (el) el.scrollIntoView({ behavior: "smooth", block: "start" });
          }}
        >
          <span className="label-text">{s.label}</span>
          <span className="tick"></span>
        </a>
      ))}
    </nav>
  );
}

// ───────── Top status bar ─────────
function TopBar({ prompt }) {
  const [time, setTime] = useState(() => new Date());
  useEffect(() => {
    const t = setInterval(() => setTime(new Date()), 1000);
    return () => clearInterval(t);
  }, []);
  const hh = time.toUTCString().slice(17, 25);
  return (
    <div
      style={{
        position: "sticky",
        top: 0,
        zIndex: 20,
        backdropFilter: "blur(10px)",
        background: "color-mix(in oklab, var(--bg) 78%, transparent)",
        borderBottom: "1px solid var(--line)",
      }}
    >
      <div
        className="topbar-inner"
        style={{
          maxWidth: 1280,
          margin: "0 auto",
          padding: "12px 28px",
          display: "flex",
          alignItems: "center",
          justifyContent: "space-between",
          gap: 18,
          fontSize: 11,
          color: "var(--ink-mute)",
          letterSpacing: "0.16em",
          textTransform: "uppercase",
          fontFamily: "JetBrains Mono, monospace",
          flexWrap: "wrap",
        }}
      >
        <div style={{ display: "flex", alignItems: "center", gap: 14, minWidth: 0 }}>
          <span style={{ color: "var(--accent)" }}>●</span>
          <span className="topbar-prompt">{prompt}</span>
        </div>
        <div style={{ display: "flex", alignItems: "center", gap: 18, flexWrap: "wrap" }}>
          <span className="ink-dim topbar-extra" style={{ display: "flex", alignItems: "center", gap: 6 }}>
            <span style={{ width: 6, height: 6, borderRadius: "50%", background: "var(--accent)", boxShadow: "0 0 8px var(--accent)" }}></span>
            uplink stable
          </span>
          <span className="ink-dim">UTC {hh}</span>
          <span className="ink-dim topbar-extra">SYS-2026</span>
        </div>
      </div>
    </div>
  );
}

// ───────── Marquee ─────────
function Marquee({ items }) {
  const content = items.concat(items).concat(items);
  return (
    <div
      style={{
        borderTop: "1px solid var(--line)",
        borderBottom: "1px solid var(--line)",
        overflow: "hidden",
        background: "rgba(57,255,122,0.02)",
        margin: "60px 0",
      }}
    >
      <div
        className="marquee-row"
        style={{
          display: "flex",
          gap: 36,
          animation: "marqueeScroll 38s linear infinite",
          padding: "16px 0",
          whiteSpace: "nowrap",
          fontFamily: "Space Grotesk, sans-serif",
          fontSize: 22,
          fontWeight: 600,
          color: "var(--ink)",
          letterSpacing: "-0.01em",
          textTransform: "uppercase",
        }}
      >
        {content.map((t, i) => (
          <span key={i} style={{ display: "inline-flex", alignItems: "center", gap: 36 }}>
            {t}
            <span style={{ color: "var(--accent)" }}>◆</span>
          </span>
        ))}
      </div>
      <style>{`@keyframes marqueeScroll { from { transform: translateX(0) } to { transform: translateX(-33.333%) } }`}</style>
    </div>
  );
}

Object.assign(window, { Pill, TypeLine, CopyBtn, SectionHead, Brackets, SideRail, TopBar, Marquee });
