// siderail.jsx — Vertical chapter index. 4 chapters now.

const { useEffect, useState } = React;

const CHAPTERS = [
  { id: "hero",     n: "01", name: "Index" },
  { id: "platform", n: "02", name: "Platform" },
  { id: "pillars",  n: "03", name: "Pillars" },
  { id: "network",  n: "04", name: "Network" },
  { id: "speak",    n: "05", name: "Speak" },
];

function SideRail() {
  const [active, setActive] = useState("hero");
  useEffect(() => {
    const els = CHAPTERS.map(c => document.getElementById(c.id)).filter(Boolean);
    if (els.length === 0) return;
    function reset() {
      const vh = window.innerHeight;
      const anchor = vh * 0.3;
      let best = null, bestDist = Infinity;
      els.forEach(el => {
        const r = el.getBoundingClientRect();
        if (r.bottom < 0 || r.top > vh) return;
        const d = Math.abs(r.top - anchor);
        if (d < bestDist) { bestDist = d; best = el.id; }
      });
      if (best && best !== active) setActive(best);
    }
    reset();
    window.addEventListener("scroll", reset, { passive: true });
    window.addEventListener("resize", reset);
    return () => {
      window.removeEventListener("scroll", reset);
      window.removeEventListener("resize", reset);
    };
  }, [active]);

  return (
    <aside className="siderail" aria-label="Chapter index">
      <a href="#hero" className="siderail-brand" aria-label="KavNetwork — top">
        <span className="siderail-brand-glyph">K</span>
      </a>
      <div className="siderail-items">
        {CHAPTERS.map((c) => (
          <a key={c.id} href={`#${c.id}`}
            className={`siderail-item ${active === c.id ? "active" : ""}`}>
            <span className="si-num">{c.n}</span>
            <span className="si-tick" />
            <span className="si-name">{c.name}</span>
          </a>
        ))}
      </div>
      <div className="siderail-bottom">
        <LanguageToggle />
        <span className="siderail-foot">KavNetwork · Brand signal</span>
      </div>
    </aside>
  );
}

function LanguageToggle() {
  const [lang, setLang] = useState("en");
  useEffect(() => { document.documentElement.lang = lang; }, [lang]);
  return (
    <div className="lang-toggle" role="group" aria-label="Language">
      <button
        type="button"
        className={`lang-opt ${lang === "en" ? "is-on" : ""}`}
        onClick={() => setLang("en")}
        aria-pressed={lang === "en"}
      >EN</button>
      <button
        type="button"
        className="lang-opt is-soon"
        title="Portuguese — coming soon"
        aria-disabled="true"
        onClick={(e) => e.preventDefault()}
      >PT</button>
    </div>
  );
}

window.SideRail = SideRail;
window.LanguageToggle = LanguageToggle;
window.CHAPTERS = CHAPTERS;
