// mv-page.jsx — shared page chrome and section primitives for interior pages.
// Hero header, marker-rail sections, figures, index lists, image-slot graphic
// frames, and the site footer. Reveal-on-scroll is built in.

if (typeof document !== 'undefined' && !document.getElementById('mv-page-styles')) {
  const s = document.createElement('style');
  s.id = 'mv-page-styles';
  s.textContent = `
    .mv-reveal{opacity:0}
    .mv-reveal.is-in{opacity:1;animation:mv-rise .75s cubic-bezier(.32,.72,0,1)}
    .mv-stagger > *{opacity:0}
    .mv-stagger.is-in > *{opacity:1;animation:mv-rise .7s cubic-bezier(.32,.72,0,1)}
    .mv-stagger.is-in > *:nth-child(2){animation-delay:.08s}
    .mv-stagger.is-in > *:nth-child(3){animation-delay:.16s}
    .mv-stagger.is-in > *:nth-child(4){animation-delay:.24s}
    .mv-stagger.is-in > *:nth-child(5){animation-delay:.32s}
    @keyframes mv-rise{from{opacity:0;transform:translateY(20px)}to{opacity:1;transform:none}}
    .mv-idxrow{display:grid;grid-template-columns:1fr auto;gap:28px;align-items:baseline;
      padding:26px 0;border-top:1px solid var(--rule);text-decoration:none;transition:padding-left .3s cubic-bezier(.32,.72,0,1)}
    .mv-idxrow:hover{padding-left:8px}
    .mv-idxrow:hover .mv-idxt{color:${MV.gold}}
    image-slot{display:block;width:100%}
    @media (prefers-reduced-motion: reduce){
      .mv-reveal,.mv-stagger > *{opacity:1!important;animation:none!important}}
  `;
  document.head.appendChild(s);
}

function useReveal() {
  React.useEffect(() => {
    const reduce = window.matchMedia && window.matchMedia('(prefers-reduced-motion: reduce)').matches;
    let pending = Array.from(document.querySelectorAll('.mv-reveal, .mv-stagger'));
    if (reduce) { pending.forEach((el) => el.classList.add('is-in')); return; }
    let raf = 0;
    const check = () => {
      const vh = window.innerHeight || document.documentElement.clientHeight;
      pending = pending.filter((el) => {
        const r = el.getBoundingClientRect();
        if (r.top < vh * 0.9 && r.bottom > 0) { el.classList.add('is-in'); return false; }
        return true;
      });
      if (!pending.length) { window.removeEventListener('scroll', onScroll); window.removeEventListener('resize', onScroll); }
    };
    const onScroll = () => { if (!raf) raf = requestAnimationFrame(() => { raf = 0; check(); }); };
    check();
    window.addEventListener('scroll', onScroll, { passive: true });
    window.addEventListener('resize', onScroll, { passive: true });
    return () => { window.removeEventListener('scroll', onScroll); window.removeEventListener('resize', onScroll); if (raf) cancelAnimationFrame(raf); };
  }, []);
}

const MV_NAVY_BG = `radial-gradient(120% 90% at 78% 26%, ${MV.navy} 0%, ${MV.navyDeep} 100%)`;

// Pick the right thin-line motif for a page hero. Every field renders at one
// shared size (MV_FIELD_W × MV_FIELD_H) so the graphic reads the same on every page.
function MVHeroField({ field }) {
  const size = { width: MV_FIELD_W, height: MV_FIELD_H };
  const o = 0.5; // interior fields sit quietly behind the text
  // fields sit high; the opaque nav bar covers whatever passes behind it
  if (field === 'bridge') return <BridgeField on="navy" style={{ right: -210, top: -34, opacity: o, ...size }} />;
  if (field === 'mountain') return <MountainField on="navy" style={{ right: -150, top: -24, opacity: o, ...size }} />;
  if (field === 'orbit') return <OrbitField on="navy" style={{ right: -170, top: -70, opacity: o, ...size }} />;
  if (field === 'globe') return <GlobeField on="navy" style={{ right: -190, top: -86, opacity: 0.55, ...size }} />;
  if (field === 'data') return <DataField on="navy" style={{ right: -190, top: -210, opacity: o, ...size }} />;
  if (field === 'connection') return <ConnectionField on="navy" style={{ right: -190, top: -230, opacity: o, ...size }} />;
  return <MeasurementField variant={field} on="navy" style={{ right: -300, top: -70, opacity: o, ...size }} />;
}

