// Shared utilities + small components
const { useState, useEffect, useRef, useMemo, useCallback } = React;

// =====================================================
// ImageSlot wrapper — React 18 + Babel-standalone doesn't reliably forward
// the `src` attribute to <image-slot> custom elements. Set it via ref.
// =====================================================
function ImgSlot({ id, src, placeholder, shape, mask, fit }) {
  const ref = useRef(null);
  useEffect(() => {
    const el = ref.current;
    if (!el) return;
    if (src) el.setAttribute("src", src); else el.removeAttribute("src");
  }, [src]);
  return React.createElement("image-slot", {
    ref, id,
    placeholder,
    ...(shape ? { shape } : {}),
    ...(mask ? { mask } : {}),
    ...(fit ? { fit } : {}),
  });
}

// =====================================================
// i18n hook
// =====================================================
function useT(lang) {
  return useCallback((node) => {
    if (node == null) return "";
    if (typeof node === "string" || typeof node === "number") return node;
    if (node[lang] != null) return node[lang];
    if (node.en != null) return node.en;
    return "";
  }, [lang]);
}

// =====================================================
// Reveal-on-scroll
// =====================================================
function useReveal() {
  useEffect(() => {
    const els = document.querySelectorAll(".reveal");
    if (!("IntersectionObserver" in window)) {
      els.forEach((e) => e.classList.add("in"));
      return;
    }
    const io = new IntersectionObserver((entries) => {
      entries.forEach((e) => { if (e.isIntersecting) { e.target.classList.add("in"); io.unobserve(e.target); } });
    }, { threshold: 0.1, rootMargin: "0px 0px -40px 0px" });
    els.forEach((el) => io.observe(el));
    return () => io.disconnect();
  });
}

// =====================================================
// Wolf / Alpha mark — placeholder badge (NOT a recreation of any logo)
// =====================================================
function AlphaMark({ size = 34 }) {
  return (
    <svg width={size} height={size} viewBox="0 0 60 60" fill="none" xmlns="http://www.w3.org/2000/svg" aria-hidden="true">
      <rect x="1" y="1" width="58" height="58" stroke="#d4a437" strokeWidth="1.2" fill="none" />
      <text x="30" y="28" textAnchor="middle" fontFamily="Anton, Impact, sans-serif" fontSize="22" fill="#d4a437" letterSpacing="1">A</text>
      <line x1="14" y1="38" x2="46" y2="38" stroke="#d4a437" strokeWidth="0.8" />
      <text x="30" y="50" textAnchor="middle" fontFamily="JetBrains Mono, monospace" fontSize="6" fill="#d4a437" letterSpacing="2">GYM</text>
    </svg>
  );
}

// =====================================================
// Brand wordmark
// =====================================================
function Brand({ onClick }) {
  return (
    <a href="#/" className="brand" onClick={onClick}>
      <img className="brand-logo" src="assets/alpha-logo.png" alt="Alpha Gym" />
      <span className="brand-text">
        <div>ALPHA GYM</div>
        <small>SPORTS CENTER</small>
      </span>
    </a>
  );
}

// =====================================================
// Language switch
// =====================================================
function LangSwitch({ lang, setLang }) {
  return (
    <div className="lang-switch" role="group" aria-label="Language">
      {["MK", "SQ", "EN"].map((c) => (
        <button key={c} className={lang === c.toLowerCase() ? "on" : ""} onClick={() => setLang(c.toLowerCase())}>{c}</button>
      ))}
    </div>
  );
}

// =====================================================
// Nav
// =====================================================
function Nav({ lang, setLang, route }) {
  const [scrolled, setScrolled] = useState(false);
  const [menuOpen, setMenuOpen] = useState(false);
  const [active, setActive] = useState("");
  const t = useT(lang);
  const T = window.I18N;

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

  const sectionIds = ["about", "facilities", "programs", "pricing", "services", "trainers", "contact"];

  // Highlight the section currently in view (only on the home route).
  useEffect(() => {
    if (route.route !== "home") { setActive(""); return; }
    const els = sectionIds.map((id) => document.getElementById(id)).filter(Boolean);
    if (!els.length || !("IntersectionObserver" in window)) return;
    const io = new IntersectionObserver((entries) => {
      entries.forEach((e) => { if (e.isIntersecting) setActive(e.target.id); });
    }, { rootMargin: "-40% 0px -55% 0px", threshold: 0 });
    els.forEach((el) => io.observe(el));
    return () => io.disconnect();
  }, [route.route]);

  const links = [
    { id: "about",      label: t(T.nav.about) },
    { id: "facilities", label: t(T.nav.facilities) },
    { id: "programs",   label: t(T.nav.programs) },
    { id: "pricing",    label: t(T.nav.pricing) },
    { id: "services",   label: t(T.nav.services) },
    { id: "trainers",   label: t(T.nav.trainers) },
    { id: "contact",    label: t(T.nav.contact) },
  ];

  // Click handler: if we're already on the home route AND on the same section,
  // re-trigger the scroll (since hashchange won't fire).
  const goSection = (id) => (e) => {
    setMenuOpen(false);
    if (route.route === "home" && (window.location.hash || "").endsWith("/" + id)) {
      e.preventDefault();
      const el = document.getElementById(id);
      if (el) {
        const navH = document.querySelector(".nav").offsetHeight || 80;
        window.scrollTo({ top: el.getBoundingClientRect().top + window.scrollY - (navH + 8), behavior: "smooth" });
      }
    }
  };
  const goHome = () => { setMenuOpen(false); };

  return (
    <React.Fragment>
      <nav className={`nav ${scrolled ? "scrolled" : ""}`}>
        <div className="container nav-inner">
          <Brand onClick={goHome} />
          <div className="nav-links">
            {links.map((l) => (
              <a
                key={l.id}
                href={`#/${l.id}`}
                className={active === l.id ? "active" : ""}
                onClick={goSection(l.id)}
              >{l.label}</a>
            ))}
          </div>
          <div className="nav-right">
            <LangSwitch lang={lang} setLang={setLang} />
            <a href="#/pricing" className="btn btn-primary btn-sm" onClick={goSection("pricing")}>{t(T.nav.join)} <span className="arrow">→</span></a>
            <button className="menu-btn" onClick={() => setMenuOpen(true)} aria-label="Open menu"><span></span></button>
          </div>
        </div>
      </nav>
      <div className={`mobile-menu ${menuOpen ? "open" : ""}`}>
        <button className="close-btn" onClick={() => setMenuOpen(false)} aria-label="Close">×</button>
        <div className="mobile-menu-links">
          {links.map((l) => (
            <a key={l.id} href={`#/${l.id}`} onClick={goSection(l.id)}>{l.label}</a>
          ))}
        </div>
        <div className="mobile-menu-foot">
          <LangSwitch lang={lang} setLang={setLang} />
          <a href="#/pricing" className="btn btn-primary" onClick={goSection("pricing")}>{t(T.nav.join)} →</a>
        </div>
      </div>
    </React.Fragment>
  );
}

