"use client";

import Link from "next/link";
import { useEffect, useState } from "react";

import styles from "./Header.module.css";

/**
 * The only fixed element on the site: a slim bar with tap-to-call and the demo
 * action, appearing after one viewport of scrolling on a phone (Blueprint 03).
 *
 * It uses an IntersectionObserver on a one-viewport sentinel rather than a
 * scroll listener, so nothing runs on the main thread while scrolling.
 */
export function MobileBar({
  phoneHref,
  phoneDisplay,
  demoHref,
  demoLabel,
}: {
  phoneHref: string;
  phoneDisplay: string;
  demoHref: string;
  demoLabel: string;
}) {
  const [visible, setVisible] = useState(false);

  useEffect(() => {
    const sentinel = document.createElement("div");
    sentinel.style.cssText =
      "position:absolute;top:0;left:0;width:1px;height:100vh;pointer-events:none;";
    sentinel.setAttribute("aria-hidden", "true");
    document.body.appendChild(sentinel);

    const observer = new IntersectionObserver(([entry]) => setVisible(!entry.isIntersecting), {
      threshold: 0,
    });
    observer.observe(sentinel);

    return () => {
      observer.disconnect();
      sentinel.remove();
    };
  }, []);

  return (
    <div className={styles.slimBar} data-visible={visible} data-print="hide">
      <a href={phoneHref} className={styles.slimCall} data-event="call_click">
        <svg width="18" height="18" viewBox="0 0 20 20" fill="none" aria-hidden="true">
          <path
            d="M5 2.5h3l1.5 3.5-2 1.5a9 9 0 0 0 5 5l1.5-2 3.5 1.5v3c0 .8-.7 1.5-1.5 1.5A14 14 0 0 1 2.5 4C2.5 3.2 3.2 2.5 4 2.5"
            stroke="currentColor"
            strokeWidth="1.5"
            strokeLinejoin="round"
          />
        </svg>
        {phoneDisplay}
      </a>
      <Link href={demoHref} className={styles.slimDemo}>
        {demoLabel}
      </Link>
    </div>
  );
}
