// shared.jsx — single source of truth for chrome reused across pages:
// icons, scroll-reveal, decorative QR, Nav, Footer. Reads window.HOME for
// brand + nav + footer data. Loaded after home-content.jsx, before any
// page-specific section/app scripts. Functions are top-level declarations so
// they're globally reachable from other Babel scripts (separate scopes).
const { useState: shS, useEffect: shE, useRef: shR } = React;

// The exam platform owns auth. We link into it for login / profile / exam /
// logout, and it redirects back here with ?u=<name> so the nav can light up.
const APP = "https://app.atlas-ai.academy";

/* ---------- shared icons ---------- */
const AICONS = {
  arrow: (p) => <svg viewBox="0 0 24 24" fill="none" className="btn-arrow" {...p}><path d="M5 12h14M13 6l6 6-6 6" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" /></svg>,
  check: (p) => <svg viewBox="0 0 24 24" fill="none" {...p}><path d="M5 12.5l4.5 4.5L19 7.5" stroke="currentColor" strokeWidth="2.4" strokeLinecap="round" strokeLinejoin="round" /></svg>,
  x: (p) => <svg viewBox="0 0 24 24" fill="none" {...p}><path d="M6 6l12 12M18 6L6 18" stroke="currentColor" strokeWidth="2.2" strokeLinecap="round" /></svg>,
  search: (p) => <svg viewBox="0 0 24 24" fill="none" {...p}><circle cx="11" cy="11" r="7" stroke="currentColor" strokeWidth="1.8" /><path d="M16.5 16.5L21 21" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" /></svg>,
  scale: (p) => <svg viewBox="0 0 24 24" fill="none" {...p}><path d="M12 4v16M7 20h10M5 8h14M5 8l-2.5 5a3 3 0 006 0L10 8M19 8l2.5 5a3 3 0 01-6 0L14 8" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round" /></svg>,
  doc: (p) => <svg viewBox="0 0 24 24" fill="none" {...p}><path d="M7 3h7l5 5v13a0 0 0 01 0 0H7a1 1 0 01-1-1V4a1 1 0 011-1z" stroke="currentColor" strokeWidth="1.7" strokeLinejoin="round" /><path d="M14 3v5h5M9 13h6M9 17h6" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round" /></svg>,
  shield: (p) => <svg viewBox="0 0 24 24" fill="none" {...p}><path d="M12 3l7 3v5c0 4.5-3 7.8-7 9-4-1.2-7-4.5-7-9V6l7-3z" stroke="currentColor" strokeWidth="1.7" strokeLinejoin="round" /><path d="M9 12l2 2 4-4" stroke="currentColor" strokeWidth="1.7" strokeLinecap="round" strokeLinejoin="round" /></svg>,
  download: (p) => <svg viewBox="0 0 24 24" fill="none" {...p}><path d="M12 4v11m0 0l-4.5-4.5M12 15l4.5-4.5M5 19h14" stroke="currentColor" strokeWidth="1.9" strokeLinecap="round" strokeLinejoin="round" /></svg>,
  quote: (p) => <svg viewBox="0 0 24 24" fill="none" {...p}><path d="M9 7H6a2 2 0 00-2 2v3a2 2 0 002 2h2v2a3 3 0 01-3 3M20 7h-3a2 2 0 00-2 2v3a2 2 0 002 2h2v2a3 3 0 01-3 3" stroke="currentColor" strokeWidth="1.7" strokeLinecap="round" strokeLinejoin="round" /></svg>,
  panel: (p) => <svg viewBox="0 0 24 24" fill="none" {...p}><circle cx="7" cy="8" r="2.4" stroke="currentColor" strokeWidth="1.6" /><circle cx="17" cy="8" r="2.4" stroke="currentColor" strokeWidth="1.6" /><circle cx="12" cy="16" r="2.4" stroke="currentColor" strokeWidth="1.6" /><path d="M5 19c.4-1.6 1.6-2.4 2-2.4M19 19c-.4-1.6-1.6-2.4-2-2.4" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" /></svg>,
  lock: (p) => <svg viewBox="0 0 24 24" fill="none" {...p}><rect x="5" y="10" width="14" height="10" rx="2" stroke="currentColor" strokeWidth="1.7" /><path d="M8 10V7a4 4 0 018 0v3" stroke="currentColor" strokeWidth="1.7" strokeLinecap="round" /></svg>,
  open: (p) => <svg viewBox="0 0 24 24" fill="none" {...p}><path d="M5 12h14M12 5l7 7-7 7" stroke="currentColor" strokeWidth="1.7" strokeLinecap="round" strokeLinejoin="round" /></svg>
};
window.AICONS = AICONS;