// ── Hero header ──────────────────────────────────────────────
function MVPageHero({ eyebrow, title, sub, field = 'arc', big = false, titleWeight }) {
  return (
    <div className="mv-root mv-hero" data-screen-label={eyebrow}
      style={{ background: MV_NAVY_BG, display: 'flex', flexDirection: 'column', position: 'relative', minHeight: '53vh' }}>
      <MVHeroField field={field} />
      {/* gradient banner: graphic stays behind it, nav text on top */}
      <div aria-hidden="true" style={{ position: 'absolute', top: 0, left: 0, right: 0, height: 168,
        pointerEvents: 'none', zIndex: 1, background: `linear-gradient(to bottom, #02080F 0%, ${MV.navyDeep} 34%, rgba(4,15,26,0) 100%)` }} />
      <MegaNav />
      <div style={{ position: 'relative', zIndex: 1, flex: 1, display: 'flex', flexDirection: 'column', justifyContent: 'center', padding: '40px 80px 56px', width: '100%' }}>
        <div style={{ maxWidth: 1320, margin: '0 auto', width: '100%' }}>
          <div style={{ fontFamily: MV.sans, fontSize: 11, fontWeight: 600, letterSpacing: '.24em',
            textTransform: 'uppercase', color: MV.gold, marginBottom: 30 }}>{eyebrow}</div>
          <h1 className="mv-serif" style={{ margin: 0, color: MV.cream, fontWeight: titleWeight || 500, maxWidth: big ? 1180 : 980,
            fontSize: big ? 'clamp(52px, 6.4vw, 96px)' : 'clamp(40px, 4.8vw, 70px)', lineHeight: big ? 1.0 : 1.06, letterSpacing: big ? '-0.022em' : '-0.014em' }}>{title}</h1>
          {sub && <p style={{ maxWidth: big ? 620 : 560, marginTop: big ? 36 : 30, color: MV.creamDim, fontSize: big ? 17 : 15.5, lineHeight: 1.66 }}>{sub}</p>}
        </div>
      </div>
    </div>
  );
}

// ── Marker-rail section ──────────────────────────────────────
function MVSection({ n, label, theme = 'cream', id, children, stagger, wide = false }) {
  const onNavy = theme === 'navy';
  return (
    <section id={id} className="mv-root" style={{ background: onNavy ? MV.navy : MV.cream,
      padding: '94px 80px 98px', overflow: 'visible', position: 'relative' }}>
      <div className={'mv-reveal' + (stagger ? '' : '')} style={{ display: 'grid', gridTemplateColumns: wide ? '220px 1fr' : '280px 1fr',
        gap: wide ? 56 : 72, alignItems: 'start', maxWidth: wide ? 1480 : 1320, margin: '0 auto' }}>
        <div style={{ borderTop: `2px solid ${onNavy ? MV.gold : MV.navy}`, paddingTop: 20, position: 'sticky', top: 40 }}>
          <span style={{ color: onNavy ? MV.cream : MV.navy, fontSize: 12.5, fontWeight: 600,
            letterSpacing: '.16em', textTransform: 'uppercase' }}>{label}</span>
        </div>
        <div className={stagger ? 'mv-stagger' : ''}>{children}</div>
      </div>
    </section>
  );
}

// Big serif statement
function MVLede({ children, theme = 'cream', max = 760, push = false }) {
  const onNavy = theme === 'navy';
  return (
    <p className="mv-serif" style={{ margin: 0, maxWidth: max, marginLeft: push ? 'auto' : 0, color: onNavy ? MV.cream : MV.navy,
      fontWeight: 500, fontSize: 30, lineHeight: 1.28, letterSpacing: '-0.005em' }}>{children}</p>
  );
}

// Two-up explanatory blocks
function MVBlocks({ items, theme = 'cream' }) {
  const onNavy = theme === 'navy';
  return (
    <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 48, marginTop: 52 }}>
      {items.map((b) => (
        <div key={b.k} style={{ borderTop: `1px solid ${onNavy ? MV.hair : MV.hairNavy}`, paddingTop: 22 }}>
          <h3 className="mv-serif" style={{ margin: '0 0 11px', color: onNavy ? MV.cream : MV.navy, fontWeight: 600, fontSize: 20 }}>{b.k}</h3>
          <p style={{ margin: 0, color: onNavy ? MV.creamDim : MV.slate, fontSize: 14, lineHeight: 1.65 }}>{b.d}</p>
        </div>
      ))}
    </div>
  );
}

// Figures row
function MVFigures({ items }) {
  return (
    <div style={{ display: 'grid', gridTemplateColumns: `repeat(${items.length}, 1fr)`, gap: 40, marginTop: 16,
      borderTop: `1px solid ${MV.hair}`, paddingTop: 34 }}>
      {items.map((f) => (
        <div key={f.l}>
          <div className="mv-serif" style={{ color: f.gold ? MV.gold : MV.cream, fontSize: 44, fontWeight: 500, lineHeight: 0.95 }}>
            {f.real ? f.v : <PH>{f.v}</PH>}
          </div>
          <div style={{ color: MV.creamDim, fontSize: 12.5, lineHeight: 1.5, marginTop: 13, maxWidth: 220 }}>{f.l}</div>
        </div>
      ))}
    </div>
  );
}

