/* global React, Icon */
const { useState, useEffect } = React;

// =====================================================
// Testimonials — beta player quotes
// =====================================================
function TestimonialsSection({ lang }) {
  const t = lang === 'es' ? {
    label: 'Testimonios',
    h: <>Lo que dicen los <span className="pq-lime-text" style={{ fontStyle: 'italic', fontFamily: 'Source Serif 4, Georgia, serif', textTransform: 'none', fontWeight: 400 }}>beta testers.</span></>,
    p: 'Jugadores reales en Puerto Rico que llevan tres meses probando PIQUEL antes del lanzamiento público.',
    items: [
    { q: '"Me uní un martes. El miércoles ya tenía partido coordinado con dos personas que jamás había conocido. Esto cambia el juego, literal."', a: 'C', n: 'Carla R.', r: 'Jugadora · Intermedio · San Juan' },
    { q: '"Antes pasábamos tres días en el grupo para coordinar un doble. Con PIQUEL fueron tres minutos. No regreso a WhatsApp para esto, ni loco."', a: 'M', n: 'Marco V.', r: 'Jugador · Avanzado · Bayamón' },
    { q: '"Como dueño de cancha, ver mi ocupación en vivo y a los jugadores reservando sin tener que coordinar nada — ese es el futuro."', a: 'D', n: 'Damaris O.', r: 'Club Owner · Cancha del Norte' }]

  } : {
    label: 'Testimonials',
    h: <>What the <span className="pq-lime-text" style={{ fontStyle: 'italic', fontFamily: 'Source Serif 4, Georgia, serif', textTransform: 'none', fontWeight: 400 }}>beta testers</span> say.</>,
    p: 'Real players in Puerto Rico who have been testing PIQUEL for three months before public launch.',
    items: [
    { q: '"I signed up on a Tuesday. By Wednesday I had a match locked in with two players I had never met. This is a different game."', a: 'C', n: 'Carla R.', r: 'Player · Intermediate · San Juan' },
    { q: '"We used to burn three days in the group chat to coordinate one doubles match. With PIQUEL it was three minutes. I am not going back."', a: 'M', n: 'Marco V.', r: 'Player · Advanced · Bayamón' },
    { q: '"As a court owner, seeing my occupancy live and players reserving without coordinating anything — that is the future."', a: 'D', n: 'Damaris O.', r: 'Club Owner · Cancha del Norte' }]

  };

  return (
    <section className="pq-section" id="testimonials" data-comment-anchor="40907b23ca-section-29-5">
      <div className="pq-container">
        <div className="pq-eyebrow-row pq-reveal">
          <span className="num">07</span>
          <span className="label">{t.label}</span>
        </div>
        <h2 className="pq-display pq-reveal" data-stagger="1" style={{ maxWidth: '22ch' }}>{t.h}</h2>
        <p className="pq-lead pq-reveal" data-stagger="2" style={{ marginTop: 24 }}>{t.p}</p>

        <div className="pq-tm-grid">
          {t.items.map((tm, i) =>
          <article className="pq-tm pq-reveal" data-stagger={String(i % 3 + 1)} key={i}>
              <div style={{ display: 'flex', gap: 4 }}>
                {[0, 1, 2, 3, 4].map((s) => <Icon key={s} name="star" size={14} color="#C8FF00" />)}
              </div>
              <div className="quote">{tm.q}</div>
              <div className="meta">
                <div className="av" aria-hidden="true">{tm.a}</div>
                <div>
                  <div className="name">{tm.n}</div>
                  <div className="role">{tm.r}</div>
                </div>
              </div>
            </article>
          )}
        </div>
      </div>
    </section>);

}

