/* Everbloom landing - sections part B: RSVPTables, AITools, Founding, Social, FinalCTA, Footer, App */

const { useState: useStateB, useEffect: useEffectB, useContext: useContextB } = React;
const LangContext = window.EB_LangContext;
const {
  Header, Hero, Wedge, GuestPhotos, Invitations, Reveal, Eyebrow, scrollToId,
  EBIcon, PhoneFrame, ScreenRSVP, ScreenTables,
} = window;

/* ---------------- RSVP + Tables ---------------- */
function RSVPTables() {
  const { t } = useContextB(LangContext);
  return (
    <section className="lp-section sunk" id="rsvp" data-screen-label="RSVP & Tables">
      <div className="lp-container">
        <div className="lp-feature">
          <Reveal className="lp-feature-media">
            <div className="lp-phone-stack">
              <PhoneFrame><ScreenTables /></PhoneFrame>
              <PhoneFrame><ScreenRSVP /></PhoneFrame>
              <PhoneFrame><ScreenRSVP /></PhoneFrame>
            </div>
          </Reveal>
          <div>
            <Reveal><Eyebrow>{t.rsvp.eyebrow}</Eyebrow></Reveal>
            <Reveal delay={70}><h2>{t.rsvp.title}</h2></Reveal>
            <Reveal delay={130}><p className="lp-lead">{t.rsvp.lead}</p></Reveal>
            <Reveal delay={180}>
              <ul className="lp-bullets">
                {t.rsvp.bullets.map((b, i) => <li key={i}><EBIcon name="check" />{b}</li>)}
              </ul>
            </Reveal>
          </div>
        </div>
      </div>
    </section>
  );
}

/* ---------------- AI tools ---------------- */
function AITools() {
  const { t } = useContextB(LangContext);
  const visuals = [
    <div className="lp-ai-visual" key="0">
      <div className="before-after">
        <div className="ph-tone ph-f" />
        <div className="ph-tone ph-e" />
      </div>
      <div style={{ position:'absolute', top:0, bottom:0, left:'50%', width:'2px', background:'rgba(255,255,255,0.85)' }} />
      <div className="lp-ai-icon" style={{ position:'absolute' }}><EBIcon name="wand-sparkles" /></div>
      <div className="tag">{t.ai.cards[0].tag}</div>
    </div>,
    <div className="lp-ai-visual ph-tone ph-c" key="1">
      <div className="lp-ai-icon"><EBIcon name="shirt" /></div>
      <div className="tag">{t.ai.cards[1].tag}</div>
    </div>,
    <div className="lp-ai-visual ph-tone ph-d" key="2">
      <div className="lp-ai-icon"><EBIcon name="sparkles" /></div>
      <div className="tag">{t.ai.cards[2].tag}</div>
    </div>,
  ];
  return (
    <section className="lp-section" id="ai" data-screen-label="AI Tools">
      <div className="lp-container">
        <Reveal style={{ textAlign:'center', maxWidth:'640px', margin:'0 auto' }}>
          <Eyebrow center>{t.ai.eyebrow}</Eyebrow>
          <h2 style={{ fontSize:'clamp(2.1rem,4vw,3.4rem)', marginTop:'18px' }}>{t.ai.title}</h2>
          <p className="lp-lead" style={{ margin:'18px auto 0' }}>{t.ai.lead}</p>
        </Reveal>
        <div className="lp-ai-grid">
          {t.ai.cards.map((c, i) => (
            <Reveal className="lp-ai-card" key={i} delay={i*90}>
              {visuals[i]}
              <div className="lp-ai-body">
                <h3>{c.t}</h3>
                <p>{c.d}</p>
              </div>
            </Reveal>
          ))}
        </div>
      </div>
    </section>
  );
}

/* ---------------- Founding offer + email capture ---------------- */
function monthOptions(t) {
  const opts = [];
  let y = 2026, m = 6; // start June 2026
  for (let i = 0; i < 20; i++) {
    opts.push({ value: `${y}-${String(m).padStart(2,'0')}`, label: `${t.months[m]} ${y}` });
    m++; if (m > 12) { m = 1; y++; }
  }
  return opts;
}

