/* Everbloom landing - sections part A: helpers, Header, Hero, Wedge, GuestPhotos, Invitations */

const { useState, useEffect, useRef, useContext } = React;

function scrollToId(id) {
  const el = document.getElementById(id);
  if (el) window.scrollTo({ top: el.getBoundingClientRect().top + window.scrollY - 60, behavior: 'smooth' });
}

/* Reveal-on-scroll: scroll-listener based (IntersectionObserver is not
   reliable in every render/screenshot environment). */
const _revQueue = [];
function _revCheck(margin) {
  const vh = window.innerHeight; const m = margin || 0.92;
  for (let i = _revQueue.length - 1; i >= 0; i--) {
    const it = _revQueue[i];
    const r = it.el.getBoundingClientRect();
    if (r.top < vh * m && r.bottom > -60) { setTimeout(it.cb, it.delay); _revQueue.splice(i, 1); }
  }
}
if (!window.__ebRevInit) {
  window.__ebRevInit = true;
  window.addEventListener('scroll', () => _revCheck(0.92), { passive: true });
  window.addEventListener('resize', () => _revCheck(0.92));
  // safety: ensure nothing stays hidden if scroll never fires
  setTimeout(() => _revCheck(1.4), 1800);
}
function registerInView(el, cb, delay) {
  _revQueue.push({ el, cb, delay: delay || 0 });
  _revCheck(1.05);
  requestAnimationFrame(() => _revCheck(1.05));
  setTimeout(() => _revCheck(1.05), 140);
  setTimeout(() => _revCheck(0.92), 650);
}

function Reveal({ children, as = 'div', delay = 0, className = '', ...rest }) {
  const ref = useRef(null);
  useEffect(() => {
    const el = ref.current;
    if (!el) return;
    registerInView(el, () => {
      el.classList.add('in');
      // Fallback: if CSS transitions are frozen (some screenshot/render
      // environments), force the resting state so content is never invisible.
      setTimeout(() => {
        if (getComputedStyle(el).opacity === '0') {
          el.style.transition = 'none';
          el.style.opacity = '1';
          el.style.transform = 'none';
        }
      }, 950);
    }, delay);
  }, [delay]);
  const Tag = as;
  return <Tag ref={ref} className={('reveal ' + className).trim()} {...rest}>{children}</Tag>;
}

function Eyebrow({ children, center, hero }) {
  return <span className={'lp-eyebrow' + (center ? ' center' : '') + (hero ? ' lp-hero-eyebrow' : '')}>{children}</span>;
}

/* ---------------- Header ---------------- */
function Header() {
  const { lang, setLang, t } = useContext(window.EB_LangContext);
  const [scrolled, setScrolled] = useState(false);
  const [overHero, setOverHero] = useState(true);
  useEffect(() => {
    const onScroll = () => {
      setScrolled(window.scrollY > 24);
      setOverHero(window.scrollY < window.innerHeight - 130);
    };
    onScroll();
    window.addEventListener('scroll', onScroll, { passive: true });
    return () => window.removeEventListener('scroll', onScroll);
  }, []);
  const cls = 'lp-header' + (scrolled ? ' scrolled' : '') + (overHero ? ' on-hero' : '');
  return (
    <header className={cls}>
      <div className="lp-container lp-header-inner">
        <a href="#top" className="lp-logo" onClick={(e)=>{e.preventDefault(); window.scrollTo({top:0,behavior:'smooth'});}}>
          <img className="lp-logo-mark" src="assets/logo-mark.png" alt="Sarà per sempre sì" />
          <span className="lp-logo-text">Sarà per sempre <em>sì</em></span>
        </a>
        <nav className="lp-nav">
          <a href="#photos" onClick={(e)=>{e.preventDefault();scrollToId('photos');}}>{t.nav.photos}</a>
          <a href="#invites" onClick={(e)=>{e.preventDefault();scrollToId('invites');}}>{t.nav.invites}</a>
          <a href="#rsvp" onClick={(e)=>{e.preventDefault();scrollToId('rsvp');}}>{t.nav.rsvp}</a>
          <a href="#ai" onClick={(e)=>{e.preventDefault();scrollToId('ai');}}>{t.nav.ai}</a>
          <a href="#founding" onClick={(e)=>{e.preventDefault();scrollToId('founding');}}>{t.nav.founding}</a>
        </nav>
        <div className="lp-header-actions">
          <div className="lp-lang" role="group" aria-label="Language">
            <button className={lang==='it'?'active':''} onClick={()=>setLang('it')}>IT</button>
            <button className={lang==='en'?'active':''} onClick={()=>setLang('en')}>EN</button>
          </div>
          <a className="lp-btn lp-btn--primary" href="#founding" onClick={(e)=>{e.preventDefault();scrollToId('founding');}}
             style={{ padding: '12px 22px', fontSize: '0.92rem' }}>
            {t.nav.cta}
          </a>
        </div>
      </div>
    </header>
  );
}

