/* Acqius® main app - React + Babel inline */

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

/* ---- Scroll progress hook for a section ---- */
function useScrollProgress(ref) {
  const [progress, setProgress] = useState(0);
  useEffect(() => {
    if (!ref.current) return;
    const onScroll = () => {
      const el = ref.current;
      if (!el) return;
      const rect = el.getBoundingClientRect();
      const total = rect.height - window.innerHeight;
      const p = total > 0 ? Math.max(0, Math.min(1, -rect.top / total)) : 0;
      setProgress(p);
    };
    onScroll();
    window.addEventListener('scroll', onScroll, { passive: true });
    window.addEventListener('resize', onScroll);
    return () => {
      window.removeEventListener('scroll', onScroll);
      window.removeEventListener('resize', onScroll);
    };
  }, [ref]);
  return progress;
}

/* ---- Map a value between two ranges ---- */
function mapRange(t, [a, b], [c, d]) {
  if (t <= a) return c;
  if (t >= b) return d;
  const ratio = (t - a) / (b - a);
  return c + (d - c) * ratio;
}

/* ---- Is viewport mobile-width ---- */
function useIsMobile(bp = 768) {
  const [m, setM] = useState(typeof window !== 'undefined' && window.innerWidth < bp);
  useEffect(() => {
    const on = () => setM(window.innerWidth < bp);
    on();
    window.addEventListener('resize', on);
    return () => window.removeEventListener('resize', on);
  }, [bp]);
  return m;
}

/* ---- Reveal on scroll ---- */
function Reveal({ children, delay = 0, as: Tag = 'div', className = '', style }) {
  const ref = useRef(null);
  const [state, setState] = useState({ shown: false, instant: false });
  React.useLayoutEffect(() => {
    if (!ref.current) return;
    const rect = ref.current.getBoundingClientRect();
    if (rect.top < window.innerHeight && rect.bottom > 0) { setState({ shown: true, instant: true }); return; }
    const io = new IntersectionObserver((entries) => {
      entries.forEach((e) => {
        if (e.isIntersecting) {
          setState({ shown: true, instant: false });
          io.disconnect();
        }
      });
    }, { rootMargin: '-60px' });
    io.observe(ref.current);
    return () => io.disconnect();
  }, []);
  const d = (!state.instant && delay) ? (delay * 0.08) + 's' : '0s';
  const revealStyle = {
    opacity: state.shown ? 1 : 0,
    transform: state.shown ? 'translateY(0)' : 'translateY(28px)',
    transition: state.instant ? 'none' : `opacity 0.8s cubic-bezier(0.22,1,0.36,1) ${d}, transform 0.8s cubic-bezier(0.22,1,0.36,1) ${d}`,
    ...style,
  };
  return <Tag ref={ref} className={className} style={revealStyle}>{children}</Tag>;
}

/* ---- Window scroll Y ---- */
function useScrollY() {
  const [y, setY] = useState(0);
  useEffect(() => {
    const onScroll = () => setY(window.scrollY);
    onScroll();
    window.addEventListener('scroll', onScroll, { passive: true });
    return () => window.removeEventListener('scroll', onScroll);
  }, []);
  return y;
}

/* ---- LinkedIn ---- */
const LINKEDIN = 'https://www.linkedin.com/company/acqius/';
function LinkedInIcon({ size = 20 }) {
  return (
    <svg width={size} height={size} viewBox="0 0 24 24" fill="currentColor" aria-hidden="true" focusable="false">
      <path d="M20.447 20.452h-3.554v-5.569c0-1.328-.027-3.037-1.852-3.037-1.853 0-2.136 1.445-2.136 2.939v5.667H9.351V9h3.414v1.561h.046c.477-.9 1.637-1.85 3.37-1.85 3.601 0 4.267 2.37 4.267 5.455v6.286zM5.337 7.433a2.062 2.062 0 1 1 0-4.125 2.062 2.062 0 0 1 0 4.125zm1.782 13.019H3.555V9h3.564v11.452zM22.225 0H1.771C.792 0 0 .774 0 1.729v20.542C0 23.227.792 24 1.771 24h20.451C23.2 24 24 23.227 24 22.271V1.729C24 .774 23.2 0 22.222 0h.003z" />
    </svg>
  );
}

