// Pages: News, Recruit, Contact
const { useState: useStateP3, useEffect: useEffectP3, useRef: useRefP3 } = React;

// ============================================================
// NEWS / MEDIA
// ============================================================
function NewsPage() {
  const articles = [
    { tag: 'RECAP', date: 'APR 20 · 2012', title: 'PACK DOMINATES LAKEPOINT POOL PLAY', excerpt: 'Wolfpack 12U opened the April tournament with back-to-back run-rule wins…' },
    { tag: 'FEATURE', date: 'APR 12 · 2012', title: 'BEHIND THE STANDARD: INSIDE SPRING CAMP', excerpt: 'Four weeks. One roster. A relentless pursuit of excellence.' },
    { tag: 'ANNOUNCE', date: 'APR 05 · 2012', title: 'OPEN WORKOUTS · MAY & JUNE', excerpt: 'Wolfpack is moving up to 14U for Fall 2026. Open workouts every Tuesday in May & June, 6–8 PM at Joe Cowan Park. Looking to add a pitcher/utility.' },
    { tag: 'RECAP', date: 'MAR 30 · 2012', title: '10-2 RUN-RULE OVER COBB CRUSH', excerpt: 'A full bullpen day and a patient offense sealed an early weekend win.' },
    { tag: 'SPOTLIGHT', date: 'MAR 22 · 2012', title: 'PLAYER SPOTLIGHT: 12U PITCHING ROTATION', excerpt: 'Meet the arms keeping opponents under 3 runs per game.' },
    { tag: 'COMMUNITY', date: 'MAR 15 · 2012', title: 'WOLFPACK AT BARTOW YOUTH CLINIC', excerpt: 'Our athletes coached 60+ young softball players at a free weekend clinic.' },
  ];
  return (
    <section className="section grid-bg" style={{ paddingTop: 'clamp(120px, 14vw, 160px)' }}>
      <div className="container">
        <SectionHeader num="07" kicker="NEWS · MEDIA · FILM" title="THE PACK REPORT." tagline="Recaps, player spotlights, community coverage." />

        {/* Featured */}
        <div style={{ marginTop: 48 }} className="corners">
          <div className="card" style={{
            padding: 0, border: '1px solid rgba(196,30,58,0.3)',
            display: 'grid', gridTemplateColumns: '1fr', gap: 0,
          }}>
            <style>{`@media (min-width: 900px) { .featured { grid-template-columns: 1fr 1fr !important; } }`}</style>
            <div className="featured" style={{ display: 'grid', gridTemplateColumns: '1fr', gap: 0 }}>
              <div className="ph" style={{ aspectRatio: '16/10', borderRadius: 0, border: 'none' }}>
                <div className="mono">[FEATURE HERO IMAGE]</div>
                <div style={{ position: 'absolute', top: 16, left: 16, padding: '4px 10px', background: 'var(--wolf-red)', fontFamily: 'var(--font-mono)', fontSize: 10, letterSpacing: '0.2em' }}>FEATURE</div>
              </div>
              <div style={{ padding: 'clamp(24px, 4vw, 40px)' }}>
                <div className="mono">APR 20 · 2012</div>
                <h3 className="display" style={{ fontSize: 'clamp(32px, 4vw, 52px)', marginTop: 16, lineHeight: 0.9 }}>
                  PACK DOMINATES LAKEPOINT POOL PLAY
                </h3>
                <p style={{ marginTop: 20, color: 'var(--bone-dim)', lineHeight: 1.7, fontSize: 15 }}>
                  Wolfpack 12U opened the April LakePoint tournament with back-to-back run-rule wins, flashing the pitching depth and offensive patience that's defined the spring season. Full recap with box scores inside.
                </p>
                <a href="#" className="btn ghost" style={{ marginTop: 28 }}>READ FULL RECAP <span className="arrow">→</span></a>
              </div>
            </div>
          </div>
        </div>

        {/* Article grid */}
        <div style={{ marginTop: 48, display: 'grid', gridTemplateColumns: '1fr', gap: 16 }}>
          <style>{`@media (min-width: 700px) { .news-grid { grid-template-columns: repeat(2, 1fr) !important; } } @media (min-width: 1100px) { .news-grid { grid-template-columns: repeat(3, 1fr) !important; } }`}</style>
          <div className="news-grid" style={{ display: 'grid', gridTemplateColumns: '1fr', gap: 16 }}>
            {articles.map((a, i) => (
              <a href="#" key={i} className="card" style={{ padding: 0, overflow: 'hidden', display: 'block' }}>
                <div className="ph" style={{ aspectRatio: '4/3', borderRadius: 0, border: 'none' }}>
                  <div style={{ position: 'absolute', top: 12, left: 12, padding: '3px 8px', background: 'var(--ink)', fontFamily: 'var(--font-mono)', fontSize: 9, letterSpacing: '0.2em', color: 'var(--wolf-red-hot)', border: '1px solid var(--wolf-red)' }}>{a.tag}</div>
                  <div className="mono">[IMG]</div>
                </div>
                <div style={{ padding: 20 }}>
                  <div className="mono">{a.date}</div>
                  <h4 className="head" style={{ fontSize: 17, letterSpacing: '0.06em', marginTop: 10, lineHeight: 1.2 }}>{a.title}</h4>
                  <p style={{ marginTop: 10, fontSize: 13, color: 'var(--bone-dim)', lineHeight: 1.6 }}>{a.excerpt}</p>
                </div>
              </a>
            ))}
          </div>
        </div>

        {/* Gallery */}
        <h3 className="display" style={{ fontSize: 'clamp(36px, 6vw, 64px)', marginTop: 80 }}>GALLERY.</h3>
        <div className="mono" style={{ marginTop: 10 }}>◆ RECENT FRAMES · 2012 SEASON</div>
        <div style={{ marginTop: 32, display: 'grid', gridTemplateColumns: 'repeat(2, 1fr)', gap: 8 }}>
          <style>{`@media (min-width: 700px) { .gallery { grid-template-columns: repeat(4, 1fr) !important; } }`}</style>
          <div className="gallery" style={{ gridColumn: '1 / -1', display: 'grid', gridTemplateColumns: 'repeat(2, 1fr)', gap: 8 }}>
            {Array.from({ length: 8 }).map((_, i) => (
              <div key={i} className="ph" style={{ aspectRatio: '1/1', borderRadius: 0 }}>
                <div className="mono">IMG {String(i + 1).padStart(2, '0')}</div>
              </div>
            ))}
          </div>
        </div>
      </div>
    </section>
  );
}

