// HpUI — small ambient UI components used across the homepage.
// Exports: HpScrollProgress, HpScrollToTop, HpLiveBadge.

// --- Scroll progress bar (fixed coral line at the very top) ---------
function HpScrollProgress() {
  const [pct, setPct] = React.useState(0);

  React.useEffect(() => {
    let rafId = null;
    const onScroll = () => {
      if (rafId) return;
      rafId = window.requestAnimationFrame(() => {
        const doc = document.documentElement;
        const scrollable = (doc.scrollHeight - window.innerHeight) || 1;
        const p = Math.min(100, Math.max(0, (window.scrollY / scrollable) * 100));
        setPct(p);
        rafId = null;
      });
    };
    onScroll();
    window.addEventListener("scroll", onScroll, { passive: true });
    window.addEventListener("resize", onScroll);
    return () => {
      window.removeEventListener("scroll", onScroll);
      window.removeEventListener("resize", onScroll);
      if (rafId) window.cancelAnimationFrame(rafId);
    };
  }, []);

  return (
    <div className="hp-scroll-progress" aria-hidden="true">
      <div className="hp-scroll-progress-bar" style={{ width: pct + "%" }} />
    </div>
  );
}
window.HpScrollProgress = HpScrollProgress;

// --- Floating back-to-top button ------------------------------------
function HpScrollToTop() {
  const [visible, setVisible] = React.useState(false);

  React.useEffect(() => {
    const onScroll = () => setVisible(window.scrollY > 720);
    onScroll();
    window.addEventListener("scroll", onScroll, { passive: true });
    return () => window.removeEventListener("scroll", onScroll);
  }, []);

  const onClick = () => {
    window.scrollTo({ top: 0, behavior: "smooth" });
  };

  return (
    <button
      type="button"
      className={"hp-scroll-top " + (visible ? "is-visible" : "")}
      onClick={onClick}
      aria-label="Back to top"
      title="Back to top"
    >
      <svg viewBox="0 0 24 24" width="18" height="18" aria-hidden="true">
        <path
          d="M12 5 L12 19 M5 12 L12 5 L19 12"
          fill="none"
          stroke="currentColor"
          strokeWidth="2"
          strokeLinecap="round"
          strokeLinejoin="round"
        />
      </svg>
    </button>
  );
}
window.HpScrollToTop = HpScrollToTop;

// --- LIVE badge (pulsing dot + caption) -----------------------------
function HpLiveBadge({ children }) {
  return (
    <span className="hp-live-badge" role="status">
      <span className="hp-live-dot" aria-hidden="true" />
      <span>{children}</span>
    </span>
  );
}
window.HpLiveBadge = HpLiveBadge;
