// Tela: Landing page
const { useState: useStateLanding, useEffect: useEffectLanding } = React;

function Landing({ t, lang, setLang, onStart, onSignIn }) {
  const [scrolled, setScrolled] = useStateLanding(false);
  useEffectLanding(() => {
    const el = document.querySelector('.mv-landing-scroll');
    if (!el) return;
    const onScroll = () => setScrolled(el.scrollTop > 12);
    el.addEventListener('scroll', onScroll);
    return () => el.removeEventListener('scroll', onScroll);
  }, []);

  return (
    <div className="mv-landing-scroll" style={{ height: '100%', overflowY: 'auto', background: 'var(--cream)', color: 'var(--ink)' }}>
      <header className={'mv-land-nav' + (scrolled ? ' is-scrolled' : '')}>
        <div className="mv-brand">
          <span className="mv-brand-mark">✧</span>
          <span className="mv-brand-name">{t.brand_name}</span>
        </div>
        <div style={{ display: 'flex', alignItems: 'center', gap: 18 }}>
          <LangSwitch lang={lang} setLang={setLang} compact />
          <button className="mv-btn-ghost" onClick={onSignIn}>{t.cta_signin}</button>
          <button className="mv-btn-primary" onClick={onStart}>{t.cta_start}</button>
        </div>
      </header>

      <section className="mv-hero">
        <div className="mv-hero-mark">
          <svg viewBox="0 0 200 200" width="120" height="120" aria-hidden>
            <defs>
              <radialGradient id="g1" cx="50%" cy="40%" r="60%">
                <stop offset="0%" stopColor="#f6e9c8" />
                <stop offset="60%" stopColor="#e7d3a3" />
                <stop offset="100%" stopColor="#c9a96b" stopOpacity="0.4" />
              </radialGradient>
            </defs>
            <circle cx="100" cy="100" r="78" fill="url(#g1)" />
            <circle cx="100" cy="100" r="78" fill="none" stroke="#a8814a" strokeOpacity="0.35" strokeWidth="0.5" />
            <g stroke="#7a5a30" strokeOpacity="0.5" strokeWidth="0.6" fill="none">
              <path d="M100 22 L100 178" /><path d="M22 100 L178 100" />
              <path d="M44 44 L156 156" /><path d="M156 44 L44 156" />
            </g>
            <text x="100" y="112" textAnchor="middle" fontFamily="Cormorant Garamond, serif" fontSize="48" fill="#5d4220" fontStyle="italic">v</text>
          </svg>
        </div>
        <p className="mv-eyebrow">{t.landing_eyebrow}</p>
        <h1 className="mv-h1">{t.landing_title}</h1>
        <p className="mv-lead">{t.landing_sub}</p>
        <div style={{ display: 'flex', gap: 12, justifyContent: 'center', marginTop: 36 }}>
          <button className="mv-btn-primary mv-btn-lg" onClick={onStart}>{t.cta_start}</button>
          <button className="mv-btn-ghost mv-btn-lg" onClick={onSignIn}>{t.cta_signin}</button>
        </div>
        <p className="mv-fineprint">{t.pricing_trial} · No credit card required.</p>
      </section>

      <section className="mv-features">
        <FeatureCard icon="✧" title={t.feat_1_t} desc={t.feat_1_d} />
        <FeatureCard icon="◯" title={t.feat_2_t} desc={t.feat_2_d} />
        <FeatureCard icon="✛" title={t.feat_3_t} desc={t.feat_3_d} />
      </section>

      <ShareDemo lang={lang} t={t} />

      <section className="mv-pricing">
        <div className="mv-price-card">
          <p className="mv-eyebrow">{t.pricing_title}</p>
          <div className="mv-plan-grid">
            <div className="mv-plan-opt mv-plan-opt-static">
              <div className="mv-plan-opt-name">{t.plan_monthly}</div>
              <div className="mv-plan-opt-price">{t.plan_monthly_price}<span>{t.plan_per_month}</span></div>
              <div className="mv-plan-opt-equiv">&nbsp;</div>
            </div>
            <div className="mv-plan-opt mv-plan-opt-static is-on">
              <span className="mv-plan-badge">{t.plan_best}</span>
              <div className="mv-plan-opt-name">{t.plan_yearly}</div>
              <div className="mv-plan-opt-price">{t.plan_yearly_price}<span>{t.plan_per_year}</span></div>
              <div className="mv-plan-opt-equiv">{t.plan_yearly_equiv}</div>
            </div>
          </div>
          <p className="mv-price-trial">{t.pricing_trial} · No credit card required.</p>
          <ul className="mv-price-list">
            <li>{t.pricing_b1}</li>
            <li>{t.pricing_b2}</li>
            <li>{t.pricing_b3}</li>
            <li>{t.pricing_b4}</li>
          </ul>
          <button className="mv-btn-primary mv-btn-lg" style={{ width: '100%' }} onClick={onStart}>{t.cta_start}</button>
        </div>
      </section>

      <footer className="mv-footer">
        <span className="mv-brand-mark">✧</span>
        <span>{t.brand_name}</span>
        <span className="mv-footer-sep">·</span>
        <a href={t.terms_url} style={{color:'inherit',textDecoration:'none'}}>{t.nav_terms}</a>
        <span className="mv-footer-sep">·</span>
        <a href={t.privacy_url} style={{color:'inherit',textDecoration:'none'}}>{t.nav_privacy}</a>
        <span className="mv-footer-sep">·</span>
        <span>{t.footer}</span>
      </footer>
    </div>
  );
}