// ============================================================
// RECRUIT / TRYOUTS
// ============================================================
function RecruitPage() {
  const [step, setStep] = useStateP3(1);
  const [data, setData] = useStateP3({
    name: '', email: '', phone: '', dob: '',
    age: '14U · Fall 2026', position: 'P', school: '', exp: '',
    video: '', waiver: false, website: '',
  });
  const [sent, setSent] = useStateP3(false);
  const [submitting, setSubmitting] = useStateP3(false);
  const [error, setError] = useStateP3(null);
  const turnstileRef = useRefP3(null);
  const turnstileWidgetIdRef = useRefP3(null);

  const dates = [
    { group: '14U · OPEN WORKOUT', date: 'JUN 2',  day: 'TUE', time: '6–8 PM' },
    { group: '14U · OPEN WORKOUT', date: 'JUN 9',  day: 'TUE', time: '6–8 PM' },
    { group: '14U · OPEN WORKOUT', date: 'JUN 16', day: 'TUE', time: '6–8 PM' },
    { group: '14U · OPEN WORKOUT', date: 'JUN 23', day: 'TUE', time: '6–8 PM' },
  ];

  // Render Cloudflare Turnstile on step 3 (it lives there) — mirrors ContactPage pattern.
  useEffectP3(() => {
    if (sent || step !== 3) return;
    let cancelled = false;
    let interval = null;
    function tryRender() {
      if (cancelled) return false;
      if (!window.turnstile || !turnstileRef.current) return false;
      turnstileRef.current.innerHTML = '';
      turnstileWidgetIdRef.current = window.turnstile.render(turnstileRef.current, {
        sitekey: '0x4AAAAAADCjUz167sR3etr-',
        theme: 'dark',
      });
      return true;
    }
    if (!tryRender()) {
      interval = setInterval(() => { if (tryRender()) clearInterval(interval); }, 100);
    }
    return () => {
      cancelled = true;
      if (interval) clearInterval(interval);
      if (window.turnstile && turnstileWidgetIdRef.current != null) {
        try { window.turnstile.remove(turnstileWidgetIdRef.current); } catch {}
        turnstileWidgetIdRef.current = null;
      }
    };
  }, [sent, step]);

  async function handleSubmit(e) {
    e.preventDefault();
    if (submitting) return;
    setError(null);

    if (!data.name.trim()) { setError('Athlete name is required.'); return; }
    if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(data.email)) { setError('Please enter a valid parent/guardian email.'); return; }
    if (!data.waiver) { setError('Please acknowledge the waiver to submit.'); return; }
    if (data.video && !/^https?:\/\/[^\s]+$/i.test(data.video.trim())) {
      setError('Highlight video link must be a full URL (https://…).'); return;
    }

    const turnstileToken = new FormData(e.target).get('cf-turnstile-response') || '';
    if (!turnstileToken) { setError('Please complete the verification challenge.'); return; }

    setSubmitting(true);
    try {
      const resp = await fetch('/api/tryout', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          athleteName: data.name,
          dob: data.dob,
          age: data.age,
          school: data.school,
          position: data.position,
          exp: data.exp,
          video: data.video,
          parentEmail: data.email,
          parentPhone: data.phone,
          waiverAck: data.waiver,
          website: data.website,
          turnstileToken,
        }),
      });
      const respBody = await resp.json().catch(() => ({}));
      if (!resp.ok) {
        setError(respBody.error || 'Something went wrong. Try again in a moment.');
        if (window.turnstile) window.turnstile.reset();
      } else {
        setSent(true);
      }
    } catch {
      setError('Network error. Check your connection and try again.');
      if (window.turnstile) window.turnstile.reset();
    } finally {
      setSubmitting(false);
    }
  }

  function resetForm() {
    setSent(false);
    setStep(1);
    setError(null);
    setData({
      name: '', email: '', phone: '', dob: '',
      age: '14U · Fall 2026', position: 'P', school: '', exp: '',
      video: '', waiver: false, website: '',
    });
  }

  return (
    <section className="section grid-bg" style={{ paddingTop: 'clamp(120px, 14vw, 160px)' }}>
      <div className="container">
        <SectionHeader num="08" kicker="OPEN WORKOUTS · 14U · FALL 2026" title="EARN YOUR SPOT." tagline="Open workouts every Tuesday · May & June · 6–8 PM at Joe Cowan Park. Wolfpack is moving up to 14U for Fall 2026 — looking to add a pitcher/utility." />

        {/* Priority need banner */}
        <div className="corners" style={{
          marginTop: 48,
          padding: '18px 24px',
          background: 'linear-gradient(90deg, rgba(196,30,58,0.22), rgba(5,5,6,0.55))',
          border: '1px solid rgba(230,57,70,0.45)',
          borderLeft: '4px solid var(--wolf-red-hot)',
          display: 'flex', flexWrap: 'wrap', gap: 16, alignItems: 'center', justifyContent: 'space-between',
        }}>
          <div>
            <div className="mono" style={{ color: 'var(--wolf-red-hot)', fontSize: 10, letterSpacing: '0.24em' }}>◆ ESTABLISHED COMPETITIVE TEAM</div>
            <div className="head" style={{ fontSize: 'clamp(18px, 2.4vw, 22px)', letterSpacing: '0.08em', marginTop: 6 }}>LOOKING TO ADD A <span style={{ color: 'var(--wolf-red-hot)' }}>PITCHER / UTILITY</span></div>
          </div>
          <div className="mono" style={{ color: 'var(--bone-dim)', fontSize: 11 }}>PRIVATE TRYOUTS AVAILABLE IF PREFERRED</div>
        </div>

        {/* Dates */}
        <div style={{ marginTop: 24, display: 'grid', gridTemplateColumns: '1fr', gap: 8 }}>
          <style>{`@media (min-width: 700px) { .dates-grid { grid-template-columns: repeat(2, 1fr) !important; } } @media (min-width: 1100px) { .dates-grid { grid-template-columns: repeat(4, 1fr) !important; } }`}</style>
          <div className="dates-grid" style={{ display: 'grid', gridTemplateColumns: '1fr', gap: 8 }}>
            {dates.map((d, i) => (
              <div key={i} className="corners" style={{ padding: 24, background: 'var(--ink-3)', borderLeft: '3px solid var(--wolf-red)' }}>
                <div className="mono" style={{ color: 'var(--wolf-red-hot)' }}>{d.group}</div>
                <div className="display" style={{ fontSize: 36, marginTop: 10 }}>{d.date}</div>
                <div className="mono" style={{ marginTop: 6 }}>{d.day} · {d.time}</div>
              </div>
            ))}
          </div>
        </div>

        {/* Form + info */}
        <div style={{ marginTop: 64, display: 'grid', gridTemplateColumns: '1fr', gap: 32 }}>
          <style>{`@media (min-width: 900px) { .form-grid { grid-template-columns: 1.3fr 1fr !important; } }`}</style>
          <div className="form-grid" style={{ display: 'grid', gridTemplateColumns: '1fr', gap: 32 }}>
            {/* Multi-step form */}
            <div className="corners" style={{ padding: 'clamp(24px, 4vw, 36px)', background: 'var(--ink-2)' }}>
              {sent ? (
                <div style={{ textAlign: 'center', padding: '12px 0 24px' }}>
                  <div className="eyebrow" style={{ color: 'var(--wolf-red-hot)' }}><span className="live-dot"/>&nbsp;&nbsp;REGISTRATION RECEIVED</div>
                  <div className="display" style={{ fontSize: 'clamp(56px, 9vw, 88px)', color: 'var(--wolf-red-hot)', lineHeight: 0.9, marginTop: 14 }}>
                    YOU'RE IN<br/>THE HUNT.
                  </div>
                  <p style={{ marginTop: 22, fontSize: 15, color: 'var(--bone-dim)', lineHeight: 1.6, maxWidth: 460, margin: '22px auto 0' }}>
                    Thanks{data.name ? `, ${data.name.split(' ')[0]}` : ''}. Coach Cole will reach out within <strong style={{ color: 'var(--bone)' }}>48 hours</strong> to confirm your workout date and answer any questions.
                  </p>
                  <div style={{
                    marginTop: 28, padding: '18px 22px', textAlign: 'left',
                    background: 'rgba(5,5,6,0.55)', border: '1px solid rgba(230,57,70,0.35)',
                  }}>
                    <div className="mono" style={{ color: 'var(--wolf-red-hot)', fontSize: 10, letterSpacing: '0.22em' }}>◆ WHAT HAPPENS NEXT</div>
                    <ol style={{ margin: '10px 0 0', paddingLeft: 18, color: 'var(--bone)', fontSize: 14, lineHeight: 1.7 }}>
                      <li>We email <span className="mono" style={{ color: 'var(--bone-dim)' }}>{data.email}</span> with a confirmation.</li>
                      <li>Coach Cole calls/texts to schedule.</li>
                      <li>Show up at <strong>Joe Cowan Park</strong>, Euharlee — Tuesdays, 6–8 PM.</li>
                    </ol>
                  </div>
                  <div className="mono" style={{ marginTop: 24, color: 'var(--bone-dim)', fontSize: 11, lineHeight: 1.8 }}>
                    Questions before then?<br/>
                    ◆ COACH COLE · <a href="tel:+14043919872" style={{ color: 'var(--wolf-red-hot)' }}>404·391·9872</a>
                  </div>
                  <button type="button" className="btn ghost" style={{ marginTop: 28 }} onClick={resetForm}>REGISTER ANOTHER ATHLETE</button>
                </div>
              ) : (
                <form onSubmit={handleSubmit} noValidate>
                  <div className="eyebrow">REGISTRATION · STEP {step} OF 3</div>
                  <h3 className="display" style={{ fontSize: 40, marginTop: 14 }}>SIGN UP.</h3>

                  {/* Progress */}
                  <div style={{ marginTop: 24, display: 'flex', gap: 6 }}>
                    {[1,2,3].map(n => (
                      <div key={n} style={{ flex: 1, height: 4, background: n <= step ? 'var(--wolf-red)' : 'rgba(255,255,255,0.08)', transition: 'background 300ms' }}/>
                    ))}
                  </div>

                  <div style={{ marginTop: 32, display: 'grid', gap: 16 }}>
                    {step === 1 && <>
                      <FormField label="ATHLETE NAME" value={data.name} onChange={v => setData({...data, name: v})} placeholder="JANE DOE"/>
                      <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 16 }}>
                        <FormField label="DATE OF BIRTH" value={data.dob} onChange={v => setData({...data, dob: v})} placeholder="MM/DD/YYYY"/>
                        <FormSelect label="AGE DIVISION" value={data.age} onChange={v => setData({...data, age: v})} options={['14U · Fall 2026']}/>
                      </div>
                      <FormField label="SCHOOL" value={data.school} onChange={v => setData({...data, school: v})} placeholder="HIGH SCHOOL / MIDDLE SCHOOL"/>
                    </>}
                    {step === 2 && <>
                      <FormSelect label="PRIMARY POSITION" value={data.position} onChange={v => setData({...data, position: v})} options={['P','C','1B','2B','3B','SS','LF','CF','RF','UTIL']}/>
                      <FormField label="YEARS OF EXPERIENCE" value={data.exp} onChange={v => setData({...data, exp: v})} placeholder="e.g. 4 YEARS TRAVEL"/>
                      <FormField label="HIGHLIGHT VIDEO LINK (OPTIONAL)" value={data.video} onChange={v => setData({...data, video: v})} placeholder="https://youtu.be/... or hudl.com/..." type="url"/>
                      <div className="mono" style={{ fontSize: 10, color: 'var(--bone-dim)', lineHeight: 1.6 }}>
                        ◆ Paste a YouTube, Hudl, or GameChanger link. Uploads not accepted.
                      </div>
                    </>}
                    {step === 3 && <>
                      <FormField label="PARENT/GUARDIAN EMAIL" value={data.email} onChange={v => setData({...data, email: v})} placeholder="parent@example.com" type="email"/>
                      <FormField label="PARENT PHONE" value={data.phone} onChange={v => setData({...data, phone: v})} placeholder="(404) 555-0100" type="tel"/>
                      <label style={{ display: 'flex', gap: 12, alignItems: 'start', fontSize: 13, color: 'var(--bone-dim)', cursor: 'pointer' }}>
                        <input type="checkbox" checked={data.waiver} onChange={e => setData({...data, waiver: e.target.checked})} style={{ marginTop: 4, accentColor: 'var(--wolf-red-hot)' }}/>
                        <span>I acknowledge the open-workout/tryout waiver and confirm the athlete is medically cleared to participate.</span>
                      </label>
                      {/* Honeypot — hidden from humans */}
                      <input type="text" name="website" tabIndex={-1} autoComplete="off"
                        value={data.website} onChange={e => setData({...data, website: e.target.value})}
                        style={{ position: 'absolute', left: '-9999px', width: 1, height: 1, opacity: 0 }}
                        aria-hidden="true" />
                      <div ref={turnstileRef} style={{ marginTop: 4 }} />
                      {error && (
                        <div className="mono" style={{ color: 'var(--wolf-red-hot)', fontSize: 11, letterSpacing: '0.1em' }}>
                          ◆ {error}
                        </div>
                      )}
                    </>}
                  </div>

                  <div style={{ marginTop: 32, display: 'flex', gap: 10, justifyContent: 'space-between' }}>
                    <button type="button" className="btn ghost" onClick={() => { setError(null); setStep(Math.max(1, step - 1)); }} disabled={step === 1 || submitting} style={{ opacity: (step === 1 || submitting) ? 0.3 : 1 }}>← BACK</button>
                    {step < 3
                      ? <button type="button" className="btn" onClick={() => setStep(step + 1)}>NEXT STEP <span className="arrow">→</span></button>
                      : <button type="submit" className="btn" disabled={submitting} style={{ opacity: submitting ? 0.6 : 1 }}>
                          {submitting ? 'SUBMITTING…' : <>SUBMIT <span className="arrow">→</span></>}
                        </button>}
                  </div>
                </form>
              )}
            </div>

            {/* What to bring */}
            <div style={{ display: 'grid', gap: 24 }}>
              <div className="corners" style={{ padding: 28, background: 'var(--ink-3)' }}>
                <div className="eyebrow">WHAT TO BRING</div>
                <div style={{ marginTop: 20, display: 'grid', gap: 14 }}>
                  {['Glove, cleats, batting helmet','Bat & protective gear','Water & snacks','Athletic gear · ready to compete','Positive attitude. No exceptions.'].map((x, i) => (
                    <div key={i} style={{ display: 'grid', gridTemplateColumns: '20px 1fr', fontSize: 14 }}>
                      <span style={{ color: 'var(--wolf-red-hot)' }}>◆</span>
                      <span style={{ color: 'var(--bone)' }}>{x}</span>
                    </div>
                  ))}
                </div>
              </div>
              <div className="corners" style={{ padding: 28, background: 'var(--ink-3)' }}>
                <div className="eyebrow">LOCATION</div>
                <div className="display" style={{ fontSize: 28, marginTop: 12 }}>JOE COWAN<br/>PARK</div>
                <div className="mono" style={{ marginTop: 14, color: 'var(--bone-dim)', lineHeight: 1.8 }}>
                  EUHARLEE, GA · BARTOW CO<br/>
                  PRIVATE TRYOUTS AVAILABLE IF PREFERRED
                </div>
              </div>
              <div className="corners" style={{ padding: 28, background: 'var(--ink-3)', borderLeft: '3px solid var(--wolf-red)' }}>
                <div className="eyebrow">CONTACT COACH COLE</div>
                <a href="tel:+14043919872" className="display" style={{ display: 'block', fontSize: 28, marginTop: 12, color: 'var(--bone)', letterSpacing: '0.04em' }}>404·391·9872</a>
                <div className="mono" style={{ marginTop: 12, color: 'var(--bone-dim)', lineHeight: 1.8 }}>
                  CALL OR TEXT FOR QUESTIONS,<br/>PRIVATE TRYOUTS, OR DIRECTIONS
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </section>
  );
}

