// Shared chrome for legal pages — nav, footer, and the page-shell layout

// Page-transition helper: prefetch sibling legal pages on idle so navigation is instant,
// and crossfade by fading out before nav and fading the body in on load.
(function setupLegalTransitions() {
  if (typeof window === 'undefined' || window.__legalTransitionsSetup) return;
  window.__legalTransitionsSetup = true;

  const SIBLINGS = ['Privacy.html', 'Terms.html', 'Accessibility.html', 'Cookies.html'];

  // Inject the fade-in/out stylesheet once.
  const style = document.createElement('style');
  style.textContent = `
    body { opacity: 0; transition: opacity 0.32s cubic-bezier(0.22,1,0.36,1); }
    body.legal-ready { opacity: 1; }
    body.legal-leaving { opacity: 0; }
  `;
  document.head.appendChild(style);

  // Fade in once everything has rendered.
  const fadeIn = () => {
    requestAnimationFrame(() => {
      requestAnimationFrame(() => document.body.classList.add('legal-ready'));
    });
  };
  if (document.readyState === 'complete' || document.readyState === 'interactive') {
    fadeIn();
  } else {
    document.addEventListener('DOMContentLoaded', fadeIn, {once: true});
  }

  // Prefetch sibling pages once the page is idle — only on legal pages themselves,
  // since this chrome is shared with other sections (programs, careers, etc).
  const isLegalPage = location.pathname.includes('/legal/') ||
    SIBLINGS.includes(location.pathname.split('/').pop());
  const prefetchSiblings = () => {
    const here = location.pathname.split('/').pop();
    SIBLINGS.filter(s => s !== here).forEach(s => {
      const link = document.createElement('link');
      link.rel = 'prefetch';
      link.href = s;
      link.as = 'document';
      document.head.appendChild(link);
    });
  };
  if (isLegalPage) {
    if ('requestIdleCallback' in window) {
      requestIdleCallback(prefetchSiblings, {timeout: 1500});
    } else {
      setTimeout(prefetchSiblings, 600);
    }
  }

  // Intercept sibling-page links: fade out, then navigate.
  document.addEventListener('click', (e) => {
    const a = e.target.closest('a[data-legal-link]');
    if (!a) return;
    const href = a.getAttribute('href');
    if (!href || href.startsWith('#') || a.target === '_blank') return;
    if (e.metaKey || e.ctrlKey || e.shiftKey || e.altKey) return;
    e.preventDefault();
    document.body.classList.remove('legal-ready');
    document.body.classList.add('legal-leaving');
    setTimeout(() => { window.location.href = href; }, 220);
  });

  // Restore opacity if user uses Back/Forward (BFCache).
  window.addEventListener('pageshow', (e) => {
    if (e.persisted) {
      document.body.classList.remove('legal-leaving');
      document.body.classList.add('legal-ready');
    }
  });
})();

const LegalNav = () => {
  const [scrolled, setScrolled] = React.useState(false);

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

  return (
    <header style={{
      position: 'fixed', top: 0, left: 0, right: 0, zIndex: 50,
      padding: scrolled ? '12px 0' : '20px 0',
      paddingTop: scrolled
        ? 'max(12px, env(safe-area-inset-top))'
        : 'max(20px, env(safe-area-inset-top))',
      transition: 'all 0.4s var(--ease-out)',
    }}>
      <div className="container" style={{
        display: 'flex', alignItems: 'center', justifyContent: 'space-between',
        background: scrolled ? 'rgba(13, 21, 48, 0.72)' : 'rgba(13, 21, 48, 0.85)',
        backdropFilter: 'blur(20px) saturate(1.4)',
        WebkitBackdropFilter: 'blur(20px) saturate(1.4)',
        border: '1px solid rgba(255,255,255,0.08)',
        borderRadius: 999,
        padding: '10px 14px 10px 20px',
        boxShadow: scrolled ? '0 10px 40px rgba(13,21,48,0.25)' : 'none',
        transition: 'all 0.4s var(--ease-out)',
      }}>
        <a href="../" style={{display: 'flex', alignItems: 'center', gap: 10, color: '#fff'}}>
          <div style={{
            width: 38, height: 38, borderRadius: 10, background: '#fff',
            display: 'flex', alignItems: 'center', justifyContent: 'center', overflow: 'hidden',
          }}>
            <img src="../shared-assets/keats-logo.jpeg" alt="Keats Learning Academy" style={{width: '100%', height: '100%', objectFit: 'cover'}}/>
          </div>
          <span style={{
            fontFamily: 'var(--font-display)', fontWeight: 700,
            fontSize: 17, letterSpacing: '-0.02em',
          }}>Keats Learning Academy</span>
        </a>

        <div style={{display: 'flex', alignItems: 'center', gap: 14, flexShrink: 0}}>
          <a href="../" style={{
            color: 'rgba(255,255,255,0.82)', fontSize: 13.5, fontWeight: 500,
            whiteSpace: 'nowrap', padding: '8px 14px', borderRadius: 999,
          }}>← Back to site</a>
        </div>
      </div>
    </header>
  );
};

