/* SkipNav — fixed right-rail section navigator.
   Tracks the current section via IntersectionObserver and highlights it.
   Click any label to scroll to that section. Includes a wavy line indicator
   next to the active label, plain rules next to inactive labels.
   Hidden on very small viewports to avoid covering content. */

const SkipNav = ({ lang }) => {
  const isAR = lang === "ar";
  const sections = isAR ? [
    { id: "problem", label: "المشكلة" },
    { id: "what",    label: "النظام" },
    { id: "tryit",   label: "جرّب" },
    { id: "proof",   label: "النتائج" },
    { id: "pricing", label: "الأسعار" },
    { id: "book",    label: "احجز" },
    { id: "faq",     label: "أسئلة" },
  ] : [
    { id: "problem", label: "Problem" },
    { id: "what",    label: "System" },
    { id: "tryit",   label: "Try it" },
    { id: "proof",   label: "Proof" },
    { id: "pricing", label: "Pricing" },
    { id: "book",    label: "Book" },
    { id: "faq",     label: "FAQ" },
  ];

  const [active, setActive] = React.useState(sections[0].id);
  const [visible, setVisible] = React.useState(false);

  React.useEffect(() => {
    // Show the rail only after we've scrolled past the hero
    const onScroll = () => {
      setVisible(window.scrollY > window.innerHeight * 0.6);
    };
    onScroll();
    window.addEventListener("scroll", onScroll, { passive: true });
    return () => window.removeEventListener("scroll", onScroll);
  }, []);

  React.useEffect(() => {
    const els = sections
      .map(s => ({ id: s.id, el: document.getElementById(s.id) }))
      .filter(s => s.el);
    if (!els.length) return;

    const io = new IntersectionObserver((entries) => {
      // Pick the entry whose top is closest to the upper-third of the viewport.
      const candidates = entries.filter(e => e.isIntersecting);
      if (!candidates.length) return;
      // Sort by distance from a 33% scroll line.
      candidates.sort((a, b) => {
        const aDist = Math.abs(a.boundingClientRect.top - window.innerHeight * 0.33);
        const bDist = Math.abs(b.boundingClientRect.top - window.innerHeight * 0.33);
        return aDist - bDist;
      });
      setActive(candidates[0].target.id);
    }, {
      // Trigger when section enters middle band of viewport
      rootMargin: "-25% 0px -55% 0px",
      threshold: [0, 0.1, 0.5, 1],
    });

    els.forEach(s => io.observe(s.el));
    return () => io.disconnect();
  }, [lang]);

  const goTo = (id) => {
    const el = document.getElementById(id);
    if (!el) return;
    // Native scrollIntoView is intercepted by Lenis — use its API directly.
    if (window.__lenis) {
      window.__lenis.scrollTo(el, { offset: 0 });
    } else {
      const top = el.getBoundingClientRect().top + window.scrollY;
      window.scrollTo({ top, behavior: "smooth" });
    }
  };

  return (
    <nav
      className={`skipnav ${visible ? "is-visible" : ""} ${isAR ? "is-ar" : ""}`}
      aria-label={isAR ? "تنقّل الأقسام" : "Section navigation"}
    >
      <ul className="skipnav-list">
        {sections.map(s => {
          const isActive = active === s.id;
          return (
            <li key={s.id} className={`skipnav-item ${isActive ? "is-active" : ""}`}>
              <button
                type="button"
                onClick={() => goTo(s.id)}
                aria-current={isActive ? "true" : undefined}
                className="skipnav-btn"
              >
                <span className="skipnav-label">{s.label}</span>
                <span className="skipnav-rule" aria-hidden="true">
                  {isActive ? (
                    <svg viewBox="0 0 40 12" preserveAspectRatio="none" className="skipnav-wave">
                      <path
                        d="M0,6 Q5,0 10,6 T20,6 T30,6 T40,6"
                        fill="none"
                        stroke="currentColor"
                        strokeWidth="1.5"
                        strokeLinecap="round"
                      />
                    </svg>
                  ) : (
                    <span className="skipnav-line"></span>
                  )}
                </span>
              </button>
            </li>
          );
        })}
      </ul>

      <style>{`
        .skipnav {
          position: fixed;
          top: 50%;
          right: 24px;
          transform: translateY(-50%);
          z-index: 60;
          opacity: 0;
          pointer-events: none;
          transition: opacity .5s var(--ease, ease);
          font-family: var(--sans, inherit);
        }
        .skipnav.is-visible {
          opacity: 1;
          pointer-events: auto;
        }
        .skipnav.is-ar {
          right: auto;
          left: 24px;
        }

        .skipnav-list {
          list-style: none;
          margin: 0;
          padding: 0;
          display: flex;
          flex-direction: column;
          gap: 14px;
        }

        .skipnav-btn {
          all: unset;
          cursor: pointer;
          display: grid;
          grid-template-columns: 1fr 40px;
          align-items: center;
          gap: 12px;
          padding: 4px 0;
          color: color-mix(in oklab, var(--ink) 38%, transparent);
          transition: color .3s var(--ease, ease);
        }
        .skipnav.is-ar .skipnav-btn {
          grid-template-columns: 40px 1fr;
        }

        .skipnav-label {
          font-size: 14px;
          letter-spacing: -0.01em;
          line-height: 1;
          text-align: right;
          white-space: nowrap;
          font-weight: 400;
        }
        .skipnav.is-ar .skipnav-label {
          text-align: left;
          order: 2;
        }

        .skipnav-rule {
          display: flex;
          align-items: center;
          justify-content: flex-start;
          height: 12px;
          width: 40px;
          color: color-mix(in oklab, var(--ink) 38%, transparent);
        }
        .skipnav.is-ar .skipnav-rule {
          order: 1;
          justify-content: flex-end;
        }

        .skipnav-line {
          display: block;
          width: 24px;
          height: 1px;
          background: currentColor;
          opacity: 0.65;
        }

        .skipnav-wave {
          width: 36px;
          height: 12px;
          color: var(--accent);
          overflow: visible;
        }

        .skipnav-item.is-active .skipnav-btn {
          color: var(--accent);
        }
        .skipnav-item.is-active .skipnav-label {
          color: var(--accent);
        }

        .skipnav-btn:hover {
          color: var(--ink);
        }
        .skipnav-btn:hover .skipnav-line {
          opacity: 1;
        }

        /* Compact on smaller desktops */
        @media (max-width: 1100px) {
          .skipnav { right: 16px; }
          .skipnav.is-ar { left: 16px; right: auto; }
          .skipnav-label { font-size: 13px; }
          .skipnav-rule { width: 32px; }
          .skipnav-line { width: 20px; }
          .skipnav-wave { width: 28px; }
          .skipnav-btn { grid-template-columns: 1fr 32px; }
          .skipnav.is-ar .skipnav-btn { grid-template-columns: 32px 1fr; }
        }

        /* Hide on mobile — nav-like rails get in the way of touch scroll */
        @media (max-width: 760px) {
          .skipnav { display: none; }
        }
      `}</style>
    </nav>
  );
};

window.SkipNav = SkipNav;