/* ---- Logotype ---- */
function Logo() {
  return (
    <span className="logo-stack">
      <img className="lg-white" src="assets/logo-light.png?v=102" alt="Acqius® — Global M&A Advisory" />
      <img className="lg-green" src="assets/logo-dark.png?v=102" alt="" aria-hidden="true" />
    </span>
  );
}

/* ---------- Site Header ---------- */
const NAV_LINKS = [
  ['industries.html', 'Industries'],
  ['insights.html', 'Insights'],
  ['businesses-for-sale.html', 'Businesses For Sale'],
  ['contact.html', 'Contact'],
];
const SERVICES_MENU = [
  ['MaaS', 'maas.html'],
  ['Selling A Business', 'selling-a-business.html'],
  ['Private Equity Services', 'private-equity.html'],
  ['Raising Capital', 'raising-capital.html'],
  ['Buying A Business', 'buying-a-business.html'],
  ['Financial Modelling', 'financial-modelling.html'],
  ['Diligence Support', 'diligence-support.html'],
];
const ABOUT_MENU = [
  ['Founders', 'leadership-team.html'],
  ['Corporate Video', 'corporate-video.html'],
  ['Sustainable M&A', 'sustainable-ma.html'],
];
function NavDropdown({ label, href, items }) {
  const [open, setOpen] = useState(false);
  return (
    <span className={'nav-dd' + (open ? ' open' : '')} onMouseEnter={() => setOpen(true)} onMouseLeave={() => setOpen(false)}>
      <a href={href} className="nav-dd-trigger" aria-haspopup="true" aria-expanded={open}>
        {label}
        <svg className="chev" width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round"><path d="M6 9l6 6 6-6" /></svg>
      </a>
      {open && (
        <div className="nav-dd-panel">
          <div className="inner">
            {items.map(([l, h]) => <a key={h} href={h}>{l}</a>)}
          </div>
        </div>
      )}
    </span>
  );
}
function SiteHeader() {
  const y = useScrollY();
  const [menuOpen, setMenuOpen] = useState(false);
  // Switch to solid/dark text as soon as the hero sky fades to white (~35% into the morph)
  const ratio = Math.min(1, Math.max(0, (y - window.innerHeight * 0.3) / (window.innerHeight * 0.2)));
  const dark = ratio < 0.4 && !menuOpen;
  const headerStyle = {
    backgroundColor: menuOpen ? '#fff' : `rgba(255, 255, 255, ${ratio * 0.9})`,
    color: dark ? '#fff' : '#191c1f',
    borderBottom: (ratio > 0.6 || menuOpen) ? '1px solid var(--line)' : '1px solid transparent',
  };
  return (
    <header className={'header ' + (dark ? 'dark' : 'light')} style={headerStyle}>
      <div className="container row">
        <a href="index.html" className="logo" aria-label="Acqius® — Corporate Finance">
          <Logo />
        </a>
        <nav>
          <NavDropdown label="Services" href="services.html" items={SERVICES_MENU} />
          <NavDropdown label="About Us" href="about.html" items={ABOUT_MENU} />
          {NAV_LINKS.map(([href, label]) => <a key={href} href={href}>{label}</a>)}
        </nav>
        <div className="actions">
          <a href="tel:+443337723616" className="contact tel">+44 (0)333 772 3616</a>
          <a href={LINKEDIN} className="in-link" target="_blank" rel="noopener noreferrer" aria-label="Acqius on LinkedIn"><LinkedInIcon size={18} /></a>
          <a href="#" className="apply" onClick={(e) => e.preventDefault()}>Login</a>
          <button className="nav-toggle" aria-label="Menu" aria-expanded={menuOpen} onClick={() => setMenuOpen((o) => !o)}>
            {menuOpen ? (
              <svg width="22" height="22" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round"><path d="M18 6L6 18M6 6l12 12" /></svg>
            ) : (
              <svg width="22" height="22" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round"><path d="M3 6h18M3 12h18M3 18h18" /></svg>
            )}
          </button>
        </div>
      </div>
      {menuOpen && (
        <div className="mobile-menu">
          <a href="services.html" onClick={() => setMenuOpen(false)}>Services</a>
          {SERVICES_MENU.map(([label, href]) => (
            <a key={href} href={href} className="sub" onClick={() => setMenuOpen(false)}>{label}</a>
          ))}
          <a href="about.html" onClick={() => setMenuOpen(false)}>About Us</a>
          {ABOUT_MENU.map(([label, href]) => (
            <a key={href} href={href} className="sub" onClick={() => setMenuOpen(false)}>{label}</a>
          ))}
          {NAV_LINKS.map(([href, label]) => <a key={href} href={href} onClick={() => setMenuOpen(false)}>{label}</a>)}
          <div className="mobile-menu-actions">
            <a href="tel:+443337723616" className="mm-contact">+44 (0)333 772 3616</a>
            <a href={LINKEDIN} className="mm-in" target="_blank" rel="noopener noreferrer"><LinkedInIcon size={17} /> LinkedIn</a>
            <a href="#" className="mm-apply" onClick={(e) => e.preventDefault()}>Login</a>
          </div>
        </div>
      )}
    </header>
  );
}

