/* CloudAurum shared components
   Pure JSX — load via Babel before pages.jsx + app.jsx */

const { useState, useEffect, useRef, useCallback } = React;

/* -------------------------------------------------------
   BOOKING ENDPOINTS
   -------------------------------------------------------
   These are the only two URLs to update at hard-launch.

   Two-state funnel architecture (clarified 2026-05-28):

   SOFT-LAUNCH (first 3 testimonial-trade clients, family-network only):
     BOOKING_URL currently points to a Calendly event with NO Stripe.
     Workflow Assessment is delivered FREE in exchange for testimonial
     and case-study rights. Soft-launch traffic is direct-link only
     (Mark sends the Calendly URL via DM/SMS/email); the site button
     also routes here for now.

   HARD-LAUNCH (everyone after, including all site traffic):
     Replace BOOKING_URL with a Stripe Payment Link whose success_url
     is https://cloudaurum.com/welcome. Stripe handles the $999 payment,
     then the buyer lands on /welcome to schedule via Calendly embed.
     This is the production funnel for both warm and cold leads — the
     financial commitment qualifies the prospect AND Stripe Checkout
     reads as more premium than embedded card-collection in Calendly.

   CALENDLY_POSTPAY_URL: the Calendly event embedded on the Welcome page.
     - Soft-launch: not yet reachable (no buyers land on /welcome).
     - Hard-launch: duplicate the Calendly Discovery Call event with
       NO payment requirement (payment already happened via Stripe
       upstream) and paste that URL here.

   Regulated-vertical Pre-Call Confidentiality & Scope Notice (HelloSign):
     Currently triggered manually by Mark when a dental/medical/legal/
     financial-advisory booking arrives. Full automation (Calendly
     webhook → Make.com → conditional HelloSign dispatch by industry
     intake answer) waits on lawyer-finalized doc + HelloSign template
     build.
------------------------------------------------------- */
const BOOKING_URL = 'https://calendly.com/mark-cloudaurum/workflow-assessment-discovery-call';
const CALENDLY_POSTPAY_URL = 'https://calendly.com/mark-cloudaurum/workflow-assessment-discovery-call';

/* -------------------------------------------------------
   Router (history API — uses pushState + popstate so URLs
   are crawlable by search engines and AI agents.
   Requires SPA fallback at the host: see /_redirects.
   ------------------------------------------------------- */