// =====================================================
// FAQ — accordion
// =====================================================
function FAQSection({ lang }) {
  const t = lang === 'es' ? {
    label: 'FAQ',
    h: <>Preguntas <span className="pq-lime-text" style={{ fontStyle: 'italic', fontFamily: 'Source Serif 4, Georgia, serif', textTransform: 'none', fontWeight: 400, color: '#000' }}>frecuentes.</span></>,
    p: 'Si tu duda no está aquí, escríbenos a Piquelapp@gmail.com — leemos todo.',
    items: [
    { q: '¿Cuándo se lanza PIQUEL?', a: 'Lanzamos en Puerto Rico durante el verano 2026. Los miembros de la lista de espera tienen acceso 3 semanas antes que el público.' },
    { q: '¿Es gratis?', a: 'La app es gratis para jugadores. Habrá un plan Premium opcional con stats avanzadas y más. Clubes y organizadores en la waitlist arrancan gratis el primer año.' },
    { q: '¿Funciona si soy principiante?', a: 'Hecho para todos los niveles. Filtramos por DUPR (Principiante < 3.0, Intermedio 3.0-4.0, Avanzado 4.0+) para que juegues con gente de tu calibre.' },
    { q: '¿En qué ciudades arranca?', a: 'Empezamos en San Juan, Bayamón, Carolina y Ponce. Después expandimos a toda la isla según la demanda de la waitlist.' },
    { q: '¿Cómo funciona el código de referido?', a: 'Después de unirte recibes un código personal. Cada amigo que se una con tu código te sube de tier — desde acceso temprano hasta Founders Club con 10 referidos.' },
    { q: '¿Qué pasa con mi DUPR existente?', a: 'PIQUEL va a tener la capacidad de sincronizar con tu DUPR oficial. Tu rating actual se importa y cada partido en PIQUEL contribuye a tu DUPR. Sin duplicación de cuentas.' },
    { q: '¿Hay app para iOS y Android?', a: 'Sí. PIQUEL es nativo en iOS y Android. Sin versión web para jugadores — la app es donde vive el producto.' },
    { q: '¿Cómo aseguran que los jugadores son reales?', a: 'Foto de perfil obligatoria, verificación por email + teléfono, rating personal de partidos previos. Reportes de comportamiento se revisan en menos de 24 horas.' }]

  } : {
    label: 'FAQ',
    h: <>Frequently asked <span className="pq-lime-text" style={{ fontStyle: 'italic', fontFamily: 'Source Serif 4, Georgia, serif', textTransform: 'none', fontWeight: 400, color: '#000' }}>questions.</span></>,
    p: 'If your question is not here, email us at Piquelapp@gmail.com — we read everything.',
    items: [
    { q: 'When does PIQUEL launch?', a: 'We launch in Puerto Rico during Summer 2026. Waitlist members get access 3 weeks before the public.' },
    { q: 'Is it free?', a: 'The app is free for players. There will be an optional Premium plan with advanced stats, video review, and more. Clubs and organizers on the waitlist start free for year one.' },
    { q: 'Does it work if I am a beginner?', a: 'Built for every level. We filter by DUPR (Beginner < 3.0, Intermediate 3.0-4.0, Advanced 4.0+) so you play with your calibre.' },
    { q: 'What cities launch first?', a: 'We start in San Juan, Bayamón, Carolina, and Ponce. We expand across the island based on waitlist demand.' },
    { q: 'How does the referral code work?', a: 'After joining you get a personal code. Each friend who joins with your code bumps you a tier — from early access to Founders Club at 10 referrals.' },
    { q: 'What happens to my existing DUPR?', a: 'PIQUEL syncs with your official DUPR. Your current rating imports and every PIQUEL match contributes back. No account duplication.' },
    { q: 'iOS and Android?', a: 'Yes. PIQUEL is native on iOS and Android. No web version for players — the app is where the product lives.' },
    { q: 'How do you keep players real?', a: 'Mandatory profile photo, email + phone verification, personal rating from past matches. Reports are reviewed in under 24 hours.' }]

  };

  return (
    <section className="pq-section light" id="faq">
      <div className="pq-container">
        <div className="pq-eyebrow-row pq-reveal">
          <span className="num" style={{ color: '#888' }}>06</span>
          <span className="label">{t.label}</span>
        </div>
        <h2 className="pq-display pq-reveal" data-stagger="1" style={{ color: '#000', maxWidth: '20ch' }}>{t.h}</h2>
        <p className="pq-lead pq-reveal" data-stagger="2" style={{ marginTop: 20, color: '#555', maxWidth: '54ch' }}>{t.p}</p>

        <div className="pq-faq pq-reveal" data-stagger="3">
          {t.items.map((it, i) =>
          <details className="pq-faq-item" key={i}>
              <summary className="pq-faq-q">
                {it.q}
                <span className="plus" aria-hidden="true"><Icon name="plus" size={14} stroke={2} /></span>
              </summary>
              <div className="pq-faq-a">{it.a}</div>
            </details>
          )}
        </div>
      </div>
    </section>);

}