function FoundingForm() {
  const { t } = useContextB(LangContext);
  const [email, setEmail] = useStateB('');
  const [date, setDate] = useStateB('');
  const [err, setErr] = useStateB(false);
  const [sent, setSent] = useStateB(false);
  const [loading, setLoading] = useStateB(false);
  const [apiErr, setApiErr] = useStateB(false);
  const submit = async (e) => {
    e.preventDefault();
    const ok = /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email.trim());
    if (!ok) { setErr(true); return; }
    setErr(false); setApiErr(false); setLoading(true);
    try {
      const res = await fetch('/api/subscribe', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ email: email.trim(), date }),
      });
      if (!res.ok) throw new Error('server');
      setSent(true);
    } catch {
      setApiErr(true);
    } finally {
      setLoading(false);
    }
  };
  if (sent) {
    return (
      <div className="lp-form-card">
        <div className="lp-success">
          <div className="ring"><EBIcon name="check" /></div>
          <h3>{t.founding.successTitle}</h3>
          <p>{t.founding.successBody}</p>
        </div>
      </div>
    );
  }
  return (
    <form className="lp-form-card" onSubmit={submit} noValidate>
      <h3>{t.founding.formTitle}</h3>
      <p className="sub">{t.founding.formSub}</p>
      <div className="lp-field-group">
        <div>
          <label className="lp-label" htmlFor="eb-email">{t.founding.emailLabel}</label>
          <input id="eb-email" type="email" className={'lp-input' + (err ? ' invalid' : '')}
            placeholder={t.founding.emailPlaceholder} value={email}
            onChange={(e)=>{ setEmail(e.target.value); if (err) setErr(false); }} />
          {err && <div className="lp-form-error">{t.founding.errorEmail}</div>}
        </div>
        <div>
          <label className="lp-label" htmlFor="eb-date">{t.founding.dateLabel}</label>
          <select id="eb-date" className="lp-select" value={date} onChange={(e)=>setDate(e.target.value)}>
            <option value="">{t.founding.datePlaceholder}</option>
            {monthOptions(t).map(o => <option key={o.value} value={o.value}>{o.label}</option>)}
            <option value="tbd">{t.months[0]} · ?</option>
          </select>
        </div>
        {apiErr && <div className="lp-form-error">{t.founding.errorServer}</div>}
        <button type="submit" disabled={loading} className="lp-btn lp-btn--primary lp-btn--full lp-btn--lg" style={{ marginTop:'4px' }}>
          {loading ? '…' : <>{t.founding.submit} <EBIcon name="arrow-right" /></>}
        </button>
      </div>
      <div className="lp-form-fine">{t.founding.fine}</div>
    </form>
  );
}

function Founding() {
  const { t } = useContextB(LangContext);
  return (
    <section className="lp-section lp-founding" id="founding" data-screen-label="Founding Offer">
      <div className="lp-container">
        <div className="lp-founding-grid">
          <div>
            <Reveal><span className="lp-badge"><EBIcon name="crown" /> {t.founding.badge}</span></Reveal>
            <Reveal delay={70}>
              <h2>{t.founding.title[0]}<span className="price">{t.founding.title[1]}</span>{t.founding.title[2]}</h2>
            </Reveal>
            <Reveal delay={130}>
              <div className="lp-price-row">
                <span className="lp-price-old">{t.founding.oldPrice}</span>
                <span className="lp-price-new">{t.founding.newPrice}</span>
                <span className="lp-price-note">{t.founding.priceNote}</span>
              </div>
            </Reveal>
            <Reveal delay={180}>
              <div className="lp-scarcity"><EBIcon name="users" /> {t.founding.scarcity}</div>
              <div className="lp-counter"><i /></div>
              <div style={{ fontSize:'0.86rem', color:'var(--ink-2)', marginTop:'8px' }}>{t.founding.counterNote}</div>
            </Reveal>
          </div>
          <Reveal delay={120}><FoundingForm /></Reveal>
        </div>
      </div>
    </section>
  );
}

/* ---------------- Social proof + FAQ ---------------- */
function FAQItem({ q, a }) {
  const [open, setOpen] = useStateB(false);
  const innerRef = React.useRef(null);
  return (
    <div className={'lp-faq-item' + (open ? ' open' : '')}>
      <button className="lp-faq-q" onClick={() => setOpen(o => !o)} aria-expanded={open}>
        {q} <EBIcon name="plus" />
      </button>
      <div className="lp-faq-a" style={{ maxHeight: open ? (innerRef.current ? innerRef.current.scrollHeight + 'px' : '300px') : '0px' }}>
        <div className="lp-faq-a-inner" ref={innerRef}>{a}</div>
      </div>
    </div>
  );
}