/* ---------- HERO MORPH ---------- */
function HeroMorph() {
  const ref = useRef(null);
  const p = useScrollProgress(ref);
  const isMobile = useIsMobile();

  // Animation mappings
  const skyOpacity = mapRange(p, [0.05, 0.45], [1, 0]);
  const textOpacity = mapRange(p, [0, 0.18], [1, 0]);
  const textY = mapRange(p, [0, 0.18], [0, -80]);
  const heroScale = mapRange(p, [0.05, 0.5], [isMobile ? 1.95 : 1.6, 1]);
  const heroX = mapRange(p, [0.05, 0.5], [isMobile ? 0 : 50, 0]); // %
  const heroY = mapRange(p, [0.05, 0.5], [isMobile ? 0 : 16, 0]); // %
  const centerOp = mapRange(p, [0.05, 0.28], [0, 1]);
  const leftX = mapRange(p, [0.15, 0.55], [-80, 0]);
  const leftOp = mapRange(p, [0.15, 0.4], [0, 1]);
  const rightX = mapRange(p, [0.15, 0.55], [80, 0]);
  const rightOp = mapRange(p, [0.15, 0.4], [0, 1]);
  const labelOp = mapRange(p, [0.45, 0.7], [0, 1]);
  const finalOp = mapRange(p, [0.5, 0.78], [0, 1]);
  const finalY = mapRange(p, [0.5, 0.78], [30, 0]);

  return (
    <section ref={ref} className="hero-section">
      <div className="hero-sticky">
        <div className="hero-sky" style={{ opacity: skyOpacity }} />
        <div className="hero-fullbg" style={{ opacity: skyOpacity }}>
          <img src="assets/hero-refinery-night.jpg?v=102" alt="Refinery complex lit at night with engineers on the gantry" fetchPriority="high" />
        </div>
        <div className="hero-clouds" style={{ opacity: skyOpacity }} />
        <div className="hero-white" />

        {/* Hero text */}
        <div
          className="hero-text"
          style={{ opacity: textOpacity, transform: `translateY(${textY}px)` }}
        >
          <h1 className="hero-headline">
            <span className="ho-line ho-bold">GLOBAL M&amp;A ADVISORY</span>
            <span className="ho-line ho-regular" style={{ fontSize: '0.52em', marginTop: '0.35em', letterSpacing: '-0.03em' }}>FOR HIGHLY REGULATED &amp; TECHNICALLY CRITICAL INDUSTRIES</span>
          </h1>
          <p>We specialise exclusively in regulated industries where certification and compliance materially affect valuation and deal structure. Most advisors underprice these risks.</p>
          <div className="cta-row">
            <a href="maas.html" className="btn-primary">MaaS — M&amp;A as a Service</a>
            <a href="contact.html" className="btn-ghost-light">Speak to us</a>
          </div>
          <div className="hero-award">
            <img
              src="assets/award-ma-today-2026.png?v=101"
              alt="M&amp;A Today Global Awards 2026 Winner — Acqius, Cross-Border Deal of the Year 2026"
              width="596"
              height="595"
            />
            <span className="hero-award-txt">
              <strong>Cross-Border Deal of the Year 2026</strong>
              <span>M&amp;A Today Global Awards — Winner</span>
            </span>
          </div>
        </div>
        {/* Final title */}
        <div
          className="hero-final-title"
          style={{ opacity: finalOp, transform: `translateY(${finalY}px)` }}
        >
          <p className="eyebrow">Sell, Buy, Raise</p>
          <h2>Specialists in sell-side, buy-side, and capital-raising transactions.</h2>        </div>

        {/* Card stage */}
        <div className="card-stage">
          <div className="card-grid">
            <a
              href="selling-a-business.html"
              className="morph-card card-left"
              style={{ transform: `translateX(${leftX}%)`, opacity: leftOp }}
            >
              <img src="assets/hero-refinery.jpg" alt="Refinery at blue hour — selling a business" />
              <div className="label" style={{ opacity: labelOp }}>
                <p className="num">01 — Sell-side</p>
                <h3 className="svc-name">Selling A Business</h3>
              </div>
            </a>

            <a
              href="buying-a-business.html"
              className="morph-card card-center"
              style={{ transform: `scale(${heroScale}) translate(${heroX}%, ${heroY}%)`, opacity: centerOp }}
            >
              <img src="assets/hero-oil-platform.jpg" alt="Offshore platform at golden hour — buying a business" />
              <div className="card-scrim" style={{ opacity: textOpacity }} />
              <div className="label" style={{ opacity: labelOp }}>
                <p className="num">02 — Buy-side</p>
                <h3 className="svc-name">Buying A Business</h3>
              </div>
            </a>

            <a
              href="raising-capital.html"
              className="morph-card card-right"
              style={{ transform: `translateX(${rightX}%)`, opacity: rightOp }}
            >
              <img src="assets/hero-tanks.jpg" alt="Fuel storage tanks — raising capital" />
              <div className="label" style={{ opacity: labelOp }}>
                <p className="num">03 — Capital</p>
                <h3 className="svc-name">Raising Capital</h3>
              </div>
            </a>
          </div>
        </div>
      </div>
    </section>
  );
}

