/* Acqius® — shared shell for subpages (header, footer, hero, forms, helpers).
   Reuses styles.css design tokens so subpages match the homepage. */

const { useState: useStateP, useEffect: useEffectP, useRef: useRefP } = React;

/* ---- Routes ---- */
const ROUTES = {
  home: 'index.html',
  services: 'services.html',
  selling: 'selling-a-business.html',
  maas: 'maas.html',
  pe: 'private-equity.html',
  industries: 'industries.html',
  insights: 'insights.html',
  businesses: 'businesses-for-sale.html',
  about: 'about.html',
  contact: 'contact.html',
  buying: 'buying-a-business.html',
  raising: 'raising-capital.html',
  modelling: 'financial-modelling.html',
  diligence: 'diligence-support.html',
  leadership: 'leadership-team.html',
  video: 'corporate-video.html',
  sustainable: 'sustainable-ma.html',
};

const PHONE = '+44 (0)333 772 3616';
const PHONE_HREF = 'tel:+443337723616';
const EMAIL = 'enquiries@acqius.com';
const LINKEDIN = 'https://www.linkedin.com/company/acqius/';

/* ---- LinkedIn glyph ---- */
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>
  );
}

/* ---- Scroll Y ---- */
function useScrollYP() {
  const [y, setY] = useStateP(0);
  useEffectP(() => {
    const onScroll = () => setY(window.scrollY);
    onScroll();
    window.addEventListener('scroll', onScroll, { passive: true });
    return () => window.removeEventListener('scroll', onScroll);
  }, []);
  return y;
}