/* ---------- scroll reveal (transform-only; never strands invisible) ---------- */
function useReveal() {
  shE(() => {
    const els = Array.from(document.querySelectorAll(".reveal:not(.in)"));
    if (!("IntersectionObserver" in window)) {els.forEach((e) => e.classList.add("in"));return;}
    const io = new IntersectionObserver((ents) => {
      ents.forEach((e) => {if (e.isIntersecting) {e.target.classList.add("in");io.unobserve(e.target);}});
    }, { threshold: 0.12, rootMargin: "0px 0px -6% 0px" });
    els.forEach((e) => io.observe(e));
    const fb = setTimeout(() => document.querySelectorAll(".reveal").forEach((e) => {e.classList.add("in");e.style.opacity = "1";e.style.transform = "none";}), 2600);
    return () => {io.disconnect();clearTimeout(fb);};
  }, []);
}

/* ---------- decorative QR (deterministic, not a real code) ---------- */
function QR() {
  const cells = [];
  const grid = 11;
  const seed = "10110100101001101011010010110100101101001011010010110100101101001011010010110100101101001011010010110100101101001";
  let k = 0;
  for (let y = 0; y < grid; y++) for (let x = 0; x < grid; x++, k++) {
    const corner = x < 3 && y < 3 || x > grid - 4 && y < 3 || x < 3 && y > grid - 4;
    if (corner) continue;
    if (seed[k % seed.length] === "1") cells.push(<rect key={k} x={x} y={y} width="1" height="1" />);
  }
  const finder = (fx, fy) =>
  <g key={fx + "-" + fy}>
      <rect x={fx} y={fy} width="3" height="3" fill="none" stroke="currentColor" strokeWidth="0.5" />
      <rect x={fx + 1} y={fy + 1} width="1" height="1" />
    </g>;

  return (
    <svg viewBox={`0 0 ${grid} ${grid}`} fill="currentColor" shapeRendering="crispEdges" aria-hidden="true">
      {cells}{finder(0, 0)}{finder(grid - 3, 0)}{finder(0, grid - 3)}
    </svg>);

}

/* ---------- NAV (shared across all pages) ----------
   Homepage: scroll-spy highlights the section in view.
   Subpages: set <html data-active-nav="standard"> to force-highlight one item
   and skip the scroll-spy. */
