/* global React, ReactDOM */
const { useState, useEffect, useCallback } = React;

/* Tweaks context - lets page modules read live layout choices */
const TweaksContext = React.createContext({});
window.TweaksContext = TweaksContext;

const TWEAK_DEFAULTS = /*EDITMODE-BEGIN*/{
  "homeMood": "light",
  "pillarsLayout": "mosaic",
  "fieldLayout": "grid"
}/*EDITMODE-END*/;

/* =========================================================
   Router - hash-based, supports back/forward
   ========================================================= */
const ROUTES = [
  { path: '/',              label: 'Home',         hidden: true,  component: () => window.PageHome() },
  { path: '/capabilities',  label: 'Capabilities', component: () => window.PageCapabilities() },
  { path: '/facility',      label: 'Facility',     component: () => window.PageFacility() },
  { path: '/partnerships',  label: 'Partnerships', component: () => window.PagePartnerships() },
  { path: '/about',         label: 'About',        component: () => window.PageAbout() },
  { path: '/team',          label: 'Team',         component: () => window.PageTeam() },
  { path: '/careers',       label: 'Careers',      component: () => window.PageCareers() },
  { path: '/news',          label: 'News',         component: () => window.PageNews() },
  { path: '/contact',       label: 'Contact',      hidden: true, component: () => window.PageContact() },
];

