/* Scroll rail — fixed-position progress indicator with section labels. */

const SECTIONS = [
  { id: "top", n: "00", en: "Index", th: "ดัชนี" },
  { id: "what", n: "01", en: "What", th: "สิ่งที่ทำ" },
  { id: "products", n: "02", en: "Products", th: "ผลิตภัณฑ์" },
  { id: "why", n: "03", en: "Why now", th: "ทำไมตอนนี้" },
  { id: "market", n: "04", en: "Market", th: "ตลาด" },
  { id: "approach", n: "05", en: "Approach", th: "แนวทาง" },
  { id: "partners", n: "06", en: "Partner", th: "พาร์ทเนอร์" },
  { id: "investors", n: "07", en: "Invest", th: "ลงทุน" },
  { id: "founder", n: "08", en: "Founder", th: "ผู้ก่อตั้ง" },
  { id: "contact", n: "09", en: "Contact", th: "ติดต่อ" },
];

const ScrollRail = ({ lang }) => {
  const [active, setActive] = React.useState("top");
  const [progress, setProgress] = React.useState(0);

  React.useEffect(() => {
    const onScroll = () => {
      const y = window.scrollY + window.innerHeight * 0.35;
      let cur = "top";
      for (const s of SECTIONS) {
        const el = document.getElementById(s.id);
        if (el && el.offsetTop <= y) cur = s.id;
      }
      setActive(cur);
      const docH = document.documentElement.scrollHeight - window.innerHeight;
      setProgress(docH > 0 ? Math.min(1, window.scrollY / docH) : 0);
    };
    onScroll();
    window.addEventListener("scroll", onScroll, { passive: true });
    return () => window.removeEventListener("scroll", onScroll);
  }, []);

  return (
    <aside className="scroll-rail" aria-hidden="true">
      <div className="rail-progress" style={{ "--p": progress }}>
        <span className="rail-progress-fill" style={{ height: `${progress * 100}%` }}></span>
      </div>
      <div className="rail-list">
        {SECTIONS.map((s) => (
          <a
            key={s.id}
            href={`#${s.id}`}
            className={`rail-item ${active === s.id ? "is-active" : ""}`}
          >
            <span className="rail-num">{s.n}</span>
            <span className="rail-label">{lang === "th" ? s.th : s.en}</span>
            <span className="rail-tick"></span>
          </a>
        ))}
      </div>
      <div className="rail-meta mono-tag">
        <span>{Math.round(progress * 100).toString().padStart(2, "0")}%</span>
      </div>
    </aside>
  );
};

window.ScrollRail = ScrollRail;
