/* ============================================================
   BY ANY MEANS GTA · Shared chrome + helpers
   Loaded before each page's own components file.
   Exposes globals via window for other babel scripts.
   ============================================================ */
const { useState, useEffect, useRef } = React;

/* ── Meta Pixel (both BAM GTA pixels, carried over from the GHL site) ──
   Loaded on every page via shared.jsx → fires PageView. Conversion events
   fire via window.bamTrack(event, params): 'Lead' on a form/booking submit
   (see submitLead) and 'Purchase' on a completed enrollment payment. */
(function () {
  if (window.fbq) return;
  !function (f, b, e, v, n, t, s) { if (f.fbq) return; n = f.fbq = function () { n.callMethod ? n.callMethod.apply(n, arguments) : n.queue.push(arguments); }; if (!f._fbq) f._fbq = n; n.push = n; n.loaded = !0; n.version = '2.0'; n.queue = []; t = b.createElement(e); t.async = !0; t.src = v; s = b.getElementsByTagName(e)[0]; s.parentNode.insertBefore(t, s); }(window, document, 'script', 'https://connect.facebook.net/en_US/fbevents.js');
  window.fbq('init', '1692167884521071');
  window.fbq('init', '854357739640091');
  window.fbq('track', 'PageView');
})();
window.bamTrack = function (event, params) { try { window.fbq && window.fbq('track', event, params || {}); } catch (e) { /* never break the page */ } };

const TRIAL = "free-trial.html";
const HOME = "index.html";
const ABOUT = "about.html";
const PROGRAMS = "programs.html";
const FAQ = "faq.html";
const CONTACT = "contact.html";
const P_ELEM = "elementary.html";
const P_HS = "high-school.html";
const P_ADAPT = "adapt.html";
const P_VA = "https://byanymeansbball.com/virtual-academy";

/* ---- SOCIAL ICONS (brand glyphs, currentColor) ---- */
const SOCIAL_PATHS = {
  ig: "M12 2.16c3.2 0 3.58.01 4.85.07 1.17.05 1.8.25 2.23.41.56.22.96.48 1.38.9.42.42.68.82.9 1.38.16.42.36 1.06.41 2.23.06 1.27.07 1.65.07 4.85s-.01 3.58-.07 4.85c-.05 1.17-.25 1.8-.41 2.23-.22.56-.48.96-.9 1.38-.42.42-.82.68-1.38.9-.42.16-1.06.36-2.23.41-1.27.06-1.65.07-4.85.07s-3.58-.01-4.85-.07c-1.17-.05-1.8-.25-2.23-.41-.56-.22-.96-.48-1.38-.9-.42-.42-.68-.82-.9-1.38-.16-.42-.36-1.06-.41-2.23-.06-1.27-.07-1.65-.07-4.85s.01-3.58.07-4.85c.05-1.17.25-1.8.41-2.23.22-.56.48-.96.9-1.38.42-.42.82-.68 1.38-.9.42-.16 1.06-.36 2.23-.41 1.27-.06 1.65-.07 4.85-.07M12 0C8.74 0 8.33.01 7.05.07 5.78.13 4.9.33 4.14.63c-.79.31-1.46.72-2.13 1.38C1.35 2.68.94 3.35.63 4.14.33 4.9.13 5.78.07 7.05.01 8.33 0 8.74 0 12s.01 3.67.07 4.95c.06 1.27.26 2.15.56 2.91.31.79.72 1.46 1.38 2.13.67.66 1.34 1.07 2.13 1.38.76.3 1.64.5 2.91.56C8.33 23.99 8.74 24 12 24s3.67-.01 4.95-.07c1.27-.06 2.15-.26 2.91-.56.79-.31 1.46-.72 2.13-1.38.66-.67 1.07-1.34 1.38-2.13.3-.76.5-1.64.56-2.91.06-1.28.07-1.69.07-4.95s-.01-3.67-.07-4.95c-.06-1.27-.26-2.15-.56-2.91-.31-.79-.72-1.46-1.38-2.13-.67-.66-1.34-1.07-2.13-1.38-.76-.3-1.64-.5-2.91-.56C15.67.01 15.26 0 12 0zm0 5.84A6.16 6.16 0 1 0 18.16 12 6.16 6.16 0 0 0 12 5.84zM12 16a4 4 0 1 1 4-4 4 4 0 0 1-4 4zm6.41-10.85a1.44 1.44 0 1 0 1.44 1.44 1.44 1.44 0 0 0-1.44-1.44z",
  fb: "M24 12.07C24 5.41 18.63 0 12 0S0 5.4 0 12.07C0 18.1 4.39 23.1 10.13 24v-8.44H7.08v-3.49h3.04V9.41c0-3.02 1.8-4.7 4.54-4.7 1.31 0 2.68.24 2.68.24v2.97h-1.5c-1.5 0-1.96.93-1.96 1.89v2.26h3.32l-.53 3.49h-2.8V24C19.62 23.1 24 18.1 24 12.07z",
  yt: "M23.5 6.19a3.02 3.02 0 0 0-2.12-2.14C19.5 3.55 12 3.55 12 3.55s-7.5 0-9.38.5A3.02 3.02 0 0 0 .5 6.19C0 8.07 0 12 0 12s0 3.93.5 5.81a3.02 3.02 0 0 0 2.12 2.14c1.88.5 9.38.5 9.38.5s7.5 0 9.38-.5a3.02 3.02 0 0 0 2.12-2.14C24 15.93 24 12 24 12s0-3.93-.5-5.81zM9.55 15.57V8.43L15.82 12z",
};
function SocialIcon({ name }) {
  return (
    <svg viewBox="0 0 24 24" width="18" height="18" fill="currentColor" aria-hidden="true" focusable="false">
      <path d={SOCIAL_PATHS[name]} />
    </svg>);
}