function getRoute() {
  const p = window.location.pathname.replace(/^\//, '');
  const seg = (p || 'home').split('/')[0];
  return ['home', 'services', 'about', 'contact', 'welcome', 'privacy', 'terms'].includes(seg) ? seg : 'home';
}

function useRoute() {
  const [route, setRoute] = useState(getRoute());
  useEffect(() => {
    const on = () => {
      setRoute(getRoute());
      window.scrollTo({ top: 0, behavior: 'instant' in window ? 'instant' : 'auto' });
    };
    window.addEventListener('popstate', on);
    return () => window.removeEventListener('popstate', on);
  }, []);
  return route;
}

function navigate(to) {
  const url = to === 'home' ? '/' : '/' + to;
  if (window.location.pathname === url) return;
  window.history.pushState({}, '', url);
  window.dispatchEvent(new PopStateEvent('popstate'));
}

/* Link that uses our history-API router */
function CALink({ to, children, className, style, label, onClick }) {
  const handle = (e) => {
    e.preventDefault();
    if (onClick) onClick();
    navigate(to);
  };
  const href = to === 'home' ? '/' : '/' + to;
  return (
    <a href={href}
    className={className}
    style={style}
    aria-label={label}
    onClick={handle}>
      {children}
    </a>);

}

/* -------------------------------------------------------
   Reveal-on-scroll wrapper
   ------------------------------------------------------- */
function Reveal({ children, delay = 0, as = 'div', className = '', style = {} }) {
  const ref = useRef(null);
  const [visible, setVisible] = useState(false);
  useEffect(() => {
    const reduced = window.matchMedia('(prefers-reduced-motion: reduce)').matches;
    if (reduced) {setVisible(true);return;}
    const el = ref.current;
    if (!el || !('IntersectionObserver' in window)) {setVisible(true);return;}
    const io = new IntersectionObserver((entries) => {
      entries.forEach((e) => {
        if (e.isIntersecting) {setVisible(true);io.unobserve(e.target);}
      });
    }, { threshold: 0.12, rootMargin: '0px 0px -60px 0px' });
    io.observe(el);
    return () => io.disconnect();
  }, []);
  const Tag = as;
  return (
    <Tag ref={ref}
    className={(visible ? 'is-visible ' : '') + className}
    data-reveal=""
    data-reveal-delay={delay ? String(delay) : undefined}
    style={style}>
      {children}
    </Tag>);

}

/* -------------------------------------------------------
   Wordmark — pure Cormorant Garamond, gold A on Aurum
   ------------------------------------------------------- */
function Wordmark({ ariaLabel = 'CloudAurum home', onClick, size }) {
  const style = size ? { fontSize: size + 'px' } : undefined;
  return (
    <CALink to="home" className="logo-link" label={ariaLabel} onClick={onClick} style={style}>
      Cloud<span className="a-accent">A</span>urum
    </CALink>);

}

/* -------------------------------------------------------
   Nav
   ------------------------------------------------------- */
function Nav({ route }) {
  const [scrolled, setScrolled] = useState(false);
  const [open, setOpen] = useState(false);

  useEffect(() => {
    const on = () => setScrolled(window.scrollY > 60);
    on();
    window.addEventListener('scroll', on, { passive: true });
    return () => window.removeEventListener('scroll', on);
  }, []);

  // Nav goes dark when hero (only on home) is in view
  const [overDark, setOverDark] = useState(route === 'home');
  useEffect(() => {
    if (route !== 'home') {setOverDark(false);return;}
    const hero = document.querySelector('.hero');
    if (!hero || !('IntersectionObserver' in window)) {setOverDark(true);return;}
    const io = new IntersectionObserver((entries) => {
      entries.forEach((e) => setOverDark(e.intersectionRatio > 0.3));
    }, { threshold: [0, 0.3, 0.6, 1] });
    io.observe(hero);
    return () => io.disconnect();
  }, [route]);

  // Close mobile on route change
  useEffect(() => {setOpen(false);}, [route]);

  // Body scroll lock when drawer open
  useEffect(() => {
    if (open) {
      document.body.classList.add('nav-open');
    } else {
      document.body.classList.remove('nav-open');
    }
    return () => document.body.classList.remove('nav-open');
  }, [open]);

  // ESC to close
  useEffect(() => {
    if (!open) return;
    const onKey = (e) => {if (e.key === 'Escape') setOpen(false);};
    window.addEventListener('keydown', onKey);
    return () => window.removeEventListener('keydown', onKey);
  }, [open]);

  const cls = ['nav', scrolled ? 'scrolled' : '', overDark ? 'on-dark-nav' : ''].filter(Boolean).join(' ');
  const linkCls = (r) => 'nav-link' + (route === r ? ' is-active' : '');

  return (
    <nav className={cls}>
      <div className="container nav-inner">
        <Wordmark />
        <div className={'nav-links' + (open ? ' open' : '')}>
          <CALink to="services" className={linkCls('services')}>Services</CALink>
          <CALink to="about" className={linkCls('about')}>About</CALink>
          <CALink to="contact" className={linkCls('contact')}>Contact</CALink>
          <CALink to="contact" className="nav-cta">Start Assessment</CALink>
        </div>
        <button className={'nav-mobile' + (open ? ' active' : '')}
        aria-label={open ? 'Close menu' : 'Open menu'}
        aria-expanded={open}
        onClick={() => setOpen(!open)}>
          <span></span><span></span><span></span>
        </button>
      </div>
    </nav>);

}

/* -------------------------------------------------------
   Hero atmosphere + particle drift
   ------------------------------------------------------- */
function HeroAtmosphere() {
  const ref = useRef(null);
  useEffect(() => {
    const reduced = window.matchMedia('(prefers-reduced-motion: reduce)').matches;
    if (reduced || !ref.current) return;
    const host = ref.current;
    host.innerHTML = '';
    // Adaptive particle count: 32 desktop, 12 tablet/large mobile, 0 small mobile
    const w = window.innerWidth;
    let count = 32;
    if (w < 480) count = 0;else
    if (w < 768) count = 8;else
    if (w < 1024) count = 16;
    if (count === 0) return;
    const frag = document.createDocumentFragment();
    for (let i = 0; i < count; i++) {
      const p = document.createElement('span');
      const size = 1 + Math.random() * 2.6;
      const left = Math.random() * 100;
      const top = Math.random() * 100;
      const dur = 14 + Math.random() * 22;
      const delay = -Math.random() * dur;
      const opacity = 0.3 + Math.random() * 0.55;
      p.style.cssText = `
        position:absolute; left:${left}%; top:${top}%;
        width:${size}px; height:${size}px;
        background: radial-gradient(circle, rgba(232, 201, 126, ${opacity}) 0%, rgba(232, 201, 126, 0) 70%);
        border-radius:50%;
        animation: particleDrift ${dur}s linear ${delay}s infinite;
        pointer-events:none;
      `;
      frag.appendChild(p);
    }
    host.appendChild(frag);
  }, []);
  return (
    <>
      <div className="hero-atmosphere" aria-hidden="true"></div>
      <div className="hero-particles" ref={ref} aria-hidden="true"></div>
    </>);

}

/* -------------------------------------------------------
   CTA Band — appears at bottom of every page
   ------------------------------------------------------- */
function CTABand({ eyebrow, headline, italic, body, primaryLabel = 'Start your Workflow Assessment', secondaryLabel, note }) {
  return (
    <section className="cta-band">
      <div className="container">
        <Reveal>
          <span className="eyebrow">{eyebrow}</span>
          <h2 className="mt-4">
            {headline}{' '}
            <em className="display-italic" style={{ color: 'var(--gold-light)' }}>{italic}</em>
          </h2>
          <p className="lead">{body}</p>
          <div className="hero-actions mt-4">
            <CALink to="contact" className="btn btn-gold">{primaryLabel}</CALink>
            {secondaryLabel && <CALink to="services" className="btn-secondary">{secondaryLabel} →</CALink>}
          </div>
          {note && <p className="note">{note}</p>}
        </Reveal>
      </div>
    </section>);

}

/* -------------------------------------------------------
   Footer
   ------------------------------------------------------- */
function Footer() {
  return (
    <footer className="footer">
      <div className="container">
        <div className="footer-inner">
          <div className="footer-brand">
            <Wordmark size={32} />
            <p className="footer-tagline">Outcome-driven consulting for businesses ready to compound.</p>
            <p className="footer-entity">A Layered Media LLC company.</p>
          </div>
          <div className="footer-meta">
            <div className="footer-meta-group">
              <h5>Navigate</h5>
              <CALink to="services">Services</CALink>
              <CALink to="about">About</CALink>
              <CALink to="contact">Contact</CALink>
            </div>
            <div className="footer-meta-group">
              <h5>Contact</h5>
              <a href="mailto:hello@cloudaurum.com">hello@cloudaurum.com</a>
              <span className="item">Dallas-Fort Worth, TX</span>
            </div>
            <div className="footer-meta-group">
              <h5>Legal</h5>
              <CALink to="privacy">Privacy Policy</CALink>
              <CALink to="terms">Terms of Service</CALink>
            </div>
          </div>
        </div>
        <div className="footer-bottom">
          <span>© 2026 Layered Media LLC. All rights reserved.</span>
          <span className="caption">Aurum · Element 79 · Latin for gold</span>
        </div>
      </div>
    </footer>);

}

/* -------------------------------------------------------
   Eyebrow with hairline rule (used in page heros)
   ------------------------------------------------------- */
function EyebrowRule({ children, className = '', style = {} }) {
  return (
    <span className={'eyebrow eyebrow-rule ' + className} style={style}>{children}</span>);

}

/* -------------------------------------------------------
   Page hero (shared by services/about/contact)
   ------------------------------------------------------- */
function PageHero({ eyebrow, children, lead }) {
  return (
    <section className="page-hero">
      <div className="container">
        <Reveal as="span" className="eyebrow">{eyebrow}</Reveal>
        <Reveal delay={1}><h1 className="mt-4">{children}</h1></Reveal>
        <Reveal delay={2}><p className="lead">{lead}</p></Reveal>
      </div>
    </section>);

}

/* -------------------------------------------------------
   Italic helper — exports an inline italic span in display serif
   ------------------------------------------------------- */
function Em({ children, color = 'var(--gold)' }) {
  return <em className="display-italic" style={{ color }}>{children}</em>;
}

/* Make available globally for other babel scripts */
Object.assign(window, {
  useRoute, navigate, CALink, Reveal, Wordmark, Nav, HeroAtmosphere,
  CTABand, Footer, EyebrowRule, PageHero, Em,
  BOOKING_URL, CALENDLY_POSTPAY_URL
});