// Index list (numbered rows)
function MVIndexList({ items, theme = 'cream' }) {
  const onNavy = theme === 'navy';
  return (
    <div style={{ '--rule': onNavy ? MV.hair : MV.hairNavy }}>
      {items.map((it, i) => (
        <a key={it.t} href={it.href || '#'} id={it.id} className="mv-idxrow" style={{ '--rule': onNavy ? MV.hair : MV.hairNavy }}>
          <span>
            <span className="mv-idxt mv-serif" style={{ display: 'block', color: onNavy ? MV.cream : MV.navy,
              fontSize: 23, fontWeight: 600, transition: 'color .22s ease' }}>{it.t}</span>
            {it.d && <span style={{ display: 'block', marginTop: 7, color: onNavy ? MV.creamDim : MV.slate,
              fontSize: 14, lineHeight: 1.55, maxWidth: 560 }}>{it.d}</span>}
          </span>
          {it.meta && <span style={{ color: onNavy ? MV.creamFaint : 'rgba(61,70,84,0.6)', fontSize: 12.5,
            letterSpacing: '.04em', whiteSpace: 'nowrap' }}>{it.meta}</span>}
        </a>
      ))}
    </div>
  );
}

// Graphic frame around an image-slot
function MVGraphic({ id, h = 320, placeholder = 'Drop an image', shape = 'rounded', theme = 'cream', caption }) {
  const onNavy = theme === 'navy';
  return (
    <figure style={{ margin: 0 }}>
      <div style={{ border: `1px solid ${onNavy ? MV.hair : MV.hairNavy}`, borderRadius: 8, overflow: 'hidden',
        background: onNavy ? 'rgba(244,243,239,0.03)' : 'rgba(8,30,52,0.03)' }}>
        <image-slot id={id} style={{ height: h + 'px' }} shape={shape} radius="0" placeholder={placeholder}></image-slot>
      </div>
      {caption && <figcaption style={{ marginTop: 14, color: onNavy ? MV.creamFaint : 'rgba(61,70,84,0.65)',
        fontSize: 12, letterSpacing: '.04em' }}>{caption}</figcaption>}
    </figure>
  );
}

// ── Footer ───────────────────────────────────────────────────
function MVFooter() {
  const cols = MV_MENUS.filter((m) => m.links).map((m) => ({ label: m.label, links: m.links }));
  return (
    <footer className="mv-root" style={{ background: MV.navyDeep, padding: '78px 80px 46px', borderTop: `1px solid ${MV.hair}` }}>
      <div style={{ maxWidth: 1320, margin: '0 auto' }}>
        <div style={{ display: 'grid', gridTemplateColumns: '1.4fr repeat(5, 1fr)', gap: 40, alignItems: 'start' }}>
          <div>
            <div className="mv-serif" style={{ fontSize: 24, fontWeight: 600, color: MV.cream, letterSpacing: '.01em' }}>ModVedi</div>
            <p style={{ marginTop: 18, maxWidth: 250, color: MV.creamDim, fontSize: 13.5, lineHeight: 1.6 }}>
              We acquire and compound the mission-critical software that runs the physical world.
            </p>
            <div style={{ marginTop: 20, color: MV.gold, fontFamily: MV.sans, fontSize: 11, fontWeight: 600, letterSpacing: '.14em', textTransform: 'uppercase', lineHeight: 1.7 }}>
              See clearly.<br />Build systematically.<br />Compound relentlessly.
            </div>
          </div>
          {cols.map((c) => (
            <div key={c.label}>
              <div style={{ color: MV.gold, fontSize: 11, fontWeight: 600, letterSpacing: '.18em',
                textTransform: 'uppercase', marginBottom: 18 }}>{c.label}</div>
              <div style={{ display: 'flex', flexDirection: 'column', gap: 11 }}>
                {c.links.map((l) => (
                  <a key={l.t} className="mv-link" href={l.href} style={{ color: MV.creamDim, fontSize: 13, textDecoration: 'none' }}>{l.t}</a>
                ))}
              </div>
            </div>
          ))}
        </div>
        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', flexWrap: 'wrap', gap: 16,
          marginTop: 64, paddingTop: 26, borderTop: `1px solid ${MV.hair}` }}>
          <div style={{ color: MV.creamFaint, fontSize: 12, letterSpacing: '.03em' }}>© {new Date().getFullYear()} ModVedi. All rights reserved.</div>
          <div style={{ display: 'flex', gap: 28 }}>
            <a className="mv-link" href="ModVedi - Contact.html" style={{ color: MV.creamDim, fontSize: 12.5, textDecoration: 'none' }}>Contact</a>
            <a className="mv-link" href="ModVedi - Investor Login.html" style={{ color: MV.creamDim, fontSize: 12.5, textDecoration: 'none' }}>Investor Login</a>
            <a className="mv-link" href="#" style={{ color: MV.creamDim, fontSize: 12.5, textDecoration: 'none' }}>Legal</a>
            <a className="mv-link" href="#" style={{ color: MV.creamDim, fontSize: 12.5, textDecoration: 'none' }}>Disclosures</a>
          </div>
        </div>
      </div>
    </footer>
  );
}

// Page wrapper — runs reveal observer.
function MVPage({ hero, children }) {
  useReveal();
  return (
    <div style={{ width: '100%' }}>
      {hero}
      <div style={{ width: '100%' }}>{children}</div>
      <MVFooter />
    </div>
  );
}

Object.assign(window, { useReveal, MVPageHero, MVSection, MVLede, MVBlocks, MVFigures, MVIndexList, MVGraphic, MVFooter, MVPage, MV_NAVY_BG });