function ShareDemo({ lang, t }) {
  const [shared, setShared] = useStateLanding(false);

  const shareUrl = 'https://mywisdomverse.online';

  const verse = {
    en: { text: '"I can do all things through Christ who strengthens me."', ref: 'Philippians 4:13' },
    pt: { text: '"Tudo posso naquele que me fortalece."', ref: 'Filipenses 4:13' },
    es: { text: '"Todo lo puedo en Cristo que me fortalece."', ref: 'Filipenses 4:13' },
  }[lang] || { text: '"I can do all things through Christ who strengthens me."', ref: 'Philippians 4:13' };

  const labels = {
    eyebrow: { en: 'Spread the Word', pt: 'Espalhe a Palavra', es: 'Comparte la Palabra' },
    title: { en: "Share a verse. Change someone's day.", pt: 'Compartilhe um versículo. Mude o dia de alguém.', es: 'Comparte un versículo. Cambia el día de alguien.' },
    desc: { en: 'Every verse you share is an invitation. One tap sends the Word — and a link so your friend can start their own daily journey.', pt: 'Cada versículo que você compartilha é um convite. Um toque envia a Palavra — e um link para que seu amigo comece sua própria jornada diária.', es: 'Cada versículo que compartes es una invitación. Un toque envía la Palabra — y un enlace para que tu amigo comience su propio camino diario.' },
    btn: { en: 'Share this verse', pt: 'Compartilhar este versículo', es: 'Compartir este versículo' },
    shared: { en: 'Copied!', pt: 'Copiado!', es: 'Copiado!' },
    sharedMobile: { en: 'Shared!', pt: 'Compartilhado!', es: 'Compartido!' },
    caption: { en: 'Works on WhatsApp, iMessage, Instagram and more', pt: 'Funciona no WhatsApp, iMessage, Instagram e mais', es: 'Funciona en WhatsApp, iMessage, Instagram y más' },
  };

  const l = (key) => labels[key][lang] || labels[key].en;

  const callToAction = {
    en: '✨ Get your daily Bible verse — free for 7 days',
    pt: '✨ Receba seu versículo diário — 7 dias grátis',
    es: '✨ Recibe tu versículo diario — 7 días gratis',
  }[lang] || '✨ Get your daily Bible verse — free for 7 days';

  // Gera imagem do cartão como Blob
  function generateImageBlob() {
    return new Promise((resolve) => {
      const c = document.createElement('canvas');
      c.width = 1080; c.height = 1080;
      const ctx = c.getContext('2d');
      const g = ctx.createRadialGradient(540, 380, 100, 540, 540, 800);
      g.addColorStop(0, '#fbf3df'); g.addColorStop(0.6, '#f1e3c0'); g.addColorStop(1, '#d8bd86');
      ctx.fillStyle = g; ctx.fillRect(0, 0, 1080, 1080);
      ctx.strokeStyle = 'rgba(122,90,48,0.3)'; ctx.lineWidth = 2;
      ctx.strokeRect(60, 60, 960, 960);
      ctx.fillStyle = '#7a5a30'; ctx.font = '64px serif'; ctx.textAlign = 'center';
      ctx.fillText('✧', 540, 200);
      ctx.fillStyle = '#3a2c14';
      ctx.font = 'italic 44px "Cormorant Garamond", serif';
      const words = verse.text.split(' ');
      let line = '', y = 420;
      for (const w of words) {
        const test = line + w + ' ';
        if (ctx.measureText(test).width > 880 && line) {
          ctx.fillText(line.trim(), 540, y); y += 60; line = w + ' ';
        } else { line = test; }
      }
      if (line) ctx.fillText(line.trim(), 540, y);
      ctx.font = '500 26px "Inter", sans-serif';
      ctx.fillStyle = '#7a5a30';
      ctx.fillText(verse.ref.toUpperCase(), 540, y + 80);
      ctx.strokeStyle = 'rgba(122,90,48,0.35)'; ctx.lineWidth = 1;
      ctx.beginPath(); ctx.moveTo(200, y + 120); ctx.lineTo(880, y + 120); ctx.stroke();
      ctx.font = '500 20px "Inter", sans-serif';
      ctx.fillStyle = 'rgba(122,90,48,0.6)';
      ctx.fillText('My Verse', 540, y + 170);
      c.toBlob(resolve, 'image/png');
    });
  }

  // Copia texto como fallback desktop
  function copyToClipboard() {
    const text = `${verse.text} — ${verse.ref}\n\n${callToAction}\n${shareUrl}`;
    try {
      if (navigator.clipboard) {
        navigator.clipboard.writeText(text).catch(() => {});
      } else {
        const ta = document.createElement('textarea');
        ta.value = text;
        ta.style.position = 'fixed';
        ta.style.opacity = '0';
        document.body.appendChild(ta);
        ta.select();
        document.execCommand('copy');
        document.body.removeChild(ta);
      }
    } catch(e) {}
    setShared(true);
    setTimeout(() => setShared(false), 2500);
  }

  async function handleShare() {
    const isMobile = /Android|iPhone|iPad|iPod/i.test(navigator.userAgent);
    if (isMobile && navigator.share) {
      try {
        const blob = await generateImageBlob();
        const file = new File([blob], 'myverse.png', { type: 'image/png' });
        const shareData = { title: 'My Verse', text: callToAction, url: shareUrl };
        if (navigator.canShare && navigator.canShare({ files: [file] })) {
          await navigator.share({ ...shareData, files: [file] });
        } else {
          await navigator.share(shareData);
        }
        setShared(true);
        setTimeout(() => setShared(false), 2500);
      } catch (e) {
        if (e.name !== 'AbortError') copyToClipboard();
      }
    } else {
      copyToClipboard();
    }
  }

  return (
    <section style={{ padding: '48px 20px', background: 'var(--cream-2)', textAlign: 'center' }}>
      <p className="mv-eyebrow" style={{ marginBottom: 8 }}>{l('eyebrow')}</p>
      <h2 style={{ fontFamily: 'var(--serif)', fontSize: 'clamp(24px,5vw,36px)', fontWeight: 600, color: 'var(--ink)', marginBottom: 12, lineHeight: 1.25 }}>{l('title')}</h2>
      <p style={{ fontSize: 15, color: 'var(--ink-soft)', maxWidth: 420, margin: '0 auto 32px', lineHeight: 1.7 }}>{l('desc')}</p>

      <div style={{ maxWidth: 340, margin: '0 auto 24px', background: 'var(--paper)', border: '1.5px solid var(--gold-soft)', borderRadius: 16, padding: '28px 24px', boxShadow: '0 4px 24px rgba(42,33,20,0.1)' }}>
        <div style={{ fontSize: 32, color: 'var(--gold)', marginBottom: 12, fontFamily: 'var(--serif)' }}>✧</div>
        <p style={{ fontFamily: 'var(--serif)', fontSize: 18, fontStyle: 'italic', color: 'var(--ink)', lineHeight: 1.6, marginBottom: 12 }}>{verse.text}</p>
        <p style={{ fontSize: 13, fontWeight: 700, letterSpacing: 1, color: 'var(--gold)', textTransform: 'uppercase' }}>{verse.ref}</p>
        <div style={{ height: 1, background: 'var(--gold-soft)', margin: '16px 0 12px' }} />
        <p style={{ fontSize: 12, color: 'var(--ink-soft)', opacity: 0.7 }}>My Verse · mywisdomverse.online</p>
      </div>

      <button onClick={handleShare} style={{ display: 'inline-flex', alignItems: 'center', gap: 8, padding: '14px 28px', background: shared ? '#4a7c59' : 'linear-gradient(135deg, var(--gold-deep), var(--gold))', color: '#fff', border: 'none', borderRadius: 999, fontFamily: 'var(--sans)', fontSize: 15, fontWeight: 700, cursor: 'pointer', transition: 'all .25s', boxShadow: '0 4px 16px rgba(122,90,48,0.3)' }}>
        {shared ? ('✓ ' + ((/Android|iPhone|iPad|iPod/i.test(navigator.userAgent)) ? l('sharedMobile') : l('shared'))) : ('⬆ ' + l('btn'))}
      </button>

      <p style={{ fontSize: 12, color: 'var(--ink-soft)', marginTop: 12, opacity: 0.65 }}>{l('caption')}</p>
    </section>
  );
}

function FeatureCard({ icon, title, desc }) {
  return (
    <div className="mv-feature">
      <div className="mv-feature-icon">{icon}</div>
      <h3 className="mv-feature-title">{title}</h3>
      <p className="mv-feature-desc">{desc}</p>
    </div>
  );
}

function LangSwitch({ lang, setLang, compact }) {
  const opts = [{ k: 'pt', l: 'PT' }, { k: 'en', l: 'EN' }, { k: 'es', l: 'ES' }];
  return (
    <div className={'mv-langsw' + (compact ? ' is-compact' : '')}>
      {opts.map(o => (
        <button key={o.k} className={'mv-langsw-b' + (lang === o.k ? ' is-on' : '')} onClick={() => setLang(o.k)}>{o.l}</button>
      ))}
    </div>
  );
}

Object.assign(window, { Landing, LangSwitch });