// =====================================================
// WhatsApp floating button
// =====================================================
function WhatsAppFAB({ number = "+38970123456", text = "Hello, I'm interested in Alpha Gym." }) {
  const num = number.replace(/[^0-9]/g, "");
  const url = `https://wa.me/${num}?text=${encodeURIComponent(text)}`;
  return (
    <a className="whatsapp-fab" href={url} target="_blank" rel="noreferrer" aria-label="WhatsApp">
      <svg viewBox="0 0 24 24" fill="currentColor"><path d="M20.52 3.48A11.94 11.94 0 0 0 12.04 0C5.5 0 .2 5.3.2 11.84c0 2.09.55 4.13 1.6 5.93L0 24l6.4-1.68a11.83 11.83 0 0 0 5.64 1.44h.01c6.54 0 11.85-5.3 11.85-11.84 0-3.16-1.23-6.13-3.38-8.44zm-8.48 18.2h-.01a9.86 9.86 0 0 1-5.02-1.37l-.36-.21-3.8 1 1.01-3.7-.23-.38a9.83 9.83 0 1 1 18.24-5.18 9.85 9.85 0 0 1-9.83 9.84zm5.4-7.37c-.3-.15-1.75-.86-2.02-.96-.27-.1-.47-.15-.66.15-.2.3-.76.96-.93 1.16-.17.2-.34.22-.64.07a8.1 8.1 0 0 1-2.38-1.47 9 9 0 0 1-1.65-2.05c-.17-.3-.02-.46.13-.61.13-.13.3-.34.45-.5.15-.18.2-.3.3-.5.1-.2.05-.37-.03-.52-.07-.15-.66-1.6-.9-2.18-.24-.58-.49-.5-.66-.51l-.57-.01c-.2 0-.52.07-.8.37s-1.05 1.02-1.05 2.5 1.07 2.9 1.22 3.1c.15.2 2.1 3.21 5.07 4.5.71.3 1.27.49 1.7.62.71.23 1.36.2 1.87.12.57-.08 1.75-.71 2-1.4.25-.7.25-1.28.18-1.4-.07-.13-.27-.2-.57-.35z"/></svg>
    </a>
  );
}

// =====================================================
// Footer
// =====================================================
function Footer({ lang }) {
  const t = useT(lang);
  const T = window.I18N;
  return (
    <footer className="footer">
      <div className="container">
        <div className="footer-grid">
          <div>
            <h5>Alpha Gym</h5>
            <p className="footer-tag">{t(T.footer.tagline)}</p>
          </div>
          <div>
            <h5>{t(T.footer.explore)}</h5>
            <ul>
              <li><a href="#/about">{t(T.nav.about)}</a></li>
              <li><a href="#/facilities">{t(T.nav.facilities)}</a></li>
              <li><a href="#/trainers">{t(T.nav.trainers)}</a></li>
            </ul>
          </div>
          <div>
            <h5>{t(T.footer.join)}</h5>
            <ul>
              <li><a href="#/pricing">{t(T.nav.pricing)}</a></li>
              <li><a href="#/contact">{t(T.nav.contact)}</a></li>
            </ul>
          </div>
          <div>
            <h5>{t(T.footer.getInTouch)}</h5>
            <ul>
              <li><a href="mailto:alphagym2023@gmail.com">alphagym2023@gmail.com</a></li>
              <li><a href="tel:071907907">071 907 907</a></li>
              <li><a href="https://www.instagram.com/gym_alphaa/" target="_blank" rel="noreferrer">Instagram</a></li>
            </ul>
          </div>
        </div>
        <div className="footer-bottom">
          <span>{t(T.footer.rights)}</span>
          <span>TETOVO · MK</span>
        </div>
      </div>
    </footer>
  );
}

// expose
Object.assign(window, { useT, useReveal, AlphaMark, Brand, LangSwitch, Nav, WhatsAppFAB, Footer, ImgSlot });
