// ---- Landing Page ----
window.LandingPage = function LandingPage({ t: appT }) {
  const { useState, useEffect } = React;
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState(null);
  const [lang, setLang] = useState(() => localStorage.getItem('lp-lang') || 'en');
  const t = useT(lang);

  // Intersection Observer for scroll animations
  useEffect(() => {
    const observer = new IntersectionObserver(
      (entries) => {
        entries.forEach(entry => {
          if (entry.isIntersecting) {
            entry.target.classList.add('lp-visible');
            observer.unobserve(entry.target);
          }
        });
      },
      { threshold: 0.1, rootMargin: '0px 0px -40px 0px' }
    );
    document.querySelectorAll('.lp-animate').forEach(el => observer.observe(el));
    return () => observer.disconnect();
  }, []);

  const handleGoogleSignIn = async () => {
    setLoading(true);
    setError(null);
    try {
      await initFirebase();
      await firebaseAuth.signInWithPopup(googleProvider);
    } catch (err) {
      if (err.code !== 'auth/popup-closed-by-user') {
        setError(err.message);
      }
    } finally {
      setLoading(false);
    }
  };

  const scrollTo = (id) => {
    document.getElementById(id)?.scrollIntoView({ behavior: 'smooth' });
  };

  const toggleLang = () => {
    const next = lang === 'en' ? 'es' : 'en';
    setLang(next);
    localStorage.setItem('lp-lang', next);
  };

  const methods = [
    { icon: '\uD83C\uDDF3\uD83C\uDDF4', name: 'Norwegian' },
    { icon: '\uD83D\uDCCA', name: '80/20' },
    { icon: '\u26A1', name: 'Polarized' },
    { icon: '\uD83C\uDF6F', name: 'Sweet Spot' },
    { icon: '\uD83D\uDD3A', name: 'Seiler Pyramidal' },
    { icon: '\uD83E\uDEC1', name: 'VO2max HIIT' },
    { icon: '\uD83E\uDDF1', name: 'Block Periodization' },
    { icon: '\u2764\uFE0F', name: 'Maffetone (MAF)' },
    { icon: '\uD83D\uDCC8', name: 'Traditional' },
    { icon: '\uD83D\uDCD0', name: 'Critical Power' },
    { icon: '\uD83C\uDFC1', name: 'Race-Pace' },
    { icon: '\uD83C\uDFAF', name: 'Custom' },
  ];

  const features = [
    { icon: '\uD83E\uDDE0', color: 'blue',   titleKey: 'lpFeature1Title', descKey: 'lpFeature1Desc' },
    { icon: '\uD83D\uDCCB', color: 'green',  titleKey: 'lpFeature2Title', descKey: 'lpFeature2Desc' },
    { icon: '\uD83D\uDCAC', color: 'purple', titleKey: 'lpFeature3Title', descKey: 'lpFeature3Desc' },
    { icon: '\uD83D\uDCC5', color: 'orange', titleKey: 'lpFeature4Title', descKey: 'lpFeature4Desc' },
    { icon: '\uD83C\uDFCA', color: 'cyan',   titleKey: 'lpFeature5Title', descKey: 'lpFeature5Desc' },
    { icon: '\uD83D\uDCA4', color: 'red',    titleKey: 'lpFeature6Title', descKey: 'lpFeature6Desc' },
  ];

  return (
    <div className="landing-page">
      {/* Nav */}
      <nav className="lp-nav">
        <div className="lp-nav-logo" onClick={() => window.scrollTo({ top: 0, behavior: 'smooth' })}>
          Flow AI Training
        </div>
        <div className="lp-nav-links">
          <button className="lp-nav-link" onClick={() => scrollTo('features')}>{t('lpNavFeatures')}</button>
          <button className="lp-nav-link" onClick={() => scrollTo('how-it-works')}>{t('lpNavHowItWorks')}</button>
          <button className="lp-nav-link" onClick={() => scrollTo('methods')}>{t('lpNavMethods')}</button>
          <button className="lp-nav-link" onClick={toggleLang}>{lang === 'en' ? 'ES' : 'EN'}</button>
          <button className="lp-nav-cta" onClick={handleGoogleSignIn} disabled={loading}>
            {loading ? t('lpGetStartedLoading') : t('lpGetStarted')}
          </button>
        </div>
        <button className="lp-nav-cta lp-nav-mobile-cta" onClick={handleGoogleSignIn} disabled={loading}>
          {loading ? '...' : t('lpGetStarted')}
        </button>
      </nav>

      {/* Hero */}
      <section className="lp-hero">
        <div className="lp-hero-glow" />
        <h1>
          {t('lpHeroTitle1')}{' '}
          <span className="lp-gradient-text">{t('lpHeroTitle2')}</span>
        </h1>
        <p className="lp-hero-subtitle">{t('lpHeroSubtitle')}</p>
        <button className="lp-hero-cta" onClick={handleGoogleSignIn} disabled={loading}>
          {loading
            ? <><div className="spinner" style={{ width: 16, height: 16 }} /> {t('lpGetStartedLoading')}</>
            : t('lpGetStarted')
          }
        </button>
        <p className="lp-hero-hint">
          {t('lpHeroHint')}{' '}
          <a href="https://intervals.icu" target="_blank" rel="noopener noreferrer">intervals.icu</a>
        </p>
        {error && <p className="lp-error">{error}</p>}
      </section>

      {/* Features */}
      <section className="lp-section" id="features">
        <h2 className="lp-section-title lp-animate">{t('lpFeaturesTitle')}</h2>
        <p className="lp-section-subtitle lp-animate">{t('lpFeaturesSubtitle')}</p>
        <div className="lp-features-grid">
          {features.map((f, i) => (
            <div key={i} className="lp-feature-card lp-animate">
              <div className={`lp-feature-icon ${f.color}`}>{f.icon}</div>
              <div className="lp-feature-title">{t(f.titleKey)}</div>
              <div className="lp-feature-desc">{t(f.descKey)}</div>
            </div>
          ))}
        </div>
      </section>

      {/* How It Works */}
      <section className="lp-section" id="how-it-works">
        <h2 className="lp-section-title lp-animate">{t('lpHowTitle')}</h2>
        <p className="lp-section-subtitle lp-animate">{t('lpHowSubtitle')}</p>
        <div className="lp-steps lp-animate">
          {[1, 2, 3].map(n => (
            <div key={n} className="lp-step">
              <div className="lp-step-number">{n}</div>
              <div className="lp-step-title">{t(`lpStep${n}Title`)}</div>
              <div className="lp-step-desc">{t(`lpStep${n}Desc`)}</div>
            </div>
          ))}
        </div>
      </section>

      {/* Methods */}
      <section className="lp-section" id="methods">
        <h2 className="lp-section-title lp-animate">{t('lpMethodsTitle')}</h2>
        <p className="lp-section-subtitle lp-animate">{t('lpMethodsSubtitle')}</p>
        <div className="lp-methods-grid lp-animate">
          {methods.map((m, i) => (
            <div key={i} className="lp-method-pill">
              <span style={{ fontSize: 18 }}>{m.icon}</span>
              {m.name}
            </div>
          ))}
        </div>
      </section>

      {/* Stats */}
      <div className="lp-stats lp-animate">
        <div className="lp-stat">
          <div className="lp-stat-value">{t('lpStat1Value')}</div>
          <div className="lp-stat-label">{t('lpStat1Label')}</div>
        </div>
        <div className="lp-stat">
          <div className="lp-stat-value">{t('lpStat2Value')}</div>
          <div className="lp-stat-label">{t('lpStat2Label')}</div>
        </div>
        <div className="lp-stat">
          <div className="lp-stat-value">{t('lpStat3Value')}</div>
          <div className="lp-stat-label">{t('lpStat3Label')}</div>
        </div>
        <div className="lp-stat">
          <div className="lp-stat-value">intervals.icu</div>
          <div className="lp-stat-label">{t('lpStat4Label')}</div>
        </div>
      </div>

      {/* Final CTA */}
      <section className="lp-final-cta lp-animate">
        <h2>{t('lpCtaTitle')}</h2>
        <p>{t('lpCtaSubtitle')}</p>
        <button className="lp-hero-cta" onClick={handleGoogleSignIn} disabled={loading}>
          {loading ? t('lpGetStartedLoading') : t('lpGetStarted')}
        </button>
        {error && <p className="lp-error">{error}</p>}
      </section>

      {/* Footer */}
      <footer className="lp-footer">
        <div style={{ marginBottom: 8 }}>
          <span style={{
            fontWeight: 700,
            background: 'linear-gradient(135deg, var(--accent-blue), var(--accent-green))',
            WebkitBackgroundClip: 'text',
            WebkitTextFillColor: 'transparent',
          }}>Flow AI Training</span>
          {' \u2014 '}{t('lpFooterTagline')}
        </div>
        <div>{t('lpFooterBuiltBy')}</div>
      </footer>
    </div>
  );
};