function Nav() {
  const A = window.HOME;
  const forced = typeof document !== "undefined" ? document.documentElement.getAttribute("data-active-nav") : null;
  const [scrolled, setScrolled] = shS(false);
  const [open, setOpen] = shS(false);
  const [active, setActive] = shS(forced || null);
  const [region, setRegion] = shS(false);
  const [atlasUser, setAtlasUser] = shS(() => { try { return localStorage.getItem('atlas_name') || ''; } catch { return ''; } });
  const close = () => setOpen(false);

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

  shE(() => {
    if (forced) return; // subpage: keep the forced item lit, no scroll-spy
    const secs = Array.from(document.querySelectorAll("[data-nav]"));
    if (!secs.length) return;
    const io = new IntersectionObserver((ents) => {
      ents.forEach((e) => {if (e.isIntersecting) setActive(e.target.getAttribute("data-nav"));});
    }, { rootMargin: "-45% 0px -50% 0px", threshold: 0 });
    secs.forEach((s) => io.observe(s));
    return () => io.disconnect();
  }, []);

  // Capture ?u=<name> handed back by the exam platform after login, store it,
  // then strip it from the URL so it doesn't linger / get shared.
  shE(() => {
    try {
      const p = new URLSearchParams(window.location.search);
      const u = p.get("u");
      if (u) {
        localStorage.setItem("atlas_name", u);
        setAtlasUser(u);
        p.delete("u");
        const qs = p.toString();
        window.history.replaceState({}, "", window.location.pathname + (qs ? "?" + qs : "") + window.location.hash);
      }
    } catch (e) {/* ignore */}
  }, []);

  // close region popover on outside click / Esc
  shE(() => {
    if (!region) return;
    const onDoc = (e) => {if (!e.target.closest(".region")) setRegion(false);};
    const onKey = (e) => {if (e.key === "Escape") setRegion(false);};
    document.addEventListener("click", onDoc);
    document.addEventListener("keydown", onKey);
    return () => {document.removeEventListener("click", onDoc);document.removeEventListener("keydown", onKey);};
  }, [region]);

  const renderMenu = (n) => (
    <div className="nav-menu" role="menu">
      <div className="nav-menu-sheet">
        <div className="nav-menu-wrap">
          <div className="nm-intro">
            <span className="nm-intro-title">{n.intro.title}</span>
            <p className="nm-intro-desc">{n.intro.desc}</p>
            {n.intro.price && <span className="nm-intro-price">{n.intro.price}</span>}
            {n.intro.cta &&
              <a className="nav-menu-cta" href={n.intro.cta.href}>
                {n.intro.cta.label}<span className="nmc-arrow" aria-hidden="true">→</span>
              </a>
            }
          </div>
          <div className="nm-cols">
            {n.columns.map((c) =>
              <div className="nm-col" key={c.title}>
                <span className="mega-group-title">{c.title}</span>
                <ul className="nav-menu-links">
                  {c.links.map(([label, href, desc]) => <li key={label}><a href={href} role="menuitem">{label}{desc && <span className="nm-link-desc">{desc}</span>}</a></li>)}
                </ul>
              </div>
            )}
          </div>
        </div>
      </div>
    </div>
  );

  const R = A.regions;

  // Auth links route through the exam platform; ?return= brings the user back
  // to this exact page (login adds ?u=name, logout clears the session).
  const ret = typeof window !== "undefined"
    ? encodeURIComponent(window.location.origin + window.location.pathname)
    : "";
  const loginHref = APP + "/login?return=" + ret;
  const logoutHref = APP + "/logout?return=" + ret;
  const doLogout = (e) => {
    e.preventDefault();
    try { localStorage.removeItem("atlas_name"); } catch (err) {/* ignore */}
    setAtlasUser("");
    window.location.href = logoutHref;
  };

  return (
    <header className={"nav" + (scrolled ? " scrolled" : "") + (open ? " menu-open" : "")}>
      <div className="wrap nav-inner">
        <a href="index.html" className="brand" onClick={close}>
          <span className="brand-mark">A</span>
          <span><span className="brand-name">{A.brand.name}</span><span className="brand-sub">{A.brand.sub}</span></span>
        </a>
        <nav className="nav-links">
          {A.nav.map((n) =>
          <div key={n.label} className="nav-item has-menu">
              <a className={"nav-link" + (active === n.id ? " active" : "")} href={n.href} onClick={(e) => e.preventDefault()}>
                {n.label}<span className="nav-caret" aria-hidden="true"></span>
              </a>
              {renderMenu(n)}
            </div>
          )}
        </nav>
        <div className="nav-right">
          <a href="verify.html" className="nav-verify"><span className="nv-dot" aria-hidden="true"></span>Verify a credential</a>
          {atlasUser
            ? <>
                <a href={APP + "/setup"} className="nav-login">Take exam</a>
                <a href={APP + "/profile"} className="nav-signup">Hi, {atlasUser.split(' ')[0]} →</a>
                <a href={logoutHref} className="nav-login" onClick={doLogout}>Log out</a>
              </>
            : <>
                <a href={loginHref} className="nav-login">Log in</a>
                <a href="https://app.atlas-ai.academy/register" className="nav-signup">Sign up</a>
              </>
          }
          <div className="region">
            <button className="region-btn" aria-label="Select region" aria-expanded={region} onClick={(e) => {e.stopPropagation();setRegion((v) => !v);}}>
              <svg className="region-globe" viewBox="0 0 24 24" fill="none" aria-hidden="true">
                <circle cx="12" cy="12" r="9" stroke="currentColor" strokeWidth="1.6" />
                <path d="M3 12h18M12 3c2.5 2.5 2.5 15 0 18M12 3c-2.5 2.5-2.5 15 0 18" stroke="currentColor" strokeWidth="1.6" />
              </svg>
              <span className="region-code">{R.current}</span>
              <span className="region-caret" aria-hidden="true"></span>
            </button>
            {region &&
            <div className="region-pop" role="menu">
                <div className="region-note">{R.note}</div>
                <ul className="region-list">
                  {R.items.map((it) =>
                <li key={it.code}>
                      <button
                    className={"region-item" + (it.live ? "" : " is-disabled") + (it.code === R.current ? " is-current" : "")}
                    disabled={!it.live}
                    aria-disabled={!it.live}
                    onClick={() => {if (it.live) setRegion(false);}}>
                    
                        {it.label}
                        {it.code === R.current && <span className="region-check" aria-hidden="true">✓</span>}
                      </button>
                    </li>
                )}
                </ul>
              </div>
            }
          </div>
        </div>
        <button className={"nav-toggle" + (open ? " open" : "")} aria-label="Menu" aria-expanded={open} onClick={() => setOpen((o) => !o)}>
          <span></span><span></span><span></span>
        </button>
      </div>
      <div className="mobile-menu">
        {A.nav.map((n) => {
          const links = [].concat(...n.columns.map((c) => c.links));
          return (
            <div className="m-group" key={n.label}>
              <a className="m-link m-link-head" href={n.href} onClick={close}>{n.label}</a>
              <div className="m-sublinks">
                {links.map(([label, href], i) =>
                <a key={label + i} className="m-sublink" href={href} onClick={close}>{label}</a>
                )}
                {n.intro && n.intro.cta && <a className="m-sublink m-sub-cta" href={n.intro.cta.href} onClick={close}>{n.intro.cta.label} →</a>}
              </div>
            </div>);

        })}
        <a className="m-link m-verify" href="verify.html" onClick={close}><span className="nv-dot" aria-hidden="true"></span>Verify a credential</a>
        {atlasUser
          ? <>
              <a className="m-link" href={APP + "/profile"} onClick={close}>My Account ({atlasUser.split(' ')[0]})</a>
              <a className="m-link" href={APP + "/setup"} onClick={close}>Take exam</a>
              <a className="m-link" href={logoutHref} onClick={doLogout}>Log out</a>
            </>
          : <>
              <a className="m-link" href={loginHref} onClick={close}>Log in</a>
              <a className="m-link" href="https://app.atlas-ai.academy/register" onClick={close}>Sign up</a>
            </>
        }
        <a href={APP + "/setup"} className="btn btn-primary" onClick={close}>Get certified</a>
        <div className="m-region-note">{A.regions.note} — {A.regions.current} only</div>
      </div>
    </header>);

}

