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

// ─── Icons (Lucide-style, 1.5px stroke) ───
const Icon = ({ name, size = 20 }) => {
  const paths = {
    play: <polygon points="6 4 20 12 6 20 6 4" />,
    mic: <><rect x="9" y="2" width="6" height="12" rx="3" /><path d="M5 11a7 7 0 0 0 14 0" /><line x1="12" y1="18" x2="12" y2="22" /></>,
    lock: <><rect x="4" y="11" width="16" height="10" rx="2" /><path d="M8 11V7a4 4 0 0 1 8 0v4" /></>,
    shield: <path d="M12 2 4 6v6c0 5 3.5 9 8 10 4.5-1 8-5 8-10V6l-8-4z" />,
    calendar: <><rect x="3" y="5" width="18" height="16" rx="2" /><line x1="3" y1="10" x2="21" y2="10" /><line x1="8" y1="3" x2="8" y2="7" /><line x1="16" y1="3" x2="16" y2="7" /></>,
    heart: <path d="M20.84 4.61a5.5 5.5 0 0 0-7.78 0L12 5.67l-1.06-1.06a5.5 5.5 0 0 0-7.78 7.78l1.06 1.06L12 21.23l7.78-7.78 1.06-1.06a5.5 5.5 0 0 0 0-7.78z" />,
    users: <><path d="M17 21v-2a4 4 0 0 0-4-4H5a4 4 0 0 0-4 4v2" /><circle cx="9" cy="7" r="4" /><path d="M23 21v-2a4 4 0 0 0-3-3.87" /><path d="M16 3.13a4 4 0 0 1 0 7.75" /></>,
    check: <polyline points="4 12 10 18 20 6" />,
    plus: <><line x1="12" y1="5" x2="12" y2="19" /><line x1="5" y1="12" x2="19" y2="12" /></>,
    book: <><path d="M4 19.5A2.5 2.5 0 0 1 6.5 17H20" /><path d="M6.5 2H20v20H6.5A2.5 2.5 0 0 1 4 19.5v-15A2.5 2.5 0 0 1 6.5 2z" /></>,
    gift: <><polyline points="20 12 20 22 4 22 4 12" /><rect x="2" y="7" width="20" height="5" /><line x1="12" y1="22" x2="12" y2="7" /><path d="M12 7H7.5a2.5 2.5 0 0 1 0-5C11 2 12 7 12 7z" /><path d="M12 7h4.5a2.5 2.5 0 0 0 0-5C13 2 12 7 12 7z" /></>,
    mail: <><rect x="3" y="5" width="18" height="14" rx="2" /><polyline points="3 7 12 13 21 7" /></>,
  };
  return (
    <svg width={size} height={size} viewBox="0 0 24 24" fill="none"
         stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round"
         aria-hidden="true" focusable="false">
      {paths[name]}
    </svg>
  );
};

// ─── Header ───
function Header({ page, navigate, cta = 'Start free trial' }) {
  const [open, setOpen] = useState(false);
  const navs = [
    { id: 'about',    label: 'About',    href: '/about/' },
    { id: 'features', label: 'Features', href: '/features/' },
    { id: 'pricing',  label: 'Pricing',  href: '/pricing/' },
    { id: 'support',  label: 'Support',  href: '/support/' },
  ];
  const go = (id, e) => { if (e) e.preventDefault(); navigate(id); setOpen(false); };
  return (
    <header className={`header${open ? ' nav-open' : ''}`} data-em-surface="ink">
      <a className="header__brand" href="/" onClick={(e) => go('home', e)}>
        <span className="header__mark">
          <img src="assets/logo.svg" alt="Everlasting Memory home" width="44" height="44" />
        </span>
      </a>
      <nav id="primary-nav" className="header__nav" aria-label="Primary navigation">
        {navs.map(n => (
          <a key={n.id} href={n.href} className={page === n.id ? 'is-active' : ''} onClick={(e) => go(n.id, e)}>{n.label}</a>
        ))}
        <div className="header__nav-signin">
          <a className="btn btn--gold" href="https://my.everlasting-memory.com/signup">{cta}</a>
          <a className="btn btn--ghost-light" href="https://my.everlasting-memory.com/login">Sign in</a>
        </div>
      </nav>
      <div className="header__actions">
        <a className="btn btn--ghost-light btn--sm" href="https://my.everlasting-memory.com/login">Login</a>
        <a className="btn btn--gold btn--sm" href="https://my.everlasting-memory.com/signup">{cta}</a>
   
      </div>
      <button
        className="header__burger"
        onClick={() => setOpen(o => !o)}
        aria-label="Toggle menu"
        aria-expanded={open}
        aria-controls="primary-nav"
      >
        <span /><span /><span />
      </button>
    </header>
  );
}