/* ---- Reveal on scroll ---- */
function Reveal({ children, className = '', delay = 0, as = 'div', style }) {
  const ref = useRefP(null);
  const [state, setState] = useStateP({ shown: false, instant: false });
  React.useLayoutEffect(() => {
    if (!ref.current) return;
    const rect = ref.current.getBoundingClientRect();
    // Above-the-fold: reveal instantly, no transition (an unfocused iframe
    // throttles rAF and would otherwise freeze the fade at opacity 0).
    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 Tag = as;
  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>;
}

function ArrowSm() {
  return (
    <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
      <path d="M5 12h14M13 5l7 7-7 7" />
    </svg>
  );
}
function Check() {
  return (
    <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.2" strokeLinecap="round" strokeLinejoin="round">
      <path d="M20 6L9 17l-5-5" />
    </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>
  );
}

/* ---- Subpage header (transparent over hero, solidifies on scroll) ---- */
const NAV_P = [
  ['services', 'Services'],
  ['about', 'About Us'],
  ['industries', 'Industries'],
  ['insights', 'Insights'],
  ['businesses', 'Businesses For Sale'],
  ['contact', '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, active }) {
  const [open, setOpen] = useStateP(false);
  return (
    <span className={'nav-dd' + (open ? ' open' : '')} onMouseEnter={() => setOpen(true)} onMouseLeave={() => setOpen(false)}>
      <a href={href} className={'nav-dd-trigger' + (active ? ' current' : '')} 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 SubHeader({ current }) {
  const y = useScrollYP();
  const [menuOpen, setMenuOpen] = useStateP(false);
  const ratio = Math.min(1, Math.max(0, (y - 120) / 180));
  const dark = ratio < 0.45 && !menuOpen;
  const headerStyle = {
    backgroundColor: menuOpen ? '#fff' : `rgba(255, 255, 255, ${ratio * 0.95})`,
    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={ROUTES.home} className="logo" aria-label="Acqius® — Corporate Finance">
          <Logo />
        </a>
        <nav>
          <NavDropdown label="Services" href={ROUTES.services} items={SERVICES_MENU} active={current === 'services'} />
          <NavDropdown label="About Us" href={ROUTES.about} items={ABOUT_MENU} active={current === 'about'} />
          {NAV_P.filter(([key]) => key !== 'services' && key !== 'about').map(([key, label]) => (
            <a key={key} href={ROUTES[key]} className={current === key ? 'current' : ''}>{label}</a>
          ))}
        </nav>
        <div className="actions">
          <a href={PHONE_HREF} className="contact tel">{PHONE}</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={ROUTES.services} onClick={() => setMenuOpen(false)}>Services</a>
          {SERVICES_MENU.map(([label, href]) => (
            <a key={href} href={href} className="sub" onClick={() => setMenuOpen(false)}>{label}</a>
          ))}
          <a href={ROUTES.about} onClick={() => setMenuOpen(false)}>About Us</a>
          {ABOUT_MENU.map(([label, href]) => (
            <a key={href} href={href} className="sub" onClick={() => setMenuOpen(false)}>{label}</a>
          ))}
          {NAV_P.filter(([key]) => key !== 'services' && key !== 'about').map(([key, label]) => (
            <a key={key} href={ROUTES[key]} onClick={() => setMenuOpen(false)}>{label}</a>
          ))}
          <div className="mobile-menu-actions">
            <a href={PHONE_HREF} className="mm-contact">{PHONE}</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>
  );
}

/* ---- Page hero band ---- */
function PageHero({ eyebrow, title, lede, cta, variant, meta, bg }) {
  return (
    <section className={'page-hero' + (variant ? ' ' + variant : '') + (bg ? ' has-bg' : '')}>
      {bg ? (
        <React.Fragment>
          <div className="hero-bg" style={{ backgroundImage: 'url(' + bg + ')' }} />
          <div className="hero-scrim" />
        </React.Fragment>
      ) : <div className="glow" />}
      <div className="container">
        <Reveal><p className="eyebrow-light">{eyebrow}</p></Reveal>
        <Reveal delay={1}><h1 className="svc-name">{title}</h1></Reveal>
        {meta && <Reveal delay={2}><p className="hero-meta">{meta}</p></Reveal>}
        {lede && <Reveal delay={2}><p className="lede">{lede}</p></Reveal>}
        {cta && (
          <Reveal delay={3}>
            <div className="cta-row">
              <a href={cta.href} className="btn-primary">{cta.label}</a>
              {cta.secondary && <a href={cta.secondary.href} className="btn-ghost-light">{cta.secondary.label}</a>}
            </div>
          </Reveal>
        )}
      </div>
    </section>
  );
}

/* ---- Amber closing CTA band ---- */
function AmberCTA() {
  return (
    <section className="band-amber">
      <div className="container">
        <Reveal>
          <h2 className="hd hd-xl mw-960">We're experts at selling businesses because we've successfully sold our own.</h2>
        </Reveal>
        <Reveal delay={1}><p className="sub">Thirty years of expertise guiding acquisitions.</p></Reveal>
        <Reveal delay={2}>
          <div className="cta-row">
            <a href={ROUTES.contact} className="btn-deep">Schedule a call <ArrowSm /></a>
            <a href={PHONE_HREF} className="tel-lg">Call Us: {PHONE}</a>
          </div>
        </Reveal>
      </div>
    </section>
  );
}

/* ---- reCAPTCHA note ---- */
function RecaptchaNote() {
  return (
    <p className="note" style={{ fontSize: 13, color: 'var(--ink-soft)', margin: 0 }}>
      This site is protected by reCAPTCHA and the Google <a href="#" style={{ textDecoration: 'underline' }}>Privacy Policy</a> and <a href="#" style={{ textDecoration: 'underline' }}>Terms of Service</a> apply.
    </p>
  );
}

/* ---- Get In Touch (dark panel + email/message form) ---- */
function GetInTouch({ heading = 'Get in touch', intro }) {
  const [sent, setSent] = useStateP(false);
  return (
    <section className="page-section">
      <div className="container">
        <div className="contact-layout">
          <Reveal>
            <div style={{ background: '#1c3527', color: '#fff', borderRadius: 24, padding: 'clamp(32px, 4vw, 52px)' }}>
              <h2 className="hd hd-xl" style={{ color: '#fff' }}>{heading}</h2>
              <p style={{ margin: '22px 0 0', fontSize: 16.5, lineHeight: 1.65, color: 'rgba(255,255,255,0.88)', maxWidth: 460 }}>
                {intro || "If you would like a no obligation discussion to explore possibilities or even to just sound us out, please get in touch, we'd be delighted to hear from you."}
              </p>
              <div style={{ marginTop: 30, display: 'flex', flexDirection: 'column', gap: 8, fontSize: 15.5 }}>
                <span>Telephone: <a href={PHONE_HREF} style={{ color: 'var(--brand-amber)', textDecoration: 'underline', textUnderlineOffset: 3 }}>+44 (0)333 772 3616</a></span>
                <span>e-mail: <a href={'mailto:' + EMAIL} style={{ color: 'var(--brand-amber)', textDecoration: 'underline', textUnderlineOffset: 3 }}>{EMAIL}</a></span>
              </div>
            </div>
          </Reveal>
          <Reveal delay={1}>
            <form className="form" style={{ margin: 0 }} onSubmit={(e) => { e.preventDefault(); setSent(true); }}>
              <div className="field">
                <label>Email Required</label>
                <input required type="email" placeholder="Email" />
              </div>
              <div className="field">
                <label>Message Required</label>
                <textarea required rows={6} placeholder="Message"></textarea>
              </div>
              <div className="form-actions">
                <RecaptchaNote />
                <button type="submit">{sent ? 'Submitted ✓' : 'Submit'}</button>
              </div>
              {sent && <p className="form-success">Thank you — we'll be in touch shortly. You can also email <a href={'mailto:' + EMAIL} style={{ textDecoration: 'underline' }}>{EMAIL}</a>.</p>}
            </form>
          </Reveal>
        </div>
      </div>
    </section>
  );
}

/* ---- Let's Work Together (first/last/email/message form) ---- */
function LetsWorkTogether() {
  const [sent, setSent] = useStateP(false);
  return (
    <section className="page-section" style={{ paddingTop: 0 }}>
      <div className="container">
        <div className="contact-layout">
          <Reveal>
            <div style={{ background: '#1c3527', color: '#fff', borderRadius: 24, padding: 'clamp(32px, 4vw, 52px)' }}>
              <h2 className="hd hd-xl" style={{ color: '#fff' }}>Let’s work together</h2>
              <p style={{ margin: '22px 0 0', fontSize: 16.5, lineHeight: 1.65, color: 'rgba(255,255,255,0.88)', maxWidth: 460 }}>
                Interested in working together? Fill the details in below and we will be in touch shortly.
              </p>
            </div>
          </Reveal>
          <Reveal delay={1}>
            <form className="form" style={{ margin: 0 }} onSubmit={(e) => { e.preventDefault(); setSent(true); }}>
              <div className="field-grid">
                <div className="field">
                  <label>First Name Required</label>
                  <input required type="text" placeholder="First name" />
                </div>
                <div className="field">
                  <label>Last Name</label>
                  <input type="text" placeholder="Last name" />
                </div>
              </div>
              <div className="field">
                <label>Email Required</label>
                <input required type="email" placeholder="Email" />
              </div>
              <div className="field">
                <label>Tell us more about your situation</label>
                <textarea rows={5} placeholder="Tell us more about your situation"></textarea>
              </div>
              <div className="form-actions">
                <RecaptchaNote />
                <button type="submit">{sent ? 'Submitted ✓' : 'Submit'}</button>
              </div>
              {sent && <p className="form-success">Thank you — we'll be in touch shortly.</p>}
            </form>
          </Reveal>
        </div>
      </div>
    </section>
  );
}

/* ---- FAQ accordion item ---- */
function FAQItem({ q, a, open, onToggle }) {
  return (
    <div className={'faq-item' + (open ? ' open' : '')}>
      <button className="faq-q" onClick={onToggle} aria-expanded={open}>
        <span>{q}</span>
        <svg className="ic" width="22" height="22" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round">
          <path d="M12 5v14M5 12h14" />
        </svg>
      </button>
      <div className="faq-a"><p>{a}</p></div>
    </div>
  );
}

/* ---- Shared dark footer ---- */
function SubFooter() {
  return (
    <footer className="footer-dark">
      <div className="container">
        <div className="cols">
          <div>
            <a href={ROUTES.home} className="logo" aria-label="Acqius® — Corporate Finance" style={{ display: 'inline-flex' }}>
              <Logo />
            </a>
            <img
              className="award-badge"
              src="assets/award-ma-today-2026.png?v=101"
              alt="M&A Today Global Awards 2026 Winner — Acqius, Cross-Border Deal of the Year 2026"
              width="596"
              height="595"
              loading="lazy"
            />
          </div>
          <div>
            <h3>Sitemap</h3>
            <ul>
              <li><a href={ROUTES.home}>Home</a></li>
              <li><a href={ROUTES.insights}>News</a></li>
              <li><a href="#">Careers</a></li>
              <li><a href={ROUTES.about}>About Us</a></li>
              <li><a href={ROUTES.contact}>Contact</a></li>
            </ul>
          </div>
          <div>
            <h3>Policies</h3>
            <ul>
              <li><a href="#">Anti-Bribery Policy</a></li>
              <li><a href="#">Privacy Policy</a></li>
              <li><a href="#">Modern Slavery Policy</a></li>
              <li><a href="#">Terms and Conditions</a></li>
            </ul>
          </div>
          <div>
            <h3>Contact Us</h3>
            <ul>
              <li><a href={PHONE_HREF}>{PHONE}</a></li>
              <li><a href={'mailto:' + EMAIL}>{EMAIL}</a></li>
            </ul>
            <a href={LINKEDIN} className="in-badge" target="_blank" rel="noopener noreferrer" aria-label="Acqius on LinkedIn" style={{ marginTop: 22, display: 'inline-grid' }}><LinkedInIcon size={19} /></a>
          </div>
        </div>
        <div className="disclaimer">
          <p>Acqius® Ltd is a corporate finance advisory firm. Please note that we are not registered with the Financial Conduct Authority (FCA) in the UK. Our services are provided on a consultancy basis and do not include regulated activities. As such, any investment or financial decisions made based on the information provided on this website are made at your own risk. We recommend that you seek independent financial advice before making any investment decisions.</p>
          <p>© Acqius® Ltd {new Date().getFullYear()}. All rights reserved.</p>
        </div>
      </div>
    </footer>
  );
}

/* ---- News article shell: shared format for every insights post ---- */
function ArtBackArrow() {
  return (
    <svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.4" strokeLinecap="round" strokeLinejoin="round">
      <path d="M19 12H5M11 19l-7-7 7-7" />
    </svg>
  );
}

function NewsArticle({ title, date, image, children }) {
  return (
    <SubPage
      current="insights"
      hero={{ variant: 'article', eyebrow: 'News', title, meta: date, bg: image }}
    >
      <section className="page-section">
        <div className="container">
          <div className="article-body">
            {children}
            <a href={ROUTES.insights} className="art-back"><ArtBackArrow /> All news</a>
          </div>
        </div>
      </section>
      <AmberCTA />
    </SubPage>
  );
}

/* ---- Page wrapper that mounts header + footer around children ---- */
function SubPage({ current, hero, children }) {
  return (
    <main className="subpage">
      <SubHeader current={current} />
      <PageHero {...hero} />
      {children}
      <SubFooter />
    </main>
  );
}

Object.assign(window, {
  ROUTES, PHONE, PHONE_HREF, EMAIL, LINKEDIN, LinkedInIcon, useScrollYP, Reveal, ArrowSm, Check, Logo,
  SubHeader, NavDropdown, SERVICES_MENU, ABOUT_MENU, PageHero, AmberCTA, RecaptchaNote, GetInTouch, LetsWorkTogether,
  FAQItem, SubFooter, SubPage, NewsArticle,
});