/* ---- scroll reveal: stagger children with .reveal ---- */
function useReveal() {
  const ref = useRef(null);
  useEffect(() => {
    const root = ref.current; if (!root) return;
    const nodes = root.classList.contains('reveal') ? [root] : Array.from(root.querySelectorAll('.reveal'));
    const io = new IntersectionObserver((es) => {
      es.forEach((e) => {
        if (!e.isIntersecting) return;
        const sibs = Array.from(e.target.parentElement.querySelectorAll(':scope > .reveal'));
        const i = Math.max(0, sibs.indexOf(e.target));
        e.target.style.transitionDelay = i * 80 + 'ms';
        e.target.classList.add('in');
        io.unobserve(e.target);
      });
    }, { threshold: 0.12, rootMargin: '0px 0px -8% 0px' });
    nodes.forEach((n) => io.observe(n));
    return () => io.disconnect();
  }, []);
  return ref;
}

/* ---- count-up stat ---- */
function StatNum({ value }) {
  const ref = useRef(null);
  useEffect(() => {
    const el = ref.current; if (!el) return;
    const m = String(value).match(/^(\d[\d,]*)(\.\d+)?(k\+?|m\+?|\+|%)?$/i);
    if (!m) { el.textContent = value; return; }
    const num = parseFloat((m[1] || '').replace(/,/g, '') + (m[2] || ''));
    const suf = m[3] || '';
    const fmt = (v) => {
      const isK = /k/i.test(suf), isM = /m/i.test(suf);
      const tail = /\+/.test(suf) ? '+' : /%/.test(suf) ? '%' : '';
      let body = isK ? Math.round(v) + 'K' : isM ? Math.round(v) + 'M' : Math.round(v).toLocaleString();
      return body + tail;
    };
    const io = new IntersectionObserver((es) => {
      es.forEach((e) => {
        if (!e.isIntersecting) return; io.unobserve(e.target);
        const dur = 1300, start = performance.now(), ease = (t) => 1 - Math.pow(1 - t, 3);
        const tick = (now) => {
          const t = Math.min(1, (now - start) / dur);
          el.textContent = fmt(num * ease(t));
          if (t < 1) requestAnimationFrame(tick); else el.textContent = value;
        };
        requestAnimationFrame(tick);
      });
    }, { threshold: 0.5 });
    io.observe(el);
    return () => io.disconnect();
  }, [value]);
  return <div className="stat__num" ref={ref}>{value}</div>;
}