// ─── Footer ───
function Footer({ navigate }) {
  const go = (id, e) => { if (e) e.preventDefault(); navigate(id); };
  return (
    <footer className="footer" data-em-surface="ink">
      <div className="footer__rule" />
      <div className="footer__inner">
        <div className="footer__brand">
          <img src="assets/logo.svg" alt="Everlasting Memory" width="44" height="44" />
        </div>
        <div className="footer__cols">
          <div>
            <div className="em-eyebrow">Product</div>
            <a href="/features/" onClick={(e) => go('features', e)}>Features</a>
            <a href="/pricing/"  onClick={(e) => go('pricing', e)}>Pricing</a>
            <a href="https://my.everlasting-memory.com/signup">Sign up</a>
          </div>
          <div>
            <div className="em-eyebrow">Company</div>
            <a href="/about/"   onClick={(e) => go('about', e)}>About us</a>
            <a href="/support/" onClick={(e) => go('support', e)}>Support</a>
          </div>
        </div>
      </div>
      <div className="footer__small">
        <span>&copy; 2026 Everlasting Memory · Made with care for the people we love, and the people we'll miss.</span>
        <nav className="footer__legal" aria-label="Legal">
          <a href="/privacy/" onClick={(e) => go('privacy', e)}>Privacy policy</a>
          <a href="/terms/" onClick={(e) => go('terms', e)}>Terms and conditions</a>
          {EM_GA_ID && <button type="button" className="footer__cookie-btn" onClick={openCookieSettings}>Cookie settings</button>}
        </nav>
      </div>
    </footer>
  );
}

// ─── CTA band (reused) ───
function CtaBand({ title, body, cta = 'Begin Yours', note }) {
  return (
    <section className="cta-band" data-em-surface="ink">
      <div className="cta-band__vignette" />
      <div className="cta-band__inner">
        <h2 dangerouslySetInnerHTML={{ __html: title }} />
        <p>{body}</p>
        <a className="btn btn--gold btn--lg" href="https://my.everlasting-memory.com/signup">{cta}</a>
        {note && <p className="cta-band__note">{note}</p>}
      </div>
    </section>
  );
}

// ─── Family tree illustration (Home + Features) ───
const TREE_ROWS = [
  [{ initials: 'AH', name: 'Arthur', rel: 'Grandad', memorial: true }, { initials: 'EH', name: 'Edith', rel: 'Nan', memorial: true }],
  [{ initials: 'MH', name: 'Margaret', rel: 'Mum' }, { initials: 'DH', name: 'David', rel: 'Dad' }],
  [{ initials: 'You', name: 'You', rel: 'Your card', self: true }, { initials: 'SH', name: 'Sam', rel: 'Brother' }],
];