function Social() {
  const { t } = useContextB(LangContext);
  return (
    <section className="lp-section alt" data-screen-label="Social proof & FAQ">
      <div className="lp-container">
        <Reveal style={{ textAlign:'center', maxWidth:'620px', margin:'0 auto' }}>
          <Eyebrow center>{t.social.eyebrow}</Eyebrow>
          <h2 style={{ fontSize:'clamp(2rem,4vw,3.2rem)', marginTop:'18px' }}>{t.social.title}</h2>
        </Reveal>
        <div className="lp-quotes">
          {t.social.quotes.map((qq, i) => (
            <Reveal className="lp-quote" key={i} delay={i*90}>
              <div className="stars">{[0,1,2,3,4].map(s => <EBIcon key={s} name="star" />)}</div>
              <p>“{qq.t}”</p>
              <div className="who">{qq.who}</div>
            </Reveal>
          ))}
        </div>
        <Reveal style={{ textAlign:'center', marginTop:'90px' }}>
          <h3 style={{ fontFamily:'var(--font-display)', fontSize:'clamp(1.8rem,3.4vw,2.6rem)', color:'var(--ink)' }}>{t.social.faqTitle}</h3>
        </Reveal>
        <div className="lp-faq">
          {t.social.faqs.map((f, i) => <FAQItem key={i} q={f.q} a={f.a} />)}
        </div>
      </div>
    </section>
  );
}

/* ---------------- Final CTA ---------------- */
function FinalCTA() {
  const { t } = useContextB(LangContext);
  return (
    <section className="lp-section">
      <div className="lp-container lp-final">
        <Reveal><Eyebrow center>{t.social.finalEyebrow}</Eyebrow></Reveal>
        <Reveal delay={70}><h2>{t.social.finalTitle}</h2></Reveal>
        <Reveal delay={130}><p>{t.social.finalBody}</p></Reveal>
        <Reveal delay={180}>
          <a className="lp-btn lp-btn--primary lp-btn--lg" href="#founding" onClick={(e)=>{e.preventDefault();scrollToId('founding');}}>
            {t.social.finalCta} <EBIcon name="arrow-right" />
          </a>
        </Reveal>
      </div>
    </section>
  );
}

/* ---------------- Footer ---------------- */
function Footer() {
  const { t } = useContextB(LangContext);
  return (
    <footer className="lp-footer">
      <div className="lp-container">
        <div className="lp-footer-top">
          <div>
            <div className="lp-logo"><img className="lp-logo-mark" src="assets/logo-mark.png" alt="" /><span className="lp-logo-text">Sarà per sempre <em>sì</em></span></div>
            <div className="lp-footer-tag">{t.footer.tag}</div>
          </div>
          <div className="lp-footer-socials">
            <a href="#" aria-label="Instagram"><EBIcon name="instagram" /></a>
            <a href="#" aria-label="Facebook"><EBIcon name="facebook" /></a>
            <a href="#" aria-label="Email"><EBIcon name="mail" /></a>
          </div>
        </div>
        <div className="lp-footer-bottom">
          <span>{t.footer.rights}</span>
          <div className="lp-footer-links">
            <a href="#">{t.footer.privacy}</a>
            <a href="#">{t.footer.terms}</a>
          </div>
        </div>
      </div>
    </footer>
  );
}

/* ---------------- App root ---------------- */
function App() {
  const [lang, setLang] = useStateB('it');
  const t = window.EB_I18N[lang];
  useEffectB(() => { document.documentElement.lang = lang; }, [lang]);
  return (
    <LangContext.Provider value={{ lang, setLang, t }}>
      <div className="lp">
        <Header />
        <Hero />
        <Wedge />
        <GuestPhotos />
        <Invitations />
        <RSVPTables />
        <AITools />
        <Founding />
        <Social />
        <FinalCTA />
        <Footer />
      </div>
    </LangContext.Provider>
  );
}

ReactDOM.createRoot(document.getElementById('eb-root')).render(<App />);