/* ---- NAV ---- */
const PROGRAMS_DD = [
  { t: 'Elementary', d: 'Grade 5 to 8 · Skills + live play', href: P_ELEM },
  { t: 'High School', d: 'Grade 9 to 12 · Personalized dev', href: P_HS },
  { t: 'ADAPT Teams', d: 'Rep club · Practices + film', href: P_ADAPT },
  { t: 'Virtual Academy', d: 'Online · 150+ countries', href: P_VA }];

function Nav({ current }) {
  const [scrolled, setScrolled] = useState(false);
  const [open, setOpen] = useState(false);
  useEffect(() => {
    const on = () => setScrolled(window.scrollY > 24);
    window.addEventListener('scroll', on, { passive: true }); on();
    return () => window.removeEventListener('scroll', on);
  }, []);
  useEffect(() => { document.body.style.overflow = open ? 'hidden' : ''; }, [open]);
  const Item = (label, href, key) =>
    <div className={`nav__item${current === key ? ' is-current' : ''}`} key={key}><a href={href}>{label}</a></div>;

  return (
    <React.Fragment>
      <header className={`nav${scrolled ? ' is-scrolled' : ''}`}>
        <div className="container-wide nav__inner">
          <a className="nav__logo" href={HOME}>
            <span className="nav__mark" />
            <span className="nav__word">By Any Means <b>GTA</b></span>
          </a>
          <nav className="nav__links">
            {Item('Home', HOME, 'home')}
            {Item('About', ABOUT, 'about')}
            <div className={`nav__item nav__item--dd${current === 'programs' ? ' is-current' : ''}`}>
              <a href={PROGRAMS}>Programs <span className="nav__caret" /></a>
              <div className="nav__dd">
                {PROGRAMS_DD.map((p) =>
                  <a key={p.t} href={p.href}>
                    <span className="nav__dd-t">{p.t}</span>
                    <span className="nav__dd-d">{p.d}</span>
                  </a>
                )}
              </div>
            </div>
            {Item('ADAPT', P_ADAPT, 'adapt')}
            {Item('FAQ', FAQ, 'faq')}
            {Item('Contact', CONTACT, 'contact')}
          </nav>
          <a className="nav__cta" href={TRIAL}>Book a Trial</a>
          <button className="nav__burger" aria-label="Menu" onClick={() => setOpen(true)}>≡</button>
        </div>
      </header>
      <div className={`navdrawer${open ? ' is-open' : ''}`}>
        <div className="navdrawer__top">
          <span className="nav__word">By Any Means <b>GTA</b></span>
          <button className="navdrawer__close" aria-label="Close" onClick={() => setOpen(false)}>×</button>
        </div>
        <a href={HOME}>Home</a>
        <a href={ABOUT}>About</a>
        <a href={PROGRAMS}>Programs</a>
        {PROGRAMS_DD.map((p) => <a key={p.t} href={p.href}>{p.t}<small>{p.d}</small></a>)}
        <a href={FAQ}>FAQ</a>
        <a href={CONTACT}>Contact</a>
        <a className="btn btn--primary" href={TRIAL}>Book a Free Trial <span className="btn__arrow">→</span></a>
      </div>
    </React.Fragment>);
}

/* ---- CTA BAND ---- */
function CtaBand({ title, sub, secondaryLabel, secondaryHref }) {
  const ref = useReveal();
  return (
    <section className="ctaband" ref={ref}>
      <div className="ctaband__glow" aria-hidden="true" />
      <div className="container ctaband__inner reveal">
        <div className="ctaband__eyebrow eyebrow eyebrow--rule">Your journey starts here</div>
        <h2 className="ctaband__title" dangerouslySetInnerHTML={{ __html: title || 'Start your <em>journey.</em>' }} />
        <p className="ctaband__sub">{sub || 'One free trial. One session on the floor. See why families across the GTA are making the switch.'}</p>
        <div className="ctaband__ctas">
          <a className="btn btn--primary btn--lg" href={TRIAL}>Book a Free Trial <span className="btn__arrow">→</span></a>
          <a className="btn btn--ghost btn--lg" href={secondaryHref || ABOUT}>{secondaryLabel || 'Read Our Story'}</a>
        </div>
      </div>
    </section>);
}