function FamilyTreeViz() {
  return (
    <div className="viz-tree">
      <div className="viz-tree__filters">
        {['Everyone', 'Living', 'Memorial'].map((label, i) => (
          <span key={label} className={'viz-tree__filter' + (i === 0 ? ' is-on' : '')}>{label}</span>
        ))}
      </div>
      {TREE_ROWS.map((row, r) => (
        <React.Fragment key={r}>
          {r > 0 && <div className="viz-tree__stem" />}
          <div className="viz-tree__row">
            {row.map(p => (
              <div key={p.name} className={'viz-tree__node' + (p.memorial ? ' viz-tree__node--memorial' : '') + (p.self ? ' viz-tree__node--self' : '')}>
                <div className="viz-tree__avatar">{p.initials}</div>
                <div>
                  <div className="viz-tree__name">{p.name}</div>
                  <div className="viz-tree__rel">{p.memorial ? `${p.rel} · In memory` : p.rel}</div>
                </div>
              </div>
            ))}
          </div>
        </React.Fragment>
      ))}
    </div>
  );
}

// ─── Scroll effects: reveal + parallax ───
function ScrollFX() {
  useEffect(() => {
    // Reveal via IntersectionObserver
    const io = new IntersectionObserver((entries) => {
      entries.forEach(e => e.isIntersecting && e.target.classList.add('is-visible'));
    }, { threshold: 0.1, rootMargin: '0px 0px -48px 0px' });
    document.querySelectorAll('[data-reveal]').forEach(el => io.observe(el));

    // Parallax via scroll + rAF
    let ticking = false;
    const update = () => {
      document.querySelectorAll('[data-parallax]').forEach(el => {
        const speed = parseFloat(el.dataset.parallax) || 0.25;
        const rect = el.parentElement.getBoundingClientRect();
        const center = (rect.top + rect.height * 0.5) - window.innerHeight * 0.5;
        const offset = Math.max(-180, Math.min(180, center * speed));
        el.style.transform = `translateY(${offset}px)`;
      });
      ticking = false;
    };
    const onScroll = () => { if (!ticking) { requestAnimationFrame(update); ticking = true; } };
    window.addEventListener('scroll', onScroll, { passive: true });
    update();

    return () => { io.disconnect(); window.removeEventListener('scroll', onScroll); };
  }, []);
  return null;
}

// ─── Legal page layout (Terms, Privacy) ───
// Sections are data: { id, title, body: [string | { table: { head, rows } } | { cookieSettings: true }] }.
function LegalPage({ title, lede, path, updated, notice, sections }) {
  const [active, setActive] = useState(sections[0].id);

  // Highlight the section being read in the contents list.
  useEffect(() => {
    const io = new IntersectionObserver((entries) => {
      entries.forEach((e) => { if (e.isIntersecting) setActive(e.target.id); });
    }, { rootMargin: '-20% 0px -70% 0px' });
    sections.forEach((s) => { const el = document.getElementById(s.id); if (el) io.observe(el); });
    return () => io.disconnect();
  }, []); // sections are fixed for the life of the page

  // <base href="/"> would send plain #links to the homepage, so jump in place.
  const jump = (id, e) => {
    e.preventDefault();
    const el = document.getElementById(id);
    const reduce = window.matchMedia('(prefers-reduced-motion: reduce)').matches;
    el.scrollIntoView({ behavior: reduce ? 'auto' : 'smooth', block: 'start' });
    el.querySelector('h2').focus({ preventScroll: true });
    history.replaceState(history.state, '', path + '#' + id);
  };

  const block = (b, j) => {
    if (typeof b === 'string') return <p key={j}>{b}</p>;
    if (b.table) return (
      <div className="legal__table" key={j} role="region" aria-label={b.table.label} tabIndex={0}>
        <table>
          <thead><tr>{b.table.head.map((h) => <th scope="col" key={h}>{h}</th>)}</tr></thead>
          <tbody>{b.table.rows.map((r) => <tr key={r[0]}>{r.map((c, k) => k === 0 ? <th scope="row" key={k}>{c}</th> : <td key={k}>{c}</td>)}</tr>)}</tbody>
        </table>
      </div>
    );
    if (b.cookieSettings) return EM_GA_ID ? (
      <p key={j}><button type="button" className="btn btn--outline-ink btn--sm" onClick={openCookieSettings}>Change cookie settings</button></p>
    ) : null;
    return null;
  };

  return (
    <div>
      <section className="page-hero" data-em-surface="ink">
        <div className="page-hero__vignette" />
        <div className="page-hero__inner">
          <h1 className="page-hero__title">{title}</h1>
          <p className="page-hero__lede">{lede}</p>
        </div>
      </section>

      <section className="section section--paper legal">
        <div className="legal__inner">
          <nav className="legal__toc" aria-label="Contents">
            <div className="legal__toc-title">Contents</div>
            <ol>
              {sections.map((s) => (
                <li key={s.id}>
                  <a href={path + '#' + s.id} onClick={(e) => jump(s.id, e)} aria-current={active === s.id ? 'true' : undefined}>{s.title}</a>
                </li>
              ))}
            </ol>
          </nav>

          <article className="legal__body">
            {notice && <p className="legal__notice">{notice}</p>}
            <p className="legal__updated">Last updated {updated}</p>
            {sections.map((s, i) => (
              <section className="legal__section" id={s.id} key={s.id} aria-labelledby={s.id + '-title'}>
                <h2 id={s.id + '-title'} tabIndex={-1}><span className="legal__num">{i + 1}.</span> {s.title}</h2>
                {s.body.map(block)}
              </section>
            ))}
          </article>
        </div>
      </section>
    </div>
  );
}