// =====================================================
// Final CTA — full bleed dark
// =====================================================
function FinalCTASection({ lang }) {
  const [email, setEmail] = useState('');
  const [done, setDone] = useState(false);

  const submit = (e) => {
    e.preventDefault();
    if (!email.trim() || !/^[^@]+@[^@]+\.[^@]+$/.test(email)) return;
    if (window.pqTrack) window.pqTrack('cta_click_final', { lang });
    // Scroll to top hero form with email prefilled
    document.getElementById('top').scrollIntoView({ behavior: 'smooth' });
    setTimeout(() => {
      const f = document.getElementById('f-email');
      if (f) {
        f.value = email;
        f.focus();
        f.dispatchEvent(new Event('input', { bubbles: true }));
      }
    }, 700);
    setDone(true);
  };

  const t = lang === 'es' ? {
    label: 'Llegó la hora',
    h1: 'MENOS CHAT.',
    h2: 'MÁS PICKLE.',
    p: 'Reserva tu acceso temprano hoy. Cuando abramos, juegas tú primero.',
    urgency: 'Cupos limitados para acceso anticipado.',
    place: 'tu@email.com',
    btn: 'Entrar →',
    foot: 'Estás a 1 email del primer partido. Sin spam.'
  } : {
    label: 'Time to play',
    h1: 'LESS CHAT.',
    h2: 'MORE PICKLE.',
    p: 'Reserve your early access today. When we open, you play first.',
    urgency: 'Limited early access spots.',
    place: 'you@email.com',
    btn: 'Get in →',
    foot: 'You are 1 email away from your first match. No spam.'
  };

  return (
    <section className="pq-final-cta" id="cta">
      <div className="pq-final-cta-inner pq-reveal">
        <div className="pq-eyebrow-row" style={{ justifyContent: 'center', marginBottom: 20 }}>
          <span className="num">07</span>
          <span className="label">{t.label}</span>
        </div>
        <h2>
          {t.h1}<br />
          <span className="accent">{t.h2.toLowerCase().replace(/^\w/, (c) => c)}</span>
        </h2>
        <p>{t.p}</p>
        <div className="pq-urgency pq-urgency--center" style={{ marginBottom: 14 }}>
          {t.urgency}
        </div>
        <form className="pq-inline-form" onSubmit={submit} aria-label="Email signup">
          <input type="email" placeholder={t.place} value={email} onChange={(e) => setEmail(e.target.value)} aria-label="Email" />
          <button type="submit">{t.btn}</button>
        </form>
        <div style={{ marginTop: 18, fontFamily: 'var(--font-body)', fontSize: 13, color: 'rgba(255,255,255,.42)' }}>{t.foot}</div>
      </div>
    </section>);

}