// =========== LEGAL PAGE SHELL — shared header + sidebar + body ===========
const LegalShell = ({ eyebrow, title, intro, lastUpdated, children, active }) => {
  const pages = [
    { slug: 'Privacy.html',       label: 'Privacy Policy' },
    { slug: 'Terms.html',         label: 'Terms of Service' },
    { slug: 'Accessibility.html', label: 'Accessibility' },
    { slug: 'Cookies.html',       label: 'Cookie Settings' },
  ];

  return (
    <>
      {/* HERO STRIP */}
      <section style={{
        position: 'relative',
        background: 'var(--ink)', color: '#fff',
        paddingTop: 140, paddingBottom: 70,
        overflow: 'hidden',
      }}>
        <div style={{
          position: 'absolute', inset: 0,
          background: 'radial-gradient(ellipse at 80% 20%, rgba(217, 162, 74, 0.15), transparent 55%), radial-gradient(ellipse at 10% 90%, rgba(33, 52, 110, 0.45), transparent 60%)',
          pointerEvents: 'none',
        }}/>
        <div className="container" style={{position: 'relative', zIndex: 2, maxWidth: 1100}}>
          <div style={{
            fontFamily: 'var(--font-mono)', fontSize: 12, letterSpacing: '0.22em',
            textTransform: 'uppercase', color: 'var(--gold-300)', marginBottom: 18,
            display: 'flex', alignItems: 'center', gap: 12, flexWrap: 'wrap',
          }}>
            <span style={{
              width: 8, height: 8, borderRadius: '50%', background: 'var(--gold-400)',
              boxShadow: '0 0 0 4px rgba(217, 162, 74, 0.25)',
            }}/>
            {eyebrow}
          </div>
          <h1 style={{
            fontFamily: 'var(--font-display)', fontWeight: 700,
            fontSize: 'clamp(38px, 5.5vw, 64px)', lineHeight: 1.0,
            letterSpacing: '-0.04em', margin: 0, maxWidth: '20ch',
          }}>{title}</h1>
          {intro && (
            <p style={{
              fontSize: 18, lineHeight: 1.55, color: 'rgba(255,255,255,0.78)',
              maxWidth: 720, margin: '24px 0 0',
            }}>{intro}</p>
          )}
          {lastUpdated && (
            <div style={{
              marginTop: 28, fontSize: 12.5, color: 'rgba(255,255,255,0.5)',
              fontFamily: 'var(--font-mono)', letterSpacing: '0.08em',
            }}>
              LAST UPDATED · {lastUpdated}
            </div>
          )}
        </div>
      </section>

      {/* CONTENT — sidebar + article */}
      <section style={{padding: '80px 0 120px', background: 'var(--paper)'}}>
        <div className="container" style={{maxWidth: 1100}}>
          <div style={{
            display: 'grid',
            gridTemplateColumns: '220px minmax(0, 1fr)',
            gap: 64,
          }} className="legal-grid">

            {/* Sidebar nav */}
            <aside className="legal-sidebar" style={{position: 'sticky', top: 100, alignSelf: 'start'}}>
              <div style={{
                fontFamily: 'var(--font-mono)', fontSize: 11, letterSpacing: '0.18em',
                color: 'var(--ink-soft)', opacity: 0.55, textTransform: 'uppercase',
                marginBottom: 16,
              }}>Legal &amp; policies</div>
              <nav style={{display: 'flex', flexDirection: 'column', gap: 2}}>
                {pages.map(p => {
                  const isActive = p.slug === active;
                  return (
                    <a key={p.slug} href={p.slug} data-legal-link="true" style={{
                      padding: '10px 14px',
                      borderRadius: 10,
                      fontSize: 14,
                      fontWeight: isActive ? 600 : 500,
                      color: isActive ? 'var(--ink)' : 'var(--ink-soft)',
                      background: isActive ? '#fff' : 'transparent',
                      border: isActive ? '1px solid var(--line-strong)' : '1px solid transparent',
                      boxShadow: isActive ? '0 4px 14px -8px rgba(13,21,48,0.2)' : 'none',
                      display: 'flex', alignItems: 'center', gap: 10,
                      transition: 'all 0.15s',
                    }}>
                      {isActive && (
                        <span style={{
                          width: 4, height: 16, borderRadius: 4, background: 'var(--gold-500)',
                        }}/>
                      )}
                      {p.label}
                    </a>
                  );
                })}
              </nav>

              <div style={{
                marginTop: 32, padding: 18,
                background: '#fff', border: '1px solid var(--line)', borderRadius: 14,
              }}>
                <div style={{fontSize: 12.5, fontWeight: 600, color: 'var(--ink)', marginBottom: 4}}>
                  Questions?
                </div>
                <div style={{fontSize: 12, color: 'var(--ink-soft)', marginBottom: 12, lineHeight: 1.5}}>
                  We're happy to help.
                </div>
                <a href="mailto:admin@keatslearningacademy.com" style={{
                  display: 'inline-flex', alignItems: 'center', gap: 8,
                  background: 'var(--ink)', color: '#fff',
                  fontSize: 12.5, fontWeight: 500,
                  padding: '9px 14px', borderRadius: 999,
                  textDecoration: 'none',
                }}>
                  <svg width="13" height="13" viewBox="0 0 16 16" fill="none" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round" strokeLinejoin="round">
                    <rect x="2" y="3.5" width="12" height="9" rx="1.5"/>
                    <path d="M2.5 4.5l5.5 4 5.5-4"/>
                  </svg>
                  Email us
                </a>
              </div>
            </aside>

            {/* Article */}
            <article className="legal-article">
              {children}
            </article>
          </div>
        </div>

        <style>{`
          @media (max-width: 860px) {
            .legal-grid { grid-template-columns: 1fr !important; gap: 32px !important; }
            .legal-sidebar { position: static !important; }
          }
          .legal-article h2 {
            font-family: var(--font-display); font-weight: 700;
            font-size: 26px; letter-spacing: -0.02em;
            margin: 56px 0 16px; color: var(--ink);
            scroll-margin-top: 100px;
          }
          .legal-article h2:first-child { margin-top: 0; }
          .legal-article h3 {
            font-family: var(--font-display); font-weight: 600;
            font-size: 18px; letter-spacing: -0.015em;
            margin: 32px 0 10px; color: var(--ink);
          }
          .legal-article p, .legal-article li {
            font-size: 15.5; line-height: 1.7; color: var(--ink-soft);
          }
          .legal-article p { margin: 0 0 16px; }
          .legal-article ul { padding-left: 20px; margin: 0 0 16px; }
          .legal-article li { margin-bottom: 8px; }
          .legal-article a { color: var(--navy-700); text-decoration: underline; text-underline-offset: 3px; }
          .legal-article strong { color: var(--ink); font-weight: 600; }
          .legal-article .callout {
            background: #fff; border: 1px solid var(--line-strong);
            border-radius: 14px; padding: 20px 22px;
            display: flex; gap: 14px; align-items: flex-start;
            margin: 24px 0;
          }
          .legal-article .callout .dot {
            width: 8px; height: 8px; border-radius: 50%;
            background: var(--gold-500); flex-shrink: 0; margin-top: 8px;
          }
          .legal-article .callout p { margin: 0; font-size: 14.5; }
          .legal-article .meta {
            font-family: var(--font-mono); font-size: 11; letter-spacing: 0.18em;
            color: var(--ink-soft); opacity: 0.55; text-transform: uppercase;
            margin-bottom: 8px;
          }
        `}</style>
      </section>
    </>
  );
};