// ─── Analytics + cookie consent ───
// GA4 measurement ID. Set to null to switch analytics off entirely: nothing loads, no cookies
// are set, and neither the banner nor "Cookie settings" appears.
// Google's tag is never in the page HTML: loadAnalytics() adds it only after the visitor accepts.
const EM_GA_ID = 'G-4GVRWMKV2E';
// Analytics only loads on the live site, so local testing and Cloudflare preview URLs
// don't count as visits. The banner still shows everywhere, so it can be tested.
const EM_GA_HOSTS = ['everlasting-memory.com', 'www.everlasting-memory.com'];
const EM_CONSENT_KEY = 'em_cookie_consent';
// The choice is shared with the app (my.everlasting-memory.com) through a cookie on the whole
// domain, em_consent = accepted | declined, kept 12 months. The app's src/js/elm-gtm.js reads and
// writes the same cookie, so a choice made on either site counts on both and nobody is asked twice.
// The cookie wins over this browser's localStorage copy, since every choice on either site writes it.
const EM_SHARED_COOKIE = 'em_consent';
const EM_DOMAIN = 'everlasting-memory.com';
const EM_CONSENT_MAX_AGE = 365 * 24 * 3600; // 12 months, then ask again

function readConsent() {
  const m = /(?:^|;\s*)em_consent=(accepted|declined)(?:;|$)/.exec(document.cookie || '');
  if (m) return m[1];
  try { return localStorage.getItem(EM_CONSENT_KEY); } catch (e) { return null; }
}

// On the live domain the cookie is for every subdomain; elsewhere (localhost, previews) this host only.
function writeConsent(value) {
  try { localStorage.setItem(EM_CONSENT_KEY, value); } catch (e) {}
  const host = window.location.hostname;
  const onDomain = host === EM_DOMAIN || host.endsWith('.' + EM_DOMAIN);
  document.cookie = EM_SHARED_COOKIE + '=' + value + ';max-age=' + EM_CONSENT_MAX_AGE + ';path=/;SameSite=Lax' +
    (onDomain ? ';domain=.' + EM_DOMAIN : '') + (window.location.protocol === 'https:' ? ';Secure' : '');
}

