/* Wh4 — shared shell for subpages (header, footer, hero, 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',
  partnership: 'partnership.html',
  approach: 'approach.html',
  portfolio: 'portfolio.html',
  fundraise: 'fundraise.html',
  /* Division routes */
  advisory: 'advisory.html',
  partners: 'partners.html',
  property: 'property.html',
  capital: 'capital.html',
  /* Legacy chapter routes — kept so old internal links still resolve */
  strategic: 'partners.html',
  network: 'partners.html#founders-collective',
  exit: 'advisory.html',
  contact: 'contact.html',
};

/* ---- 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 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), transform 0.8s cubic-bezier(0.22,1,0.36,1)',
    transitionDelay: (!state.instant && delay) ? (delay * 0.08) + 's' : '0s',
    ...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>
  );
}

/* ---- Initials avatar ---- */
function Avatar({ name }) {
  const initials = name.split(' ').filter(Boolean).slice(0, 2).map((w) => w[0]).join('').toUpperCase();
  return <div className="avatar" aria-hidden="true">{initials}</div>;
}

/* ---- Subpage header (transparent over hero, solidifies on scroll) ---- */
function SubHeader({ current }) {
  const y = useScrollYP();
  const [menuOpen, setMenuOpen] = useStateP(false);
  // On chapter/division pages the hero is light (paper), so the header must
  // start in NAVY mode so the logo + nav are visible from scroll = 0.
  // (Rob's bug — previously the header sat in white-on-white mode and vanished.)
  const dark = false;
  const ratio = Math.min(1, Math.max(0, y / 80));
  const headerStyle = {
    backgroundColor: menuOpen ? '#fff' : `rgba(255, 255, 255, ${0.7 + ratio * 0.3})`,
    color: '#191c1f',
    borderBottom: '1px solid var(--line)',
    backdropFilter: 'blur(12px)',
    WebkitBackdropFilter: 'blur(12px)',
  };
  const nav = [
    ['advisory', 'M&A'],
    ['partners', 'Growth Partnerships'],
    ['property', 'Land'],
    ['capital', 'Capital'],
  ];
  return (
    <header className={'header ' + (dark ? 'dark' : 'light')} style={headerStyle}>
      <div className="container row">
        <a href={ROUTES.home} className="logo" aria-label="Wh4">
          <img src={dark ? 'assets/wh4-logo.png' : 'assets/wh4-logo-navy.png'} alt="Wh4" className="logo-mark" />
        </a>
        <nav>
          {nav.map(([key, label]) => (
            <a key={key} href={ROUTES[key]} className={current === key ? 'current' : ''}>{label}</a>
          ))}
        </nav>
        <div className="actions">
          <a href="contact.html#book" className="apply apply-white">Book a consultation</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">
          {nav.map(([key, label]) => (
            <a key={key} href={ROUTES[key]} onClick={() => setMenuOpen(false)}>{label}</a>
          ))}
          <div className="mobile-menu-actions">
            <a href="contact.html#book" className="mm-apply">Book a consultation</a>
          </div>
        </div>
      )}
    </header>
  );
}