// =====================================================
// Footer
// =====================================================
function Footer({ lang }) {
  const t = lang === 'es' ? {
    blurb: 'PIQUEL es la primera plataforma de pickleball de Puerto Rico. Construida con jugadores locales, lanzando verano 2026.',
    product: 'Producto', co: 'Compañía', legal: 'Legal',
    productLinks: [
    { href: '#how', label: 'Cómo funciona' },
    { href: '#features', label: 'Features' },
    { href: '#benefits', label: 'Beneficios' },
    { href: '#referral', label: 'Referidos' }],

    coLinks: [
    { href: 'mailto:Piquelapp@gmail.com', label: 'Contacto' },
    { href: '#', label: 'Sobre PIQUEL' },
    { href: '#', label: 'Prensa' },
    { href: '#', label: 'Clubs partner' }],

    legalLinks: [
    { href: '/terms?lang=es', label: 'Términos' },
    { href: '/privacy?lang=es', label: 'Privacidad' },
    { href: '/privacy?lang=es#6', label: 'Cookies' }],

    copy: '© 2026 PIQUEL. Hecho en Puerto Rico.',
    tagline: 'Menos chat. Más pickle.'
  } : {
    blurb: "PIQUEL is Puerto Rico's first pickleball platform. Built with local players, launching Summer 2026.",
    product: 'Product', co: 'Company', legal: 'Legal',
    productLinks: [
    { href: '#how', label: 'How it works' },
    { href: '#features', label: 'Features' },
    { href: '#benefits', label: 'Benefits' },
    { href: '#referral', label: 'Referrals' }],

    coLinks: [
    { href: 'mailto:Piquelapp@gmail.com', label: 'Contact' },
    { href: '#', label: 'About PIQUEL' },
    { href: '#', label: 'Press' },
    { href: '#', label: 'Club partners' }],

    legalLinks: [
    { href: '/terms?lang=en', label: 'Terms' },
    { href: '/privacy?lang=en', label: 'Privacy' },
    { href: '/privacy?lang=en#6', label: 'Cookies' }],

    copy: '© 2026 PIQUEL. Made in Puerto Rico.',
    tagline: 'Less chat. More pickle.'
  };

  return (
    <footer className="pq-footer">
      <div className="pq-container">
        <div className="pq-footer-grid">
          <div className="pq-footer-brand">
            <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
              <img src="assets/logo-white.svg" alt="" style={{ height: 24 }} />
              <span style={{ fontFamily: 'var(--font-display)', fontWeight: 700, fontSize: 14, letterSpacing: '.18em', color: '#fff' }}>PIQUEL</span>
            </div>
            <p>{t.blurb}</p>
            <div style={{ display: 'flex', gap: 10, marginTop: 20 }}>
              <a href="#" aria-label="Instagram" style={{ width: 36, height: 36, borderRadius: 999, background: '#0e0e0e', border: '1px solid #1c1c1c', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
                <Icon name="instagram" size={16} />
              </a>
              <a href="#" aria-label="Twitter" style={{ width: 36, height: 36, borderRadius: 999, background: '#0e0e0e', border: '1px solid #1c1c1c', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
                <Icon name="twitter" size={16} />
              </a>
              <a href="mailto:Piquelapp@gmail.com" aria-label="Email" style={{ width: 36, height: 36, borderRadius: 999, background: '#0e0e0e', border: '1px solid #1c1c1c', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
                <Icon name="mail" size={16} />
              </a>
            </div>
          </div>
          <div>
            <h6>{t.product}</h6>
            {t.productLinks.map((l) => <a key={l.label} href={l.href}>{l.label}</a>)}
          </div>
          <div>
            <h6>{t.co}</h6>
            {t.coLinks.map((l) => <a key={l.label} href={l.href}>{l.label}</a>)}
          </div>
          <div>
            <h6>{t.legal}</h6>
            {t.legalLinks.map((l) => <a key={l.label} href={l.href}>{l.label}</a>)}
          </div>
        </div>
        <div className="pq-footer-bottom">
          <span>{t.copy}</span>
          <span style={{ fontFamily: 'var(--font-display)', letterSpacing: '.18em', textTransform: 'uppercase' }}>{t.tagline}</span>
        </div>
      </div>
    </footer>);

}

// =====================================================
// Sticky CTA (after hero scroll)
// =====================================================
function StickyCTA({ lang }) {
  const [visible, setVisible] = useState(false);
  useEffect(() => {
    const onS = () => {
      const heroH = window.innerHeight * 0.9;
      const nearBottom = window.scrollY + window.innerHeight > document.body.scrollHeight - 400;
      setVisible(window.scrollY > heroH && !nearBottom);
    };
    onS();
    window.addEventListener('scroll', onS, { passive: true });
    return () => window.removeEventListener('scroll', onS);
  }, []);

  return (
    <button
      className={`pq-sticky-cta ${visible ? 'visible' : ''}`}
      aria-label={lang === 'es' ? 'Reservar mi cupo en la lista de espera' : 'Reserve my waitlist spot'}
      onClick={() => document.getElementById('join').scrollIntoView({ behavior: 'smooth' })}>
      
      <Icon name="bolt" size={13} />
      {lang === 'es' ? 'Reservar cupo' : 'Reserve spot'}
    </button>);

}

Object.assign(window, { TestimonialsSection, FAQSection, FinalCTASection, Footer, StickyCTA });