/* ---------- FOOTER (shared across all pages) ---------- */
function Footer() {
  const HC = window.HOME;
  const f = HC.footer;
  return (
    <footer className="footer">
      <div className="wrap">
        <div className="footer-top">
          <div className="footer-brand">
            <a href="index.html" className="brand">
              <span className="brand-mark">A</span>
              <span><span className="brand-name">{HC.brand.name}</span><span className="brand-sub">{HC.brand.sub}</span></span>
            </a>
            <p className="footer-blurb">{f.blurb}</p>
          </div>
          {f.columns.map((col) =>
          <div className="footer-col" key={col.title}>
              <h4>{col.title}</h4>
              <ul>{col.links.map(([l, href]) => <li key={l}><a href={href}>{l}</a></li>)}</ul>
            </div>
          )}
        </div>
        <div className="footer-license" style={{ marginTop: 24, paddingTop: 18, borderTop: "1px solid rgba(128,128,128,.28)", fontSize: 12.5, lineHeight: 1.65, opacity: .9 }}>
          This product or portions thereof was developed at and/or is manufactured under license from Carnegie Mellon University.
        </div>
        <div className="footer-bottom">
          <span>© 2026 {HC.brand.full}, Inc. · Portions © 2026 Carnegie Mellon University. All rights reserved. · Independent certification body.</span>
          <div className="fb-links"><a href="verify.html">Verify a credential</a><a href="standard.html">The standard</a><a href="#">Privacy</a></div>
        </div>
      </div>
    </footer>);

}

/* ---------- Breadcrumb (TOEFL/ETS-style reference-page trail) ---------- */
function Breadcrumb({ trail }) {
  // trail: array of [label, href] — last item is the current page (no link).
  return (
    <nav className="crumb" aria-label="Breadcrumb">
      <div className="wrap crumb-inner">
        <a href="index.html" className="crumb-link">Home</a>
        {trail.map((it, i) => {
          const last = i === trail.length - 1;
          return (
            <React.Fragment key={it[0]}>
              <span className="crumb-sep" aria-hidden="true">›</span>
              {last || !it[1]
                ? <span className="crumb-here" aria-current="page">{it[0]}</span>
                : <a href={it[1]} className="crumb-link">{it[0]}</a>}
            </React.Fragment>
          );
        })}
      </div>
    </nav>
  );
}

/* ---------- "On this page" sticky jump-nav with scroll-spy (ETS reference layout) ---------- */
function OnThisPage({ items, title }) {
  // items: array of { id, label }
  const [active, setActive] = shS(items[0] && items[0].id);
  shE(() => {
    const secs = items.map((it) => document.getElementById(it.id)).filter(Boolean);
    if (!secs.length) return;
    const io = new IntersectionObserver((entries) => {
      entries.forEach((e) => { if (e.isIntersecting) setActive(e.target.id); });
    }, { rootMargin: "-45% 0px -50% 0px", threshold: 0 });
    secs.forEach((s) => io.observe(s));
    return () => io.disconnect();
  }, []);
  return (
    <nav className="otp" aria-label={title || "On this page"}>
      <ul className="otp-list">
        {items.map((it) => (
          <li key={it.id}>
            <a href={"#" + it.id} className={"otp-link" + (active === it.id ? " active" : "")}>{it.label}</a>
          </li>
        ))}
      </ul>
    </nav>
  );
}