function loadAnalytics() {
  if (!EM_GA_ID || !EM_GA_HOSTS.includes(window.location.hostname)) return;
  window['ga-disable-' + EM_GA_ID] = false;
  if (window._emGaLoaded) return;
  window._emGaLoaded = true;
  const s = document.createElement('script');
  s.async = true;
  s.src = 'https://www.googletagmanager.com/gtag/js?id=' + EM_GA_ID;
  document.head.appendChild(s);
  window.dataLayer = window.dataLayer || [];
  window.gtag = function () { window.dataLayer.push(arguments); };
  window.gtag('js', new Date());
  window.gtag('config', EM_GA_ID); // sends the first page view
}

function clearAnalytics() {
  if (!EM_GA_ID) return;
  window['ga-disable-' + EM_GA_ID] = true; // stops a script already loaded this visit
  const host = window.location.hostname;
  document.cookie.split(';').forEach((c) => {
    const name = c.trim().split('=')[0];
    if (name.indexOf('_ga') === 0) {
      const base = name + '=;expires=Thu, 01 Jan 1970 00:00:00 GMT;path=/';
      document.cookie = base;
      document.cookie = base + ';domain=' + host;
      document.cookie = base + ';domain=.' + host.replace(/^www\./, '');
    }
  });
}

// Client-side navigation doesn't reload the page, so report each route change.
function trackPage(path) {
  if (EM_GA_ID && window._emGaLoaded && readConsent() === 'accepted') {
    window.gtag('event', 'page_view', { page_path: path, page_location: window.location.href, page_title: document.title });
  }
}

function openCookieSettings() {
  window.dispatchEvent(new Event('em-cookie-settings'));
}

function CookieBanner({ navigate }) {
  // 'hidden' → 'open' → 'closing' → 'hidden'; closing keeps it mounted for the exit.
  const [phase, setPhase] = useState('hidden');
  const returnFocus = React.useRef(null);
  const firstBtn = React.useRef(null);

  useEffect(() => {
    if (!EM_GA_ID) return;
    const c = readConsent();
    let t;
    if (c === 'accepted') loadAnalytics();
    else if (c !== 'declined') t = setTimeout(() => setPhase('open'), 600);
    const reopen = () => {
      returnFocus.current = document.activeElement;
      setPhase('open');
      requestAnimationFrame(() => firstBtn.current && firstBtn.current.focus());
    };
    window.addEventListener('em-cookie-settings', reopen);
    return () => { clearTimeout(t); window.removeEventListener('em-cookie-settings', reopen); };
  }, []);

  const choose = (value) => {
    writeConsent(value);
    if (value === 'accepted') loadAnalytics(); else clearAnalytics();
    setPhase('closing');
    setTimeout(() => setPhase('hidden'), 200);
    if (returnFocus.current) { returnFocus.current.focus(); returnFocus.current = null; }
  };

  if (!EM_GA_ID || phase === 'hidden') return null;
  return (
    <section className={'cookie-banner' + (phase === 'closing' ? ' is-closing' : '')}
      data-em-surface="ink" aria-labelledby="cookie-banner-title">
      <div className="cookie-banner__inner">
        <div className="cookie-banner__copy">
          <h2 className="cookie-banner__title" id="cookie-banner-title">Analytics cookies</h2>
          <p>
            May we use analytics cookies to see which pages help people most? They stay off unless you say yes.
            {' '}<a href="/privacy/#cookies" onClick={(e) => { e.preventDefault(); navigate('privacy'); }}>Read our privacy policy</a>
          </p>
        </div>
        <div className="cookie-banner__actions">
          <button type="button" ref={firstBtn} className="btn btn--gold" onClick={() => choose('accepted')}>Accept</button>
          <button type="button" className="btn btn--outline-gold" onClick={() => choose('declined')}>Decline</button>
        </div>
      </div>
    </section>
  );
}

Object.assign(window, { Icon, Header, Footer, CtaBand, FamilyTreeViz, ScrollFX, LegalPage, CookieBanner, trackPage, openCookieSettings });