/* ---- FOOTER ---- */
function Footer() {
  return (
    <footer className="footer">
      <div className="container-wide">
        <div className="footer__top">
          <div>
            <div className="footer__brand">
              <span className="footer__mark" />
              <span className="footer__word">By Any Means <b>GTA</b></span>
            </div>
            <p className="footer__tag">World-class basketball training in Oakville, Ontario. Building confidence, leadership, and skills, on and off the court.</p>
            <div className="footer__social">
              <a href="https://instagram.com/byanymeansgta" aria-label="Instagram"><SocialIcon name="ig" /></a>
              <a href="https://facebook.com/byanymeansgta" aria-label="Facebook"><SocialIcon name="fb" /></a>
              <a href="https://www.youtube.com/@ByAnyMeansBasketball" aria-label="YouTube"><SocialIcon name="yt" /></a>
            </div>
          </div>
          <div className="footer__col"><h4>Programs</h4><ul>
            <li><a href="https://byanymeanstoronto.ca/elementary">Elementary</a></li>
            <li><a href="https://byanymeanstoronto.ca/highschool">High School</a></li>
            <li><a href="https://byanymeanstoronto.ca/adapt">ADAPT Teams</a></li>
            <li><a href="https://byanymeansbball.com/virtual-academy">Virtual Academy</a></li>
          </ul></div>
          <div className="footer__col"><h4>Links</h4><ul>
            <li><a href={ABOUT}>About Us</a></li>
            <li><a href="https://byanymeanstoronto.ca/faq">FAQ</a></li>
            <li><a href="https://byanymeanstoronto.ca/posts">Blog</a></li>
            <li><a href="https://byanymeansgsc.com">Merch</a></li>
            <li><a href={TRIAL}>Free Trial</a></li>
          </ul></div>
          <div className="footer__col">
            <h4>Contact</h4>
            <address className="footer__contact">
              <b>By Any Means GTA</b>
              Serving the Greater Toronto Area<br />Oakville · Burlington · Mississauga<br /><br />
              <a href="tel:+12898166569">(289) 816-6569</a><br />
              <a href="mailto:info@byanymeanstoronto.ca">info@byanymeanstoronto.ca</a>
            </address>
          </div>
        </div>
        <div className="footer__bottom">
          <div>© 2026 By Any Means GTA. All Rights Reserved.</div>
          <div className="footer__legal">
            <a href="https://byanymeanstoronto.ca/terms">Terms &amp; Conditions</a>
            <a href="https://byanymeanstoronto.ca/privacy-policy">Privacy Policy</a>
          </div>
        </div>
      </div>
    </footer>);
}

/* ---- LEADS (portal API: saves to BAM database, syncs to GHL) ---- */
const LEADS_URL = "https://portal.byanymeansbusiness.com/api/website/leads";
const LEADS_CLIENT_ID = "39875f07-0a4b-4429-a201-2249bc1f24df"; // BAM GTA

async function submitLead({ formType, name, email, phone, fields, booking }) {
  const res = await fetch(LEADS_URL, {
    method: "POST",
    headers: { "Content-Type": "application/json" },
    body: JSON.stringify({
      client_id: LEADS_CLIENT_ID,
      form_type: formType,
      name: (name || "").trim(),
      email: (email || "").trim(),
      phone: (phone || "").trim() || undefined,
      fields: fields || {},
      ...(booking ? { booking } : {}),
      source_url: window.location.href,
    }),
  });
  const data = await res.json().catch(() => ({}));
  if (!res.ok || !data.ok) throw new Error(data.error || `Submission failed (${res.status})`);
  window.bamTrack && window.bamTrack("Lead", { content_name: formType || "lead" });
  return data;
}

Object.assign(window, { useReveal, StatNum, Nav, CtaBand, Footer, SocialIcon, TRIAL, HOME, ABOUT, PROGRAMS, FAQ, CONTACT, P_ELEM, P_HS, P_ADAPT, P_VA, PROGRAMS_DD, submitLead, LEADS_CLIENT_ID });