/* ---------- Role-switch banner (org pages → individual) ---------- */
function RoleBanner() {
  return (
    <div className="role-banner">
      <div className="wrap role-banner-inner">
        <span>This page is for teams and organizations. Looking to get certified yourself?</span>
        <a href="https://app.atlas-ai.academy/register" className="role-banner-link">Get certified as an individual <AICONS.arrow style={{ width: 15, height: 15 }} /></a>
      </div>
    </div>
  );
}

/* ---------- Team upsell banner (individual pages → org pricing) ---------- */
function TeamBanner() {
  return (
    <div className="team-banner">
      <div className="wrap team-banner-inner">
        <span>Buying for your team or organization?</span>
        <a href="org-pricing.html" className="team-banner-link">View team plans <AICONS.arrow style={{ width: 15, height: 15 }} /></a>
      </div>
    </div>
  );
}

Object.assign(window, { useReveal, QR, Nav, Footer, Breadcrumb, OnThisPage, RoleBanner, TeamBanner });

/* ---------- six competency-dimension icons (index-aligned, verbatim site-wide) ----------
   Shared so standard.html renders the same duotone marks as the homepage. */
window.DIM_ICONS = [
<g key="i"><path d="M12 6.4C9.4 4.9 6.8 4.7 4.3 5.1V17.9c2.5-.4 5.1-.2 7.7 1.3 2.6-1.5 5.2-1.7 7.7-1.3V5.1C17.2 4.7 14.6 4.9 12 6.4Z" fill="currentColor" fillOpacity=".16" /><path d="M12 6.4C9.4 4.9 6.8 4.7 4.3 5.1V17.9c2.5-.4 5.1-.2 7.7 1.3 2.6-1.5 5.2-1.7 7.7-1.3V5.1C17.2 4.7 14.6 4.9 12 6.4Zm0 0v12.8" /></g>,
<g key="i"><path d="M4 7A2.5 2.5 0 0 1 6.5 4.5h11A2.5 2.5 0 0 1 20 7v5a2.5 2.5 0 0 1-2.5 2.5H10l-4 3.3V14.5H6.5A2.5 2.5 0 0 1 4 12Z" fill="currentColor" fillOpacity=".16" /><path d="M4 7A2.5 2.5 0 0 1 6.5 4.5h11A2.5 2.5 0 0 1 20 7v5a2.5 2.5 0 0 1-2.5 2.5H10l-4 3.3V14.5H6.5A2.5 2.5 0 0 1 4 12Z" /><path d="M8.5 9.5h.01M12 9.5h.01M15.5 9.5h.01" /></g>,
<g key="i"><circle cx="10.5" cy="10.5" r="6" fill="currentColor" fillOpacity=".16" /><circle cx="10.5" cy="10.5" r="6" /><path d="M19.5 19.5l-4-4M8 10.6l1.9 1.9 3.6-3.8" /></g>,
<g key="i"><path d="M5.4 13h2.2v6H5.4zM10.9 7h2.2v12h-2.2zM16.4 10h2.2v9h-2.2z" fill="currentColor" fillOpacity=".16" /><path d="M4 19.2h16M6.5 19V13M12 19V7M17.5 19v-9" /></g>,
<g key="i"><circle cx="6" cy="6.5" r="2.6" fill="currentColor" fillOpacity=".16" /><circle cx="18" cy="6.5" r="2.6" fill="currentColor" fillOpacity=".16" /><circle cx="12" cy="17.5" r="2.6" fill="currentColor" fillOpacity=".16" /><path d="M8.6 6.5h6.8M7.3 8.7l3.5 6.6M16.7 8.7l-3.5 6.6" /><circle cx="6" cy="6.5" r="2.6" /><circle cx="18" cy="6.5" r="2.6" /><circle cx="12" cy="17.5" r="2.6" /></g>,
<g key="i"><path d="M12 3.4l7.2 2.9V11c0 4.5-3.1 7.8-7.2 9-4.1-1.2-7.2-4.5-7.2-9V6.3Z" fill="currentColor" fillOpacity=".16" /><path d="M12 3.4l7.2 2.9V11c0 4.5-3.1 7.8-7.2 9-4.1-1.2-7.2-4.5-7.2-9V6.3Z" /><path d="M9 11.3l2 2 4-4" /></g>];