Object.assign(window, { useScrollY, useScrollProgress, mapRange, useIsMobile, Reveal, Logo, LINKEDIN, LinkedInIcon, SiteHeader, HeroMorph, CookieConsent });

/* ---------- Cookie consent ---------- */
function CookieConsent() {
  const [show, setShow] = useState(false);
  const [analytics, setAnalytics] = useState(false);
  useEffect(() => {
    let stored = null;
    try { stored = localStorage.getItem('acqius_cookie_consent'); } catch (e) {}
    if (!stored) setShow(true);
  }, []);
  const close = (val) => {
    try { localStorage.setItem('acqius_cookie_consent', JSON.stringify({ ...val, ts: Date.now() })); } catch (e) {}
    setShow(false);
  };
  if (!show) return null;
  return (
    <div className="cc-overlay">
    <div className="cookie-consent" role="dialog" aria-modal="true" aria-label="Our use of cookies">
      <h2 className="cc-title">Our use of cookies</h2>
      <p className="cc-body">
        We use necessary cookies to make our site work. We'd also like to set analytics cookies that help us make improvements by measuring how you use the site. These will be set only if you accept. For more detailed information about the cookies we use, see our <a href="#">Cookies page</a>.
      </p>
      <button className="cc-accept" onClick={() => close({ necessary: true, analytics: true })}>
        Accept all cookies
        <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.4" strokeLinecap="round" strokeLinejoin="round"><path d="M7 17L17 7M9 7h8v8" /></svg>
      </button>
      <div className="cc-toggle-row">
        <span className="cc-toggle on disabled" aria-hidden="true"><span className="knob" /></span>
        <span className="cc-toggle-label muted">Strictly necessary cookies</span>
      </div>
      <div className="cc-toggle-row">
        <button className={'cc-toggle' + (analytics ? ' on' : '')} onClick={() => setAnalytics((a) => !a)} aria-pressed={analytics} aria-label="Analytics cookies"><span className="knob" /></button>
        <span className="cc-toggle-label">Analytics cookies</span>
      </div>
      <p className="cc-body">
        We'd like to set Analytics cookies to help us improve our website by collecting and reporting information on how you use it. The cookies collect information in a way that does not directly identify anyone. For more information on how these cookies work please see our 'Cookies page'.
      </p>
      <div className="cc-actions">
        <button className="cc-outline" onClick={() => close({ necessary: true, analytics })}>Save cookie settings</button>
        <button className="cc-outline" onClick={() => close({ necessary: true, analytics: false })}>Reject all cookies</button>
      </div>
    </div>
    </div>
  );
}