// =========== FOOTER (slim) ===========
const CanonicalFooterCol = ({title, links}) => (
  <div>
    <div style={{fontFamily: 'var(--font-mono)', fontSize: 11, letterSpacing: '0.18em', color: 'rgba(255,255,255,0.45)', textTransform: 'uppercase', marginBottom: 16}}>{title}</div>
    <div style={{display: 'flex', flexDirection: 'column', gap: 10}}>
      {links.map(l => {
        const isObj = typeof l === 'object';
        const label = isObj ? l.label : l;
        const href = isObj ? l.href : '#';
        const external = href.startsWith('http');
        return (
          <a key={label} href={href} onClick={isObj ? l.onClick : undefined}
             {...(external ? {target: '_blank', rel: 'noopener'} : {})}
             style={{color: 'rgba(255,255,255,0.7)', fontSize: 14, textDecoration: 'none'}}>
            {label}
          </a>
        );
      })}
    </div>
  </div>
);

const LegalFooter = () => (
  <footer style={{background: 'var(--navy-950)', color: 'rgba(255,255,255,0.7)', padding: '80px 0 40px'}}>
    <div className="container">
      <div style={{display: 'grid', gridTemplateColumns: 'minmax(0, 1.4fr) repeat(4, minmax(0, 1fr))', gap: 40}} className="footer-grid">
        <div>
          <div style={{display: 'flex', alignItems: 'center', gap: 10, color: '#fff', marginBottom: 20}}>
            <div style={{width: 36, height: 36, borderRadius: 8, overflow: 'hidden', background: '#fff'}}>
              <img src="../shared-assets/keats-logo.jpeg" alt="Keats Learning Academy" style={{width: '100%', height: '100%', objectFit: 'cover'}}/>
            </div>
            <span style={{fontFamily: 'var(--font-display)', fontWeight: 700, fontSize: 19, letterSpacing: '-0.02em'}}>Keats Learning Academy</span>
          </div>
          <p style={{fontSize: 14, lineHeight: 1.6, maxWidth: 320, margin: 0}}>
            A modern tutoring academy built for curious minds, caring parents, and the space between. Est. 2025 · Vancouver.
          </p>
          <div style={{marginTop: 24, fontSize: 13, lineHeight: 1.7}}>
            <strong style={{color: '#fff', fontWeight: 600}}>North Vancouver</strong><br/>
            1258 Lynn Valley Rd #103<br/>
            North Vancouver, BC V7J 2A3<br/>
            <br/>
            {/* Kitsilano · coming soon line temporarily removed pre-launch. */}
            <a href="tel:+17784880188" style={{color: 'var(--gold-300)', fontWeight: 600}}>+1 (778) 488-0188</a><br/>
            <a href="mailto:admin@keatslearningacademy.com" style={{color: 'var(--gold-300)'}}>admin@keatslearningacademy.com</a>
          </div>
        </div>
        <CanonicalFooterCol title="Programs" links={[
          {label: 'Private One-on-One Tutoring', href: '../private-tutoring-north-vancouver/'},
          {label: 'Group Tutoring K–12', href: '../group-tutoring-north-vancouver/'},
          {label: 'Special Needs Tutoring', href: '../tutoring-for-adhd/'},
          {label: 'AP & IB Exam Prep', href: '../ap-ib-tutoring-north-vancouver/'},
        ]}/>
        <CanonicalFooterCol title="Company" links={[
          {label: 'About us', href: '../about-us/'},
          {label: 'Meet the tutors', href: '../tutors/'},
          {label: 'Careers', href: '../careers/'},
        ]}/>
        <CanonicalFooterCol title="Resources" links={[
          {label: 'Resources', href: '../blog/'},
          {label: 'Referral program', href: '../referral/'},
        ]}/>
        <CanonicalFooterCol title="Connect" links={[
          {label: 'Parent sign-in', href: '#', onClick: (e) => { e.preventDefault(); window.dispatchEvent(new CustomEvent('keats:open-signin')); }},
          {label: 'Instagram', href: 'https://www.instagram.com/keats_academy/'},
          {label: 'LinkedIn', href: 'https://www.linkedin.com/company/keatsedu/'},
          {label: 'YouTube', href: 'https://www.youtube.com/@Asal-keatsacademy'},
        ]}/>
      </div>
      <div style={{marginTop: 64, paddingTop: 24, borderTop: '1px solid rgba(255,255,255,0.1)', display: 'flex', justifyContent: 'space-between', flexWrap: 'wrap', gap: 16, fontSize: 12, color: 'rgba(255,255,255,0.5)'}}>
        <div>© 2026 Keats Learning Academy. All rights reserved.</div>
        <div style={{display: 'flex', gap: 24}}>
          <a href="../privacy-policy/" style={{color: 'rgba(255,255,255,0.5)', textDecoration: 'none'}}>Privacy</a>
          <a href="../terms-conditions/" style={{color: 'rgba(255,255,255,0.5)', textDecoration: 'none'}}>Terms</a>
          <a href="../refund-policy/" style={{color: 'rgba(255,255,255,0.5)', textDecoration: 'none'}}>Refund policy</a>
          <a href="../accessibility/" style={{color: 'rgba(255,255,255,0.5)', textDecoration: 'none'}}>Accessibility</a>
          <a href="../cookies/" style={{color: 'rgba(255,255,255,0.5)', textDecoration: 'none'}}>Cookie settings</a>
        </div>
      </div>
    </div>
    <style>{`
      @media (max-width: 900px) { .footer-grid { grid-template-columns: 1fr 1fr !important; } }
      @media (max-width: 500px) { .footer-grid { grid-template-columns: 1fr !important; } }
    `}</style>
  </footer>
);

window.LegalNav = LegalNav;
window.LegalShell = LegalShell;
window.LegalFooter = LegalFooter;