function useRoute() {
  const parse = () => {
    const h = window.location.hash.replace(/^#/, '') || '/';
    return h.startsWith('/') ? h : '/' + h;
  };
  const [route, setRoute] = useState(parse());
  useEffect(() => {
    const onChange = () => {
      setRoute(parse());
      window.scrollTo({ top: 0, behavior: 'instant' });
    };
    window.addEventListener('hashchange', onChange);
    return () => window.removeEventListener('hashchange', onChange);
  }, []);
  const navigate = useCallback((path) => {
    if (path === route) return;
    window.location.hash = path;
  }, [route]);
  return [route, navigate];
}

/* Link component - hash navigation */
function Link({ to, className, children, ...rest }) {
  const onClick = (e) => {
    e.preventDefault();
    window.location.hash = to;
  };
  return (
    <a href={'#' + to} className={className} onClick={onClick} {...rest}>{children}</a>
  );
}

/* =========================================================
   Nav
   ========================================================= */
function Nav({ route }) {
  const [scrolled, setScrolled] = useState(false);
  const [open, setOpen] = useState(false);
  useEffect(() => {
    const onScroll = () => setScrolled(window.scrollY > 30);
    onScroll();
    window.addEventListener('scroll', onScroll, { passive: true });
    return () => window.removeEventListener('scroll', onScroll);
  }, []);
  useEffect(() => { setOpen(false); }, [route]);

  const visibleRoutes = ROUTES.filter(r => !r.hidden);
  const isActive = (path) => path === route || (path !== '/' && route.startsWith(path));

  return (
    <>
      <header className={'nav' + (scrolled ? ' nav--scrolled' : '')}>
        <div className="wrap nav__inner">
          <Link to="/" className="nav__logo" aria-label="HFI Pyrotechnics, Home">
            <img src={window.A('logo-pyro-colour.png')} alt="HFI Pyrotechnics" />
          </Link>
          <ul className="nav__links">
            {visibleRoutes.map(r => (
              <li key={r.path}>
                <Link to={r.path} className={isActive(r.path) ? 'is-active' : ''}>{r.label}</Link>
              </li>
            ))}
          </ul>
          <div className="nav__cta">
            <Link to="/contact" className="btn btn--primary">Contact <span className="arr">→</span></Link>
            <button className="nav__burger" onClick={() => setOpen(o => !o)} aria-label="Menu">
              <span></span><span></span><span></span>
            </button>
          </div>
        </div>
      </header>

      <nav className={'drawer' + (open ? ' is-open' : '')}>
        {visibleRoutes.map(r => (
          <Link key={r.path} to={r.path} className={isActive(r.path) ? 'is-active' : ''}>
            {r.label}
          </Link>
        ))}
      </nav>
    </>
  );
}

/* =========================================================
   Footer
   ========================================================= */
function Footer() {
  return (
    <footer className="footer">
      <div className="wrap">
        <div className="footer__top">
          <div>
            <div className="footer__logo">
              <img src={window.A('logo-pyro-colour.png')} alt="HFI Pyrotechnics" />
            </div>
            <p className="footer__tag">
              Equipping the forces that protect Canada and its allies since 1873.
            </p>
          </div>
          <div className="footer__grid">
            <div className="footer__col">
              <h4>Navigate</h4>
              <ul>
                <li><Link to="/capabilities">Capabilities</Link></li>
                <li><Link to="/facility">Facility</Link></li>
                <li><Link to="/partnerships">Partnerships</Link></li>
                <li><Link to="/about">About</Link></li>
                <li><Link to="/team">Team</Link></li>
                <li><Link to="/careers">Careers</Link></li>
                <li><Link to="/news">News</Link></li>
              </ul>
            </div>
            <div className="footer__col">
              <h4>Headquarters</h4>
              <p>3322 Hands Road</p>
              <p>Prescott, Ontario  K0E 1T0</p>
              <p>Canada</p>
              <p style={{ marginTop: 18 }}>
                <a href="mailto:sales@hfipyrotechnics.com">sales@hfipyrotechnics.com</a>
              </p>
              <p><a href="tel:+16139252832">+1 613 925-2832</a></p>
            </div>
            <div className="footer__col">
              <h4>Engage</h4>
              <ul>
                <li><Link to="/contact">Start a conversation</Link></li>
                <li><a href="mailto:careers@hfipyrotechnics.com">Join the team</a></li>
                <li><a href="https://www.linkedin.com/company/hfi-pyrotechnics/posts/?feedView=all" target="_blank" rel="noreferrer">LinkedIn ↗</a></li>
              </ul>
            </div>
          </div>
        </div>
        <div className="footer__bottom">
          <div>
            <span className="red-dot"></span>
            © 2026 HFI Pyrotechnics Inc. All rights reserved.
            <span className="footer__credit">Select imagery © His Majesty the King in Right of Canada, Canadian Armed Forces, Combat Camera.</span>
          </div>
          <div className="footer__bottom-right">
            <span className="footer__locale">Township of Edwardsburgh Cardinal, Ontario · Canada · Est. 1873</span>
            <a
              className="footer__social"
              href="https://www.linkedin.com/company/hfi-pyrotechnics/posts/?feedView=all"
              target="_blank"
              rel="noreferrer"
              aria-label="HFI Pyrotechnics on LinkedIn"
            >
              <svg viewBox="0 0 24 24" width="16" height="16" aria-hidden="true" focusable="false">
                <path fill="currentColor" d="M20.45 20.45h-3.55v-5.57c0-1.33-.03-3.04-1.85-3.04-1.85 0-2.14 1.45-2.14 2.94v5.67H9.36V9h3.41v1.56h.05c.47-.9 1.64-1.85 3.37-1.85 3.6 0 4.27 2.37 4.27 5.46v6.28zM5.34 7.43a2.06 2.06 0 1 1 0-4.12 2.06 2.06 0 0 1 0 4.12zM7.12 20.45H3.56V9h3.56v11.45z"/>
              </svg>
              <span>LinkedIn</span>
            </a>
          </div>
        </div>
      </div>
    </footer>
  );
}

/* =========================================================
   FadeIn - intersection observer reveal
   ========================================================= */
function FadeIn({ children, delay = 0, className = '', as = 'div' }) {
  const [visible, setVisible] = useState(false);
  const ref = React.useRef(null);
  useEffect(() => {
    const el = ref.current;
    if (!el) return;
    const obs = new IntersectionObserver((entries) => {
      entries.forEach(e => {
        if (e.isIntersecting) {
          setTimeout(() => setVisible(true), delay);
          obs.unobserve(el);
        }
      });
    }, { threshold: 0.12 });
    obs.observe(el);
    return () => obs.disconnect();
  }, [delay]);
  const Tag = as;
  return (
    <Tag ref={ref} className={`fade-in ${visible ? 'is-visible' : ''} ${className}`}>
      {children}
    </Tag>
  );
}

/* =========================================================
   Reusable section pieces
   ========================================================= */

function SectionHead({ eyebrow, title, lede, align }) {
  return (
    <div className="section-head" style={align === 'center' ? { gridTemplateColumns: '1fr', textAlign: 'center', maxWidth: 720, margin: '0 auto 70px' } : null}>
      <div>
        {eyebrow && <div className="eyebrow">{eyebrow}</div>}
        <h2 className="h-1">{title}</h2>
      </div>
      {lede && <div className="section-head__right body body-lg">{lede}</div>}
    </div>
  );
}

function ClosingCTA({ headline, body, ctaText = 'Get in Touch', ctaTo = '/contact' }) {
  return (
    <section className="closing">
      <div className="wrap closing__inner">
        <img
          src={window.A('logo-pyro-colour.png')}
          alt="HFI Pyrotechnics"
          className="closing__brand"
        />
        <h2 className="h-1">{headline}</h2>
        {body && <p>{body}</p>}
        <Link to={ctaTo} className="btn btn--primary">{ctaText} <span className="arr">→</span></Link>
      </div>
    </section>
  );
}

/* HeroBrand - small banded HFI Pyrotechnics lockup placed above page-hero eyebrows */
function HeroBrand({ tone = 'dark' }) {
  return (
    <div
      className={'hero__brand' + (tone === 'light' ? ' hero__brand--light' : '')}
      aria-label="HFI Pyrotechnics"
    >
      <img src={window.A('logo-pyro-white.png')} alt="HFI Pyrotechnics" />
    </div>
  );
}

/* =========================================================
   App
   ========================================================= */
function App() {
  const [route] = useRoute();
  const [t, setTweak] = window.useTweaks(TWEAK_DEFAULTS);
  const match = ROUTES.find(r => r.path === route)
    || ROUTES.find(r => r.path !== '/' && route.startsWith(r.path + '/'))
    || ROUTES[0];
  const Page = match.component;

  const MOODS = [
    { value: 'light', label: 'Light: paper-forward, lifts the gloom' },
    { value: 'balanced', label: 'Balanced: darker, more contrast' },
  ];
  const PILLARS = [
    { value: 'mosaic', label: 'Mosaic: tall feature + stacked pair' },
    { value: 'editorial', label: 'Editorial: alternating image rows' },
    { value: 'grid', label: 'Grid: three equal tiles (original)' },
  ];
  const FIELD = [
    { value: 'cinema', label: 'Cinema: wide banner + supporting pair' },
    { value: 'triptych', label: 'Triptych: unequal full-bleed slices' },
    { value: 'grid', label: 'Grid: three equal cells (original)' },
  ];

  return (
    <TweaksContext.Provider value={t}>
      <Nav route={route} />
      <main>
        <Page />
      </main>
      <Footer />
      <window.TweaksPanel title="Tweaks">
        <window.TweakSection label="Home page mood" />
        <window.TweakSelect
          label="Mood"
          value={t.homeMood}
          options={MOODS}
          onChange={(v) => setTweak('homeMood', v)}
        />
        <window.TweakSection label="“What We Do” layout" />
        <window.TweakSelect
          label="Section"
          value={t.pillarsLayout}
          options={PILLARS}
          onChange={(v) => setTweak('pillarsLayout', v)}
        />
        <window.TweakSection label="“Operational Set” layout" />
        <window.TweakSelect
          label="Section"
          value={t.fieldLayout}
          options={FIELD}
          onChange={(v) => setTweak('fieldLayout', v)}
        />
      </window.TweaksPanel>
    </TweaksContext.Provider>
  );
}

/* Export shared helpers for page modules */
Object.assign(window, { Link, FadeIn, SectionHead, ClosingCTA, HeroBrand });

/* Mount */
ReactDOM.createRoot(document.getElementById('root')).render(<App />);