/* ---- Page hero band ---- */
function PageHero({ eyebrow, title, lede, cta }) {
  return (
    <section className="page-hero">
      <div className="glow" />
      <div className="container">
        <Reveal><p className="eyebrow-light">{eyebrow}</p></Reveal>
        <Reveal delay={1}><h1 className="svc-name">{fmtWh4P(title)}</h1></Reveal>
        {lede && <Reveal delay={2}><p className="lede">{fmtWh4P(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>
  );
}

/* ---- Closing CTA band ---- */
function CTABand({ title, lede, primary, secondary }) {
  return (
    <section className="cta-band">
      <div className="container">
        <Reveal><h2 className="hd hd-xl">{fmtWh4P(title)}</h2></Reveal>
        {lede && <Reveal delay={1}><p className="page-lede">{fmtWh4P(lede)}</p></Reveal>}
        <Reveal delay={2}>
          <div className="cta-row">
            <a href={primary.href} className="btn-primary">{primary.label}</a>
            {secondary && <a href={secondary.href} className="btn-ghost-light">{secondary.label}</a>}
          </div>
        </Reveal>
      </div>
    </section>
  );
}

/* ---- Team section ---- */
function TeamSection({ eyebrow, heading, intro, people }) {
  return (
    <section className="page-section alt">
      <div className="container">
        <Reveal><p className="eyebrow">{eyebrow}</p></Reveal>
        <Reveal delay={1}><h2 className="hd hd-xl" style={{ marginTop: 14 }}>{heading}</h2></Reveal>
        {intro && <Reveal delay={2}><p className="page-lede">{intro}</p></Reveal>}
        <div className="team-grid">
          {people.map((m, i) => (
            <Reveal key={m.name} delay={(i % 4) + 1}>
              <div className="team-card">
                <Avatar name={m.name} />
                <div className="name">{m.name}</div>
                <div className="role">{m.role}</div>
                {m.bio && <p className="bio">{m.bio}</p>}
              </div>
            </Reveal>
          ))}
        </div>
      </div>
    </section>
  );
}

/* ---- Shared subpage footer ---- */
const footerColumnsP = [
  { title: 'Wh4 Ltd', links: [
    ['Home', ROUTES.home],
    ['Wh4 M&A', ROUTES.advisory],
    ['Wh4 Growth Partnerships', ROUTES.partners],
    ['Wh4 Land', ROUTES.property],
    ['Wh4 Capital', ROUTES.capital],
    ['Portfolio', ROUTES.portfolio],
    ['Contact', ROUTES.contact],
  ]},
  { title: 'Legal', links: [
    ['Privacy Policy', 'privacy.html'],
    ['Terms of Use', 'terms.html'],
    ['Cookies', 'cookies.html'],
    ['Confidentiality', 'confidentiality.html'],
    ['Disclosures', 'disclosures.html'],
  ]},
  { title: 'Contact', links: [
    ['hello@wh4.co.uk', 'mailto:hello@wh4.co.uk'],
    ['+44 (0)203 633 9707', 'tel:+442036339707'],
    ['Lower Thames Street', ROUTES.contact],
    ['London, EC3R', ROUTES.contact],
    ['Book a consultation', 'contact.html#book'],
  ]},
];

function SubFooter() {
  return (
    <footer className="footer">
      <div className="container">
        <div className="link-grid" style={{ marginTop: 0 }}>
          {footerColumnsP.map((col) => (
            <div key={col.title} className="link-col">
              <h3>{fmtWh4P(col.title)}</h3>
              <ul>
                {col.links.map(([label, href]) => <li key={label}><a href={href}>{fmtWh4P(label)}</a></li>)}
              </ul>
            </div>
          ))}
        </div>

        <div className="footer-mid">
          <a href={ROUTES.home} className="logo" style={{ fontWeight: 700, fontSize: 26, letterSpacing: '-0.5px', display: 'inline-flex', alignItems: 'center', gap: 10 }}>
            <span style={{ width: 36, height: 36, borderRadius: 8, display: 'grid', placeItems: 'center', background: '#102e5e' }}>
              <img src="assets/wh4-logo.png" alt="Wh4" style={{ width: '70%', height: '70%', objectFit: 'contain', display: 'block' }} />
            </span>
            <span>Wh<sup>4</sup></span>
          </a>
        </div>

        <div className="footer-bot">
          <a href="mailto:hello@wh4.co.uk" className="email-pill"><span>hello@wh4.co.uk</span></a>
        </div>

        <div className="footer-regulatory">
          <h4>Regulatory Disclaimer</h4>
          <p>Wh<sup>4</sup> Ltd is not authorised or regulated by the Financial Conduct Authority (FCA) or by any other financial services regulator. Wh<sup>4</sup> Ltd provides strategic and corporate advisory services in connection with the purchase and sale of businesses. We do not provide investment advice, arrange deals in investments, or carry on any other activity regulated under the Financial Services and Markets Act 2000 (FSMA), and nothing on this website constitutes such activity.</p>
          <p>The content of this website is provided for general information purposes only. It does not constitute investment, legal, tax or accounting advice, nor a recommendation, offer, solicitation or inducement to buy, sell or subscribe for any securities or other financial instruments. Visitors should seek their own independent professional advice — including from appropriately authorised financial advisers — before making any decision relating to the sale, purchase or valuation of a business or any investment.</p>
          <p>Our services are directed at business owners and corporate entities and are not intended for retail clients or private individuals seeking regulated financial services. Any transaction discussions we facilitate relate to the sale of businesses as going concerns. Where a proposed transaction is structured in a way that involves regulated activities, we will refer the relevant parties to appropriately authorised firms.</p>
          <p><strong>United Arab Emirates.</strong> Wh<sup>4</sup> Ltd is not licensed or regulated by the UAE Securities and Commodities Authority (SCA), the Central Bank of the UAE, the Dubai Financial Services Authority (DFSA) of the Dubai International Financial Centre (DIFC), or the Financial Services Regulatory Authority (FSRA) of Abu Dhabi Global Market (ADGM). Nothing on this website constitutes the promotion, offering or sale of securities or financial products in or from the UAE, the DIFC or the ADGM, nor the provision of financial services requiring a licence in any of those jurisdictions. This website and its contents are not directed at retail clients in the UAE. Any advisory engagement involving regulated activities in the UAE will be conducted only through, or by referral to, appropriately licensed firms.</p>
          <p>While we take care to ensure the information on this website is accurate, we make no representations or warranties as to its completeness or accuracy, and we accept no liability for any loss arising from reliance upon it.</p>
        </div>

        <div className="footer-strapline">
          <p>Wh<sup>4</sup> Ltd <span className="fs-dot">·</span> M&A <span className="fs-dot">·</span> Growth Partnerships <span className="fs-dot">·</span> Land <span className="fs-dot">·</span> Capital</p>
        </div>

        <div className="footer-bot-links">
          <a href="privacy.html">Privacy</a>
          <a href="terms.html">Terms</a>
          <a href="cookies.html">Cookies</a>
          <a href="confidentiality.html">Confidentiality</a>
          <a href="disclosures.html">Disclosures</a>
          <a href="contact.html">Contact</a>
        </div>

        <div className="footer-legal">
          <p><strong>Important notice:</strong> nothing on this website constitutes financial, investment, legal, tax, accounting or transaction advice, nor an offer to sell or a solicitation to buy any security. This website is provided for informational purposes only. All engagement decisions are at the sole discretion of Wh<sup>4</sup> Ltd.</p>
          <p>Wh<sup>4</sup> Ltd is a family-owned diversified group operating four divisions: M&A, Growth Partnerships, Land and Capital. Engagements are bespoke and confidential by default.</p>
          <p>Companies featured in the portfolio section have consented to be named. Other engagements remain confidential.</p>
          <p className="footer-statutory">Wh<sup>4</sup> Ltd · Registered in England and Wales · Company No. 16339855 · Registered office: The American Barns, Banbury Road, Lighthorne, Warwick, Warwickshire, England, CV35 0AE · VAT No. 494008877</p>
        </div>

        <div className="footer-copy">
          <p style={{ color: '#191c1f', fontWeight: 500 }}>Copyright © 2026 Wh<sup>4</sup> Ltd — All Rights Reserved.</p>
        </div>
      </div>
    </footer>
  );
}

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

/* ---- Cofounder-style division page (used by the 4 division sub-pages) ---- */
const CHAPTER_DATA = [
  {
    n: 'I', roman: 'I', title: 'Wh4 M&A', file: 'advisory.html',
    sections: [
      ['overview', 'Overview'],
      ['sell-side', 'Sell-Side M&A'],
      ['buy-side', 'Buy-Side M&A'],
      ['process', 'The Sell-Side Process'],
      ['sectors', 'Sectors we cover'],
      ['cta', 'Discuss a transaction'],
    ],
  },
  {
    n: 'II', roman: 'II', title: 'Wh4 Growth Partnerships', file: 'partners.html',
    sections: [
      ['overview', 'Overview'],
      ['why', 'Why founders partner with us'],
      ['equity', 'How equity works'],
      ['founders-collective', 'The Private Founders Collective'],
      ['cta', 'Partner with us'],
    ],
  },
  {
    n: 'III', roman: 'III', title: 'Wh4 Land', file: 'property.html',
    sections: [
      ['overview', 'Overview'],
      ['approach', 'Our approach'],
      ['what-we-do', 'What we do'],
      ['cta', 'Discuss a site or opportunity'],
    ],
  },
  {
    n: 'IV', roman: 'IV', title: 'Wh4 Capital', file: 'capital.html',
    sections: [
      ['overview', 'Overview'],
      ['what-we-look-for', 'What we acquire'],
      ['how-we-build', 'How we build'],
      ['for-sellers', 'For business owners'],
      ['for-investors', 'For investors'],
    ],
  },
];

/* Cookie notice — essential cookies only; dismiss persists in localStorage */
function CookieNoticeP() {
  const [show, setShow] = useStateP(() => {
    try { return !localStorage.getItem('wh4-cookies-ok'); } catch (e) { return true; }
  });
  if (!show) return null;
  const accept = () => {
    try { localStorage.setItem('wh4-cookies-ok', '1'); } catch (e) {}
    setShow(false);
  };
  return (
    <div className="cookie-notice" role="dialog" aria-label="Cookie notice">
      <p>We use essential cookies and similar browser storage to make this site work. See our <a href="cookies.html">Cookie Policy</a>.</p>
      <button onClick={accept}>OK</button>
    </div>
  );
}

/* Render any string containing "Wh4" with the 4 as a superscript */
function fmtWh4P(str) {
  const parts = String(str).split(/Wh4/);
  if (parts.length === 1) return str;
  return parts.flatMap((p, i) => i === 0 ? [p] : [<React.Fragment key={i}>Wh<sup>4</sup></React.Fragment>, p]);
}

function ChapterSidebar({ currentN, activeSection, onSectionClick }) {
  return (
    <aside className="chap-sidebar">
      <p className="chap-sidebar-title">Wh<sup>4</sup> Ltd — the four divisions</p>
      <nav>
        {CHAPTER_DATA.map((c) => {
          const isCurrent = c.n === currentN;
          return (
            <div key={c.n} className={'chap-sidebar-ch' + (isCurrent ? ' is-current' : '')}>
              <a href={c.file} className="chap-sidebar-ch-head">
                <span className="chap-sidebar-roman">({c.roman})</span>
                <span className="chap-sidebar-ch-name">{fmtWh4P(c.title)}</span>
              </a>
              <ul className="chap-sidebar-secs">
                {c.sections.map(([id, label]) => (
                  <li key={id}>
                    <a
                      href={isCurrent ? ('#' + id) : (c.file + '#' + id)}
                      className={isCurrent && activeSection === id ? 'is-active' : ''}
                      onClick={isCurrent && onSectionClick ? (e) => onSectionClick(e, id) : undefined}
                    >
                      {label}
                    </a>
                  </li>
                ))}
              </ul>
            </div>
          );
        })}
      </nav>
      <a href={ROUTES.contact} className="chap-sidebar-cta">Speak with us</a>
    </aside>
  );
}

function ChapterPage({ n, title, intro, heroImg, children }) {
  const [activeSection, setActiveSection] = useStateP('introduction');
  const currentIdx = CHAPTER_DATA.findIndex((c) => c.n === n);
  const current = CHAPTER_DATA[currentIdx];
  const next = CHAPTER_DATA[currentIdx + 1];

  // Track which section is currently in view
  useEffectP(() => {
    const els = document.querySelectorAll('[data-chap-section]');
    if (!els.length) return;
    const obs = new IntersectionObserver(
      (entries) => {
        const visible = entries
          .filter((e) => e.isIntersecting)
          .sort((a, b) => a.boundingClientRect.top - b.boundingClientRect.top)[0];
        if (visible) setActiveSection(visible.target.getAttribute('data-chap-section'));
      },
      { rootMargin: '-25% 0px -65% 0px' }
    );
    els.forEach((e) => obs.observe(e));
    return () => obs.disconnect();
  }, []);

  const handleSectionClick = (e, id) => {
    e.preventDefault();
    const el = document.getElementById(id);
    if (el) {
      el.scrollIntoView({ behavior: 'smooth', block: 'start' });
      history.replaceState(null, '', '#' + id);
    }
  };

  return (
    <main className="chap-page">
      <SubHeader current="" />

      {/* Rob (June 10): "picture going all the way across, text overlaying the picture in white" */}
      <header
        className={'chap-hero' + (heroImg ? ' chap-hero--photo' : '')}
        style={heroImg ? { backgroundImage: `url(${heroImg})` } : undefined}
        data-chap-section="introduction" id="introduction"
      >
        <div className="chap-hero-wrap">
          <div className="chap-hero-text">
            <Reveal><div className="chap-hero-num">Division {current.roman}</div></Reveal>
            <Reveal delay={1}><h1 className="chap-hero-ttl">{fmtWh4P(title)}</h1></Reveal>
            {intro.map((p, i) => (
              <Reveal key={i} delay={2 + i}><p className="chap-hero-lede">{fmtWh4P(p)}</p></Reveal>
            ))}
          </div>
        </div>
      </header>

      <div className="chap-body-wrap">
        <div className="chap-body">
          {children}
          {next && (
            <Reveal>
              <a href={next.file} className="chap-next">
                <span className="chap-next-eyebrow">Up next · Division {next.roman}</span>
                <span className="chap-next-title">
                  Next division ({next.roman}) — {fmtWh4P(next.title)}
                  <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round">
                    <path d="M5 12h14M13 5l7 7-7 7" />
                  </svg>
                </span>
              </a>
            </Reveal>
          )}
        </div>
        <ChapterSidebar currentN={n} activeSection={activeSection} onSectionClick={handleSectionClick} />
      </div>

      <SubFooter />
      <CookieNoticeP />
    </main>
  );
}

/* Helper to wrap a chapter section with a tracked id */
function ChapSection({ id, eyebrow, heading, children }) {
  return (
    <section className="chap-section" id={id} data-chap-section={id}>
      {eyebrow && <Reveal><p className="chap-eyebrow">{eyebrow}</p></Reveal>}
      {heading && <Reveal delay={1}><h2 className="chap-h2">{fmtWh4P(heading)}</h2></Reveal>}
      <Reveal delay={2}><div className="chap-prose">{children}</div></Reveal>
    </section>
  );
}

Object.assign(window, {
  ROUTES, useScrollYP, Reveal, ArrowSm, Check, Avatar,
  SubHeader, PageHero, CTABand, TeamSection, SubFooter, SubPage,
  ChapterPage, ChapterSidebar, ChapSection, CHAPTER_DATA,
});