function FormField({ label, value, onChange, placeholder, type = 'text' }) {
  return (
    <label style={{ display: 'block' }}>
      <div className="mono" style={{ marginBottom: 6 }}>{label}</div>
      <input type={type} value={value} onChange={(e) => onChange(e.target.value)} placeholder={placeholder}
        style={{
          width: '100%', padding: 14,
          background: 'var(--ink-3)', border: '1px solid rgba(255,255,255,0.1)',
          color: 'var(--bone)', fontFamily: 'var(--font-head)', fontSize: 15, letterSpacing: '0.06em',
        }}/>
    </label>
  );
}
function FormSelect({ label, value, onChange, options }) {
  return (
    <label style={{ display: 'block' }}>
      <div className="mono" style={{ marginBottom: 6 }}>{label}</div>
      <select value={value} onChange={(e) => onChange(e.target.value)}
        style={{
          width: '100%', padding: 14,
          background: 'var(--ink-3)', border: '1px solid rgba(255,255,255,0.1)',
          color: 'var(--bone)', fontFamily: 'var(--font-head)', fontSize: 15, letterSpacing: '0.06em',
        }}>
        {options.map(o => <option key={o} value={o}>{o}</option>)}
      </select>
    </label>
  );
}

// ============================================================
// CONTACT
// ============================================================
function ContactPage() {
  const [sent, setSent] = useStateP3(false);
  const [form, setForm] = useStateP3({ name: '', email: '', reason: 'General', message: '', website: '' });
  const [submitting, setSubmitting] = useStateP3(false);
  const [error, setError] = useStateP3(null);
  const turnstileRef = useRefP3(null);
  const turnstileWidgetIdRef = useRefP3(null);

  const updateField = (key) => (val) => setForm((f) => ({ ...f, [key]: val }));

  // Explicit Turnstile render — the script's auto-scan misses React-mounted nodes.
  useEffectP3(() => {
    if (sent) return;
    let cancelled = false;
    let interval = null;
    function tryRender() {
      if (cancelled) return false;
      if (!window.turnstile || !turnstileRef.current) return false;
      // Clear any stale widget in this container before re-rendering.
      turnstileRef.current.innerHTML = '';
      turnstileWidgetIdRef.current = window.turnstile.render(turnstileRef.current, {
        sitekey: '0x4AAAAAADCjUz167sR3etr-',
        theme: 'dark',
      });
      return true;
    }
    if (!tryRender()) {
      interval = setInterval(() => { if (tryRender()) clearInterval(interval); }, 100);
    }
    return () => {
      cancelled = true;
      if (interval) clearInterval(interval);
      if (window.turnstile && turnstileWidgetIdRef.current != null) {
        try { window.turnstile.remove(turnstileWidgetIdRef.current); } catch {}
        turnstileWidgetIdRef.current = null;
      }
    };
  }, [sent]);

  async function handleSubmit(e) {
    e.preventDefault();
    if (submitting) return;
    const turnstileToken = new FormData(e.target).get('cf-turnstile-response') || '';
    if (!turnstileToken) {
      setError('Please complete the verification challenge.');
      return;
    }
    setSubmitting(true);
    setError(null);
    try {
      const resp = await fetch('/api/contact', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ ...form, turnstileToken }),
      });
      const data = await resp.json().catch(() => ({}));
      if (!resp.ok) {
        setError(data.error || 'Something went wrong. Try again in a moment.');
        if (window.turnstile) window.turnstile.reset();
      } else {
        setSent(true);
        setForm({ name: '', email: '', reason: 'General', message: '', website: '' });
      }
    } catch {
      setError('Network error. Check your connection and try again.');
      if (window.turnstile) window.turnstile.reset();
    } finally {
      setSubmitting(false);
    }
  }

  return (
    <section className="section grid-bg" style={{ paddingTop: 'clamp(120px, 14vw, 160px)' }}>
      <div className="container">
        <SectionHeader num="08" kicker="CONTACT · TRYOUTS · GENERAL" title="HOWL AT US." tagline="Questions about tryouts, sponsorship, press, or the program — this is where to reach us." />

        {/* TRYOUTS CALLOUT — most important thing on this page */}
        <div className="corners" style={{
          marginTop: 48, position: 'relative', overflow: 'hidden',
          background: 'linear-gradient(135deg, rgba(196,30,58,0.18), rgba(5,5,6,0.6))',
          border: '1px solid rgba(230,57,70,0.45)',
          padding: 'clamp(28px, 4vw, 48px)',
        }}>
          <div aria-hidden style={{ position: 'absolute', top: -60, right: -60, width: 280, height: 280, background: 'radial-gradient(circle, rgba(230,57,70,0.3), transparent 65%)', pointerEvents: 'none' }}/>
          <div style={{ display: 'grid', gridTemplateColumns: '1fr', gap: 28, position: 'relative' }}>
            <style>{`@media (min-width: 820px) { .tryouts-cta { grid-template-columns: 1.25fr 1fr !important; } }`}</style>
            <div className="tryouts-cta" style={{ display: 'grid', gridTemplateColumns: '1fr', gap: 28 }}>
              <div>
                <div className="eyebrow"><span className="live-dot"/>&nbsp;&nbsp;OPEN WORKOUTS · 14U · FALL 2026</div>
                <h3 className="display" style={{ fontSize: 'clamp(40px, 7vw, 72px)', marginTop: 10, lineHeight: 0.95 }}>
                  EARN YOUR<br/><span style={{ color: 'var(--wolf-red-hot)' }}>SPOT.</span>
                </h3>
                <p style={{ marginTop: 16, fontSize: 15, color: 'var(--bone-dim)', lineHeight: 1.65, maxWidth: 520 }}>
                  Wolfpack is <strong style={{ color: 'var(--bone)' }}>moving up to 14U for Fall 2026</strong>. Established competitive team <strong style={{ color: 'var(--wolf-red-hot)' }}>looking to add a pitcher / utility</strong>. Open workouts run every Tuesday in May & June — private tryouts available if preferred.
                </p>
                <div className="mono" style={{ marginTop: 18, color: 'var(--bone-dim)', lineHeight: 1.9 }}>
                  ◆ WHAT TO BRING — GLOVE · CLEATS · HELMET · BAT<br/>
                  ◆ WATER · READY TO COMPETE
                </div>
                <div className="mono" style={{ marginTop: 14, lineHeight: 1.7 }}>
                  ◆ COACH COLE · <a href="tel:+14043919872" style={{ color: 'var(--wolf-red-hot)' }}>404·391·9872</a>
                </div>
              </div>
              <div style={{ display: 'grid', gap: 12, alignContent: 'start' }}>
                {[
                  { kicker: 'OPEN WORKOUTS', value: 'EVERY TUE · MAY & JUN', sub: '6:00 PM – 8:00 PM' },
                  { kicker: 'LOCATION', value: 'JOE COWAN PARK', sub: 'Euharlee, GA · Bartow County' },
                  { kicker: 'AGE GROUP', value: '14U · FALL 2026', sub: 'Moving up from 12U.' },
                ].map(r => (
                  <div key={r.kicker} style={{ padding: 18, border: '1px solid rgba(255,255,255,0.08)', background: 'rgba(5,5,6,0.55)' }}>
                    <div className="mono" style={{ color: 'var(--wolf-red-hot)', fontSize: 9, letterSpacing: '0.24em' }}>◆ {r.kicker}</div>
                    <div className="head" style={{ fontSize: 18, letterSpacing: '0.08em', marginTop: 8 }}>{r.value}</div>
                    <div className="mono" style={{ marginTop: 6, color: 'var(--bone-dim)', textTransform: 'none', letterSpacing: '0.05em' }}>{r.sub}</div>
                  </div>
                ))}
              </div>
            </div>
          </div>
        </div>

        <div id="contact-form" style={{ marginTop: 48, display: 'grid', gridTemplateColumns: '1fr', gap: 32 }}>
          <style>{`@media (min-width: 900px) { .contact-grid { grid-template-columns: 1fr 1fr !important; } }`}</style>
          <div className="contact-grid" style={{ display: 'grid', gridTemplateColumns: '1fr', gap: 32 }}>
            {/* Info */}
            <div style={{ display: 'grid', gap: 20 }}>
              {/* Home base map */}
              <MapPanel />
              {[
                { label: 'COACH COLE', value: '404·391·9872', sub: 'Call or text · tryouts, directions, questions', href: 'tel:+14043919872' },
                { label: 'GENERAL', value: 'howl@ngwolfpack.com', sub: 'Responses within 48h', href: 'mailto:howl@ngwolfpack.com' },
              ].map(c => (
                <div key={c.label} className="corners" style={{ padding: 24, background: 'var(--ink-3)' }}>
                  <div className="mono" style={{ color: 'var(--wolf-red-hot)' }}>◆ {c.label}</div>
                  {c.href
                    ? <a href={c.href} className="head" style={{ display: 'block', fontSize: 18, letterSpacing: '0.06em', marginTop: 10, color: 'var(--bone)' }}>{c.value}</a>
                    : <div className="head" style={{ fontSize: 18, letterSpacing: '0.06em', marginTop: 10 }}>{c.value}</div>}
                  <div className="mono" style={{ marginTop: 6, color: 'var(--bone-dim)' }}>{c.sub}</div>
                </div>
              ))}
              <div className="corners" style={{ padding: 24, background: 'var(--ink-3)' }}>
                <div className="mono" style={{ color: 'var(--wolf-red-hot)' }}>◆ FOLLOW THE PACK</div>
                <div style={{ marginTop: 14, display: 'flex', gap: 12 }}>
                  <a href="https://www.facebook.com/profile.php?id=100090483468332" target="_blank" rel="noopener" aria-label="Facebook" style={{ width: 40, height: 40, border: '1px solid rgba(255,255,255,0.12)', display: 'grid', placeItems: 'center', fontFamily: 'var(--font-head)', fontSize: 11, letterSpacing: '0.1em' }}>FB</a>
                  <a href="https://web.gc.com/teams/hOv2dnrLHWLy?utm_source=Web&utm_campaign=team_share_link" target="_blank" rel="noopener" aria-label="GameChanger" style={{ width: 40, height: 40, border: '1px solid rgba(255,255,255,0.12)', display: 'grid', placeItems: 'center' }}>
                    <img src="assets/gc-logo.png" alt="" style={{ width: 22, height: 22, display: 'block' }}/>
                  </a>
                </div>
              </div>
            </div>

            {/* Form */}
            <div className="corners" style={{ padding: 'clamp(24px, 4vw, 36px)', background: 'var(--ink-2)', alignSelf: 'start' }}>
              <div className="eyebrow">{sent ? 'MESSAGE RECEIVED' : 'SEND A MESSAGE'}</div>
              {sent ? (
                <div style={{ padding: '48px 0', textAlign: 'center' }}>
                  <div className="display" style={{ fontSize: 60, color: 'var(--wolf-red-hot)' }}>◆ SENT</div>
                  <p style={{ marginTop: 14, color: 'var(--bone-dim)' }}>We'll respond within 48 hours. Stay sharp.</p>
                  <button className="btn ghost" style={{ marginTop: 28 }} onClick={() => setSent(false)}>NEW MESSAGE</button>
                </div>
              ) : (
                <form onSubmit={handleSubmit} style={{ marginTop: 24, display: 'grid', gap: 16 }}>
                  <FormField label="YOUR NAME" value={form.name} onChange={updateField('name')} placeholder="JANE DOE" />
                  <FormField label="EMAIL" value={form.email} onChange={updateField('email')} placeholder="jane@example.com" />
                  <FormSelect label="REASON" value={form.reason} onChange={updateField('reason')} options={['General','Tryouts','Sponsorship','Press','Other']} />
                  <label>
                    <div className="mono" style={{ marginBottom: 6 }}>MESSAGE</div>
                    <textarea placeholder="Tell us what's up..." rows={5}
                      value={form.message}
                      onChange={(e) => updateField('message')(e.target.value)}
                      style={{
                        width: '100%', padding: 14,
                        background: 'var(--ink-3)', border: '1px solid rgba(255,255,255,0.1)',
                        color: 'var(--bone)', fontFamily: 'var(--font-body)', fontSize: 14, resize: 'vertical',
                      }}/>
                  </label>
                  {/* Honeypot — hidden from humans */}
                  <input type="text" name="website" tabIndex={-1} autoComplete="off"
                    value={form.website} onChange={(e) => updateField('website')(e.target.value)}
                    style={{ position: 'absolute', left: '-9999px', width: 1, height: 1, opacity: 0 }}
                    aria-hidden="true" />
                  {/* Cloudflare Turnstile widget — rendered explicitly in useEffect above */}
                  <div ref={turnstileRef} />
                  {error && (
                    <div className="mono" style={{ color: 'var(--wolf-red-hot)', fontSize: 11, letterSpacing: '0.1em' }}>
                      ◆ {error}
                    </div>
                  )}
                  <button type="submit" className="btn" disabled={submitting} style={{ width: '100%', justifyContent: 'center', opacity: submitting ? 0.6 : 1 }}>
                    {submitting ? 'SENDING…' : <>SEND MESSAGE <span className="arrow">→</span></>}
                  </button>
                </form>
              )}
            </div>
          </div>
        </div>
      </div>
    </section>
  );
}

Object.assign(window, { NewsPage, RecruitPage, ContactPage });