/* ---------------- Hero ---------------- */
function Hero() {
  const { t } = useContext(window.EB_LangContext);
  return (
    <section className="lp-hero" id="top" data-screen-label="Hero">
      <div className="lp-hero-bg">
        <div className="lp-hero-fallback" />
      </div>
      <div className="lp-hero-scrim" />
      <div className="lp-hero-grain" />
      <div className="lp-container lp-hero-inner">
        <Reveal><Eyebrow hero>{t.hero.eyebrow}</Eyebrow></Reveal>
        <Reveal delay={80}><h1>{t.hero.title}</h1></Reveal>
        <Reveal delay={160}><p className="lp-sub">{t.hero.sub}</p></Reveal>
        <Reveal delay={240} className="lp-hero-cta">
          <a className="lp-btn lp-btn--gold lp-btn--lg" href="#founding" onClick={(e)=>{e.preventDefault();scrollToId('founding');}}>
            {t.hero.cta} <EBIcon name="arrow-right" />
          </a>
          <a className="lp-btn lp-btn--light" href="#photos" onClick={(e)=>{e.preventDefault();scrollToId('photos');}}>
            <EBIcon name="play" /> {t.hero.secondary}
          </a>
        </Reveal>
        <Reveal delay={320}>
          <div className="lp-hero-trust" style={{ marginTop: '30px' }}>
            <span className="dots"><span /><span /><span /><span /></span>
            {t.hero.trust}
          </div>
        </Reveal>
      </div>
      <div className="lp-hero-scroll" aria-hidden="true"><div className="mouse" /></div>
    </section>
  );
}

/* ---------------- Wedge ---------------- */
function Wedge() {
  const { t } = useContext(window.EB_LangContext);
  const icons = ['clipboard-list', 'qr-code', 'heart'];
  return (
    <section className="lp-section">
      <div className="lp-container">
        <Reveal style={{ textAlign:'center', marginBottom:'54px' }}>
          <Eyebrow center>{t.wedge.eyebrow}</Eyebrow>
        </Reveal>
        <div className="lp-wedge">
          {t.wedge.items.map((it, i) => (
            <Reveal className="lp-wedge-col" key={i} delay={i*90}>
              <div className="lp-wedge-num">0{i+1}</div>
              <h3>{it.k}</h3>
              <p>{it.t}</p>
            </Reveal>
          ))}
        </div>
        <Reveal className="lp-wedge-sub" delay={120}>
          {t.wedge.sub[0]}<b>{t.wedge.sub[1]}</b>{t.wedge.sub[2]}<b>{t.wedge.sub[3]}</b>{t.wedge.sub[4]}
        </Reveal>
      </div>
    </section>
  );
}

/* ---------------- Guest Photos (showpiece) ---------------- */
function GuestPhotos() {
  const { t } = useContext(window.EB_LangContext);
  return (
    <section className="lp-section alt" id="photos" data-screen-label="Guest Photos">
      <div className="lp-container">
        <div className="lp-feature">
          <Reveal className="lp-feature-media">
            <div className="lp-phone-stack">
              <PhoneFrame><ScreenGallery /></PhoneFrame>
              <PhoneFrame><ScreenQR /></PhoneFrame>
              <PhoneFrame><ScreenLive tone="ph-f" /></PhoneFrame>
            </div>
          </Reveal>
          <div>
            <Reveal><Eyebrow>{t.photos.eyebrow}</Eyebrow></Reveal>
            <Reveal delay={70}><h2>{t.photos.title}</h2></Reveal>
            <Reveal delay={130}><p className="lp-lead">{t.photos.lead}</p></Reveal>
            <Reveal delay={180}>
              <ul className="lp-bullets">
                {t.photos.bullets.map((b, i) => (
                  <li key={i}><EBIcon name="check" />{b}</li>
                ))}
              </ul>
            </Reveal>
          </div>
        </div>
      </div>
    </section>
  );
}

/* ---------------- Invitations (envelope animation) ---------------- */
function Invitations() {
  const { t } = useContext(window.EB_LangContext);
  const [open, setOpen] = useState(false);
  return (
    <section className="lp-section" id="invites" data-screen-label="Invitations">
      <div className="lp-container">
        <div className="lp-feature flip">
          <div className="lp-feature-media">
            <div>
              <div className={'lp-envelope' + (open ? ' open' : '')} onClick={() => setOpen(o => !o)}>
                <div className="lp-env-body" />
                <div className="lp-env-flap" />
                <div className="lp-env-card">
                  <div className="mono">Maya &amp; Theo</div>
                  <div className="rule" />
                  <div className="meta">Save the Date</div>
                  <h4>14 . 06 . 2025</h4>
                  <div className="meta">Briarwood · Lugano</div>
                </div>
                <div className="lp-env-pocket" />
                <div className="lp-env-seal"><EBIcon name="heart" /></div>
              </div>
              <div className="lp-env-hint"><EBIcon name="hand-pointer" /> {t.invites.hint}</div>
            </div>
          </div>
          <div>
            <Reveal><Eyebrow>{t.invites.eyebrow}</Eyebrow></Reveal>
            <Reveal delay={70}><h2>{t.invites.title}</h2></Reveal>
            <Reveal delay={130}><p className="lp-lead">{t.invites.lead}</p></Reveal>
            <Reveal delay={180}>
              <ul className="lp-bullets">
                {t.invites.bullets.map((b, i) => <li key={i}><EBIcon name="check" />{b}</li>)}
              </ul>
            </Reveal>
          </div>
        </div>
      </div>
    </section>
  );
}

Object.assign(window, { Reveal, Eyebrow, scrollToId, Header, Hero, Wedge, GuestPhotos, Invitations });
