/* Events screen with RSVP */

const { useState: useStateE } = React;

const formatPhone = (raw) => {
  const digits = raw.replace(/\D/g, '').slice(0, 10);
  if (digits.length === 0) return '';
  if (digits.length <= 3) return `(${digits}`;
  if (digits.length <= 6) return `(${digits.slice(0,3)}) ${digits.slice(3)}`;
  return `(${digits.slice(0,3)}) ${digits.slice(3,6)}-${digits.slice(6)}`;
};

const CHECKIN_BLURB = "Drop by for an informal coffee with Matthew. No agenda, no speeches — just a chance to share what's on your mind.";

// Derive display fields (MONTH / DAY / Dow) from an ISO date string.
// Parsed at local noon to avoid UTC-vs-local off-by-one.
const dateFor = (iso) => {
  const d = new Date(iso + 'T12:00:00');
  return {
    month: d.toLocaleDateString('en-US', { month: 'short' }).toUpperCase(),
    day: String(d.getDate()).padStart(2, '0'),
    dow: d.toLocaleDateString('en-US', { weekday: 'short' }),
  };
};

// Today as YYYY-MM-DD in the viewer's local timezone — used to drop past events.
const todayISO = () => {
  const n = new Date();
  return `${n.getFullYear()}-${String(n.getMonth() + 1).padStart(2, '0')}-${String(n.getDate()).padStart(2, '0')}`;
};

const EVENTS = [
  // Van Pelt campaign events will be added here as they are scheduled.
  // Empty array renders the "More events coming soon" empty state below.
];

const EventCard = ({ evt, rsvp, onRsvp, onPoster }) => {
  const [hover, setHover] = useStateE(false);
  const joined = rsvp[evt.id];
  const d = dateFor(evt.date);
  return (
    <article
      className="event-row"
      onMouseEnter={() => setHover(true)}
      onMouseLeave={() => setHover(false)}
      style={{
        background: '#fff',
        border: '1px solid var(--divider)',
        borderRadius: 4,
        gap: 0,
        transition: 'border-color 200ms var(--ease-standard), box-shadow 200ms var(--ease-standard)',
        boxShadow: hover ? '0 8px 24px rgba(10, 39, 84, 0.06)' : 'none',
        borderColor: hover ? 'var(--color-ink-soft)' : 'var(--divider)',
      }}>
      {/* Date block */}
      <div style={{
        background: 'var(--color-paper)',
        borderRight: '1px solid var(--divider)',
        padding: '22px 18px', textAlign: 'center',
        display: 'flex', flexDirection: 'column', justifyContent: 'center',
      }}>
        <div style={{ fontSize: 11, fontWeight: 700, letterSpacing: '0.18em', color: 'var(--brand-accent-warm)' }}>
          {d.month}
        </div>
        <div style={{
          fontFamily: 'var(--font-display)', fontSize: 44, fontWeight: 800,
          lineHeight: 1, color: 'var(--brand-primary)', letterSpacing: '-0.02em',
          margin: '6px 0 4px',
        }}>{d.day}</div>
        <div style={{ fontSize: 12, color: 'var(--color-muted)', letterSpacing: '0.08em', textTransform: 'uppercase', fontWeight: 600 }}>
          {d.dow}
        </div>
      </div>

      {/* Details */}
      <div style={{ padding: '22px 26px', display: 'flex', flexDirection: 'column', gap: 6 }}>
        <div style={{ display: 'flex', gap: 10, alignItems: 'center' }}>
          <span style={{
            fontSize: 11, fontWeight: 700, letterSpacing: '0.14em', textTransform: 'uppercase',
            color: 'var(--color-blue-700)',
            background: 'var(--color-blue-100)',
            padding: '4px 8px', borderRadius: 2,
          }}>{evt.tag}</span>
          <span style={{ fontSize: 13, color: 'var(--color-muted)' }}>{evt.time}</span>
        </div>
        <h3 className="h3" style={{ margin: '4px 0 2px' }}>{evt.title}</h3>
        <div style={{ fontSize: 14, color: 'var(--color-ink-soft)' }}>
          <strong style={{ color: 'var(--color-ink)', fontWeight: 600 }}>{evt.loc}</strong> · {evt.addr}
        </div>
        <p style={{ margin: '6px 0 0', fontSize: 14, color: 'var(--color-ink-soft)', lineHeight: 1.5 }}>
          {evt.blurb}
        </p>
        {evt.poster && (
          <button
            type="button"
            onClick={() => onPoster(evt.id)}
            style={{
              marginTop: 14,
              display: 'inline-flex', alignItems: 'center', gap: 12,
              background: 'var(--color-paper)',
              border: '1px solid var(--divider)',
              borderRadius: 4,
              padding: '8px 14px 8px 8px',
              cursor: 'pointer',
              fontFamily: 'var(--font-sans)', fontSize: 13, fontWeight: 600,
              color: 'var(--color-ink-soft)',
              alignSelf: 'flex-start',
              transition: 'border-color 150ms var(--ease-standard), color 150ms var(--ease-standard)',
            }}
            onMouseEnter={e => { e.currentTarget.style.borderColor = 'var(--color-ink-soft)'; e.currentTarget.style.color = 'var(--color-ink)'; }}
            onMouseLeave={e => { e.currentTarget.style.borderColor = 'var(--divider)'; e.currentTarget.style.color = 'var(--color-ink-soft)'; }}
            aria-label="View event poster"
          >
            <img src={evt.poster} alt=""
                 style={{ width: 64, height: 48, objectFit: 'cover', borderRadius: 2, display: 'block', boxShadow: '0 1px 3px rgba(0,0,0,0.15)' }} />
            <span>View event poster &nbsp;›</span>
          </button>
        )}
      </div>

      {/* RSVP button */}
      {evt.rsvp && (
        <div className="event-rsvp" style={{ padding: 22, display: 'flex', alignItems: 'center' }}>
          {joined ? (
            <div style={{
              padding: '12px 18px', borderRadius: 4,
              background: 'var(--color-green-100)', color: 'var(--color-green-900)',
              fontFamily: 'var(--font-sans)', fontSize: 14, fontWeight: 600,
              display: 'flex', gap: 8, alignItems: 'center',
            }}>
              ✓ You&rsquo;re in
            </div>
          ) : (
            <Button variant="secondary" onClick={() => onRsvp(evt.id)} style={{ padding: '11px 20px', fontSize: 14 }}>
              RSVP
            </Button>
          )}
        </div>
      )}
    </article>
  );
};

const EventsScreen = ({ onNavigate }) => {
  const [rsvp, setRsvp] = useStateE({});
  const [modal, setModal] = useStateE(null);
  const [poster, setPoster] = useStateE(null);
  const [form, setForm] = useStateE({ name: '', email: '', guests: 1 });
  const [err, setErr] = useStateE('');
  const [honeypotR, setHoneypotR] = useStateE('');
  const [rsvpOpenedAt, setRsvpOpenedAt] = useStateE(0);

  const [apprOpen, setApprOpen] = useStateE(false);
  const [apprDone, setApprDone] = useStateE(false);
  const [apprErr, setApprErr] = useStateE('');
  const [apprSubmitting, setApprSubmitting] = useStateE(false);
  const [apprHoneypot, setApprHoneypot] = useStateE('');
  const [apprOpenedAt, setApprOpenedAt] = useStateE(0);
  const [apprForm, setApprForm] = useStateE({
    name: '', email: '', phone: '',
    org_name: '', org_type: '', org_url: '',
    event_name: '', proposed_date: '', alt_date: '',
    start_time: '', duration: '', audience_size: '', format: '',
    venue_name: '', street: '', city: '', state: 'WA', zip: '',
    media_present: '', other_officials: '', notes: '',
  });

  const ORG_TYPES = ['Community group', 'Faith group', 'Civic org', 'Business / Chamber', 'Union', 'School / PTA', 'HOA / Neighborhood', 'Political club', 'Other'];
  const AUDIENCE_SIZES = ['Under 25', '25–50', '50–100', '100–250', '250+'];
  const DURATIONS = ['15 min remarks', '30 min remarks + Q&A', '45 min remarks + Q&A', '60+ min', 'Open / Other'];
  const FORMATS = ['Speech', 'Q&A only', 'Panel', 'Town hall', 'Meet & greet', 'Other'];
  const US_STATES = [
    ['AL','Alabama'],['AK','Alaska'],['AZ','Arizona'],['AR','Arkansas'],['CA','California'],
    ['CO','Colorado'],['CT','Connecticut'],['DE','Delaware'],['DC','District of Columbia'],
    ['FL','Florida'],['GA','Georgia'],['HI','Hawaii'],['ID','Idaho'],['IL','Illinois'],
    ['IN','Indiana'],['IA','Iowa'],['KS','Kansas'],['KY','Kentucky'],['LA','Louisiana'],
    ['ME','Maine'],['MD','Maryland'],['MA','Massachusetts'],['MI','Michigan'],['MN','Minnesota'],
    ['MS','Mississippi'],['MO','Missouri'],['MT','Montana'],['NE','Nebraska'],['NV','Nevada'],
    ['NH','New Hampshire'],['NJ','New Jersey'],['NM','New Mexico'],['NY','New York'],
    ['NC','North Carolina'],['ND','North Dakota'],['OH','Ohio'],['OK','Oklahoma'],['OR','Oregon'],
    ['PA','Pennsylvania'],['RI','Rhode Island'],['SC','South Carolina'],['SD','South Dakota'],
    ['TN','Tennessee'],['TX','Texas'],['UT','Utah'],['VT','Vermont'],['VA','Virginia'],
    ['WA','Washington'],['WV','West Virginia'],['WI','Wisconsin'],['WY','Wyoming'],
  ];

  const openRsvp = (id) => { setModal(id); setErr(''); setForm({ name: '', email: '', guests: 1 }); setRsvpOpenedAt(Date.now()); };
  const closeRsvp = () => setModal(null);

  const openAppearance = () => {
    setApprErr('');
    setApprDone(false);
    setApprOpenedAt(Date.now());
    setApprOpen(true);
  };

  const submitAppearance = async (e) => {
    e.preventDefault();
    if (apprSubmitting) return;

    if (apprHoneypot) { setApprDone(true); return; }
    if (Date.now() - apprOpenedAt < 2000) { setApprDone(true); return; }

    if (!apprForm.name.trim()) return setApprErr('Please enter your name.');
    if (!/^[^@\s]+@[^@\s]+\.[^@\s]+$/.test(apprForm.email)) return setApprErr('Please enter a valid email.');
    if (!apprForm.phone.replace(/\D/g, '').match(/^\d{10,}$/)) return setApprErr('Please enter a valid phone number.');
    if (!apprForm.org_name.trim()) return setApprErr('Please enter the organization name.');
    if (!apprForm.event_name.trim()) return setApprErr('Please enter the event name.');
    if (!apprForm.proposed_date) return setApprErr('Please pick a proposed date.');

    setApprErr('');
    setApprSubmitting(true);
    try {
      const resp = await fetch('/api/forms/appearance-request', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          ...apprForm,
          phone: apprForm.phone.replace(/\D/g, ''),
          email: apprForm.email.trim().toLowerCase(),
        }),
      });
      const data = await resp.json().catch(() => ({}));
      if (!resp.ok) {
        setApprSubmitting(false);
        return setApprErr(data.error || 'Something went wrong. Please try again.');
      }
      setApprSubmitting(false);
      setApprDone(true);
    } catch (err) {
      console.error('[appearance submit]', err);
      setApprSubmitting(false);
      setApprErr('Network error. Please try again.');
    }
  };
  const submit = async (e) => {
    e.preventDefault();
    if (honeypotR) { setRsvp(r => ({ ...r, [modal]: { ...form } })); setModal(null); return; }
    if (Date.now() - rsvpOpenedAt < 2000) { setRsvp(r => ({ ...r, [modal]: { ...form } })); setModal(null); return; }
    if (!form.name.trim()) return setErr('Please enter your name.');
    if (!/^[^@\s]+@[^@\s]+\.[^@\s]+$/.test(form.email)) return setErr('Please enter a valid email.');

    if (!window.supabaseClient) {
      return setErr('Connection issue. Please try again.');
    }

    const { error } = await window.supabaseClient
      .from('rsvps')
      .insert({
        event_id: modal,
        name: form.name.trim(),
        email: form.email.trim().toLowerCase(),
        guests: form.guests,
      });

    if (error) {
      console.error('[rsvps insert]', error);
      return setErr('Something went wrong. Please try again.');
    }

    setRsvp(r => ({ ...r, [modal]: { ...form } }));
    setModal(null);
  };

  const confirmed = Object.keys(rsvp).length;

  return (
    <section className="section" style={{ padding: '96px 32px 128px', background: 'var(--color-paper)' }}>
      <div style={{ maxWidth: 1160, margin: '0 auto' }}>
        <GoldRule />
        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'end', gap: 24, flexWrap: 'wrap', marginTop: 20 }}>
          <div>
            <Eyebrow>Events</Eyebrow>
            <h1 className="h1" style={{ margin: '14px 0 0', maxWidth: '22ch' }}>
              Meet Matthew across Island County.
            </h1>
          </div>
          {confirmed > 0 && (
            <div style={{
              fontFamily: 'var(--font-sans)', fontSize: 14,
              padding: '10px 16px', borderRadius: 999,
              background: 'var(--color-green-100)', color: 'var(--color-green-900)',
              fontWeight: 600,
            }}>
              ✓ {confirmed} event{confirmed === 1 ? '' : 's'} confirmed
            </div>
          )}
        </div>
        <p className="lead" style={{ maxWidth: '52ch', margin: '20px 0 48px' }}>
          Town halls, coffee meetups, and door-knocks. Pick one. Bring a neighbor.
        </p>

        <div style={{ display: 'grid', gap: 14 }}>
          {(() => {
            const today = todayISO();
            const upcoming = EVENTS.filter(e => e.date >= today)
                                   .sort((a, b) => a.date.localeCompare(b.date));
            if (upcoming.length === 0) {
              return (
                <div style={{
                  padding: '28px 32px',
                  background: '#fff',
                  border: '1px solid var(--divider)',
                  borderRadius: 4,
                  textAlign: 'center',
                  color: 'var(--color-ink-soft)',
                  fontSize: 15,
                }}>
                  More events coming soon. Check back shortly.
                </div>
              );
            }
            return upcoming.map(evt => (
              <EventCard key={evt.id} evt={evt} rsvp={rsvp} onRsvp={openRsvp} onPoster={setPoster} />
            ));
          })()}
        </div>

        <div style={{ marginTop: 64, padding: 28, background: '#fff', border: '1px solid var(--divider)', borderRadius: 4, display: 'flex', justifyContent: 'space-between', gap: 20, flexWrap: 'wrap', alignItems: 'center' }}>
          <div>
            <div style={{ fontFamily: 'var(--font-display)', fontSize: 22, fontWeight: 700, color: 'var(--color-ink)' }}>
              Want Matthew at your event?
            </div>
            <div style={{ fontSize: 14, color: 'var(--color-ink-soft)', marginTop: 4, maxWidth: '54ch' }}>
              Book clubs, union halls, PTAs, neighborhood gatherings — Matthew will show up. 22 years of being the guy who shows up for Island County doesn&rsquo;t stop now.
            </div>
          </div>
          <Button variant="primary" onClick={() => openAppearance()}>Request an appearance &nbsp;›</Button>
        </div>
      </div>

      {/* Poster lightbox */}
      {poster && (() => {
        const evt = EVENTS.find(e => e.id === poster);
        if (!evt) return null;
        return (
          <div
            onClick={() => setPoster(null)}
            style={{
              position: 'fixed', inset: 0, zIndex: 220,
              background: 'rgba(10, 39, 84, 0.78)',
              backdropFilter: 'blur(6px)',
              display: 'flex', alignItems: 'center', justifyContent: 'center',
              padding: 24,
              animation: 'fadeInUp 200ms var(--ease-standard) both',
              cursor: 'zoom-out',
            }}>
            <button
              onClick={() => setPoster(null)}
              aria-label="Close poster"
              style={{
                position: 'absolute', top: 18, right: 22,
                background: 'rgba(255,255,255,0.12)',
                border: '1px solid rgba(255,255,255,0.25)',
                color: '#fff', cursor: 'pointer',
                width: 40, height: 40, borderRadius: 999,
                fontSize: 22, lineHeight: 1,
                display: 'flex', alignItems: 'center', justifyContent: 'center',
              }}>×</button>
            <img
              src={evt.poster}
              alt={`${evt.title} poster`}
              onClick={e => e.stopPropagation()}
              style={{
                maxWidth: 'min(640px, 92vw)',
                maxHeight: '90vh',
                width: 'auto', height: 'auto',
                borderRadius: 4,
                boxShadow: '0 30px 80px rgba(0,0,0,0.55), 0 8px 24px rgba(0,0,0,0.35)',
                cursor: 'auto',
                animation: 'fadeInUp 280ms var(--ease-standard) both',
              }}
            />
          </div>
        );
      })()}

      {/* Appearance request modal */}
      {apprOpen && (
        <div
          onClick={() => setApprOpen(false)}
          style={{
            position: 'fixed', inset: 0, zIndex: 220,
            background: 'rgba(10, 39, 84, 0.5)',
            backdropFilter: 'blur(4px)',
            display: 'flex', alignItems: 'center', justifyContent: 'center',
            padding: 20,
            animation: 'fadeInUp 200ms var(--ease-standard) both',
          }}>
          <div
            onClick={e => e.stopPropagation()}
            style={{
              background: '#fff', borderRadius: 4,
              width: '100%', maxWidth: 560,
              borderTop: '3px solid var(--color-gold-base)',
              animation: 'fadeInUp 280ms var(--ease-standard) both',
              maxHeight: '90vh', overflowY: 'auto',
              position: 'relative',
            }}>
            {/* Close X */}
            <button
              type="button"
              onClick={() => setApprOpen(false)}
              aria-label="Close"
              style={{
                position: 'absolute', top: 16, right: 16,
                background: 'none', border: '1px solid var(--divider)',
                color: 'var(--color-ink-soft)', cursor: 'pointer',
                width: 32, height: 32, borderRadius: 999,
                fontSize: 20, lineHeight: 1,
                display: 'flex', alignItems: 'center', justifyContent: 'center',
              }}>×</button>

            {apprDone ? (
              <div style={{ padding: 36 }}>
                <Eyebrow>Got it</Eyebrow>
                <h3 className="h2" style={{ margin: '8px 0 10px', fontSize: 26 }}>Request received.</h3>
                <p style={{ fontSize: 15, color: 'var(--color-ink-soft)', lineHeight: 1.55, margin: '0 0 22px' }}>
                  Evie or Matthew will get back to you within 2 business days about{' '}
                  <strong style={{ color: 'var(--color-ink)' }}>{apprForm.event_name || 'your event'}</strong>
                  {apprForm.proposed_date ? ` on ${apprForm.proposed_date}` : ''}.
                </p>
                <div style={{ display: 'flex', justifyContent: 'flex-end' }}>
                  <Button variant="primary" onClick={() => setApprOpen(false)}>Close</Button>
                </div>
              </div>
            ) : (
              <form onSubmit={submitAppearance} style={{ padding: 36 }}>
                <input
                  type="text" name="website" tabIndex={-1} autoComplete="off"
                  aria-hidden="true"
                  value={apprHoneypot}
                  onChange={e => setApprHoneypot(e.target.value)}
                  style={{ position: 'absolute', left: '-9999px', width: 1, height: 1, opacity: 0, pointerEvents: 'none' }}
                />

                <Eyebrow>Request an appearance</Eyebrow>
                <h3 className="h2" style={{ margin: '8px 0 24px', fontSize: 26, paddingRight: 32 }}>
                  Want Matthew at your event?
                </h3>

                {/* Section: Your contact */}
                <div style={{ fontSize: 11, fontWeight: 700, letterSpacing: '0.16em', textTransform: 'uppercase', color: 'var(--color-muted)', marginBottom: 12 }}>
                  Your contact
                </div>
                <div className="field" style={{ marginBottom: 14 }}>
                  <label>Full name <span style={{ color: 'var(--brand-accent)' }}>·required</span></label>
                  <input
                    value={apprForm.name}
                    onChange={e => setApprForm({ ...apprForm, name: e.target.value })}
                  />
                </div>
                <div className="field" style={{ marginBottom: 14 }}>
                  <label>Email <span style={{ color: 'var(--brand-accent)' }}>·required</span></label>
                  <input
                    type="email"
                    value={apprForm.email}
                    onChange={e => setApprForm({ ...apprForm, email: e.target.value })}
                  />
                </div>
                <div className="field" style={{ marginBottom: 24 }}>
                  <label>Phone <span style={{ color: 'var(--brand-accent)' }}>·required</span></label>
                  <input
                    type="tel"
                    value={apprForm.phone}
                    onChange={e => setApprForm({ ...apprForm, phone: formatPhone(e.target.value) })}
                  />
                </div>

                {/* Section: About the organization */}
                <div style={{ fontSize: 11, fontWeight: 700, letterSpacing: '0.16em', textTransform: 'uppercase', color: 'var(--color-muted)', marginBottom: 12 }}>
                  About the organization
                </div>
                <div className="field" style={{ marginBottom: 14 }}>
                  <label>Organization name <span style={{ color: 'var(--brand-accent)' }}>·required</span></label>
                  <input
                    value={apprForm.org_name}
                    onChange={e => setApprForm({ ...apprForm, org_name: e.target.value })}
                  />
                </div>
                <div className="field" style={{ marginBottom: 14 }}>
                  <label>Organization type</label>
                  <select
                    value={apprForm.org_type}
                    onChange={e => setApprForm({ ...apprForm, org_type: e.target.value })}>
                    <option value="">Select…</option>
                    {ORG_TYPES.map(t => <option key={t} value={t}>{t}</option>)}
                  </select>
                </div>
                <div className="field" style={{ marginBottom: 24 }}>
                  <label>Organization website</label>
                  <input
                    type="url"
                    placeholder="https://"
                    value={apprForm.org_url}
                    onChange={e => setApprForm({ ...apprForm, org_url: e.target.value })}
                  />
                </div>

                {/* Section: About the event */}
                <div style={{ fontSize: 11, fontWeight: 700, letterSpacing: '0.16em', textTransform: 'uppercase', color: 'var(--color-muted)', marginBottom: 12 }}>
                  About the event
                </div>
                <div className="field" style={{ marginBottom: 14 }}>
                  <label>Event name / occasion <span style={{ color: 'var(--brand-accent)' }}>·required</span></label>
                  <input
                    value={apprForm.event_name}
                    onChange={e => setApprForm({ ...apprForm, event_name: e.target.value })}
                  />
                </div>
                <div className="pair" style={{ marginBottom: 14 }}>
                  <div className="field">
                    <label>Proposed date <span style={{ color: 'var(--brand-accent)' }}>·required</span></label>
                    <input
                      type="date"
                      value={apprForm.proposed_date}
                      onChange={e => setApprForm({ ...apprForm, proposed_date: e.target.value })}
                    />
                  </div>
                  <div className="field">
                    <label>Alternate date</label>
                    <input
                      type="date"
                      value={apprForm.alt_date}
                      onChange={e => setApprForm({ ...apprForm, alt_date: e.target.value })}
                    />
                  </div>
                </div>
                <div className="pair" style={{ marginBottom: 14 }}>
                  <div className="field">
                    <label>Start time</label>
                    <input
                      type="text"
                      placeholder="e.g. 6:30 PM"
                      value={apprForm.start_time}
                      onChange={e => setApprForm({ ...apprForm, start_time: e.target.value })}
                    />
                  </div>
                  <div className="field">
                    <label>Duration</label>
                    <select
                      value={apprForm.duration}
                      onChange={e => setApprForm({ ...apprForm, duration: e.target.value })}>
                      <option value="">Select…</option>
                      {DURATIONS.map(d => <option key={d} value={d}>{d}</option>)}
                    </select>
                  </div>
                </div>
                <div className="pair" style={{ marginBottom: 24 }}>
                  <div className="field">
                    <label>Audience size</label>
                    <select
                      value={apprForm.audience_size}
                      onChange={e => setApprForm({ ...apprForm, audience_size: e.target.value })}>
                      <option value="">Select…</option>
                      {AUDIENCE_SIZES.map(s => <option key={s} value={s}>{s}</option>)}
                    </select>
                  </div>
                  <div className="field">
                    <label>Format</label>
                    <select
                      value={apprForm.format}
                      onChange={e => setApprForm({ ...apprForm, format: e.target.value })}>
                      <option value="">Select…</option>
                      {FORMATS.map(f => <option key={f} value={f}>{f}</option>)}
                    </select>
                  </div>
                </div>

                {/* Section: About the venue */}
                <div style={{ fontSize: 11, fontWeight: 700, letterSpacing: '0.16em', textTransform: 'uppercase', color: 'var(--color-muted)', marginBottom: 12 }}>
                  About the venue
                </div>
                <div className="field" style={{ marginBottom: 14 }}>
                  <label>Venue name</label>
                  <input
                    value={apprForm.venue_name}
                    onChange={e => setApprForm({ ...apprForm, venue_name: e.target.value })}
                  />
                </div>
                <div className="field" style={{ marginBottom: 14 }}>
                  <label>Street address</label>
                  <input
                    value={apprForm.street}
                    onChange={e => setApprForm({ ...apprForm, street: e.target.value })}
                  />
                </div>
                <div className="field" style={{ marginBottom: 14 }}>
                  <label>City</label>
                  <input
                    value={apprForm.city}
                    onChange={e => setApprForm({ ...apprForm, city: e.target.value })}
                  />
                </div>
                <div className="pair-donate-meta" style={{ marginBottom: 24 }}>
                  <div className="field">
                    <label>State</label>
                    <select
                      value={apprForm.state}
                      onChange={e => setApprForm({ ...apprForm, state: e.target.value })}>
                      {US_STATES.map(([code, name]) => (
                        <option key={code} value={code}>{name}</option>
                      ))}
                    </select>
                  </div>
                  <div className="field">
                    <label>ZIP</label>
                    <input
                      inputMode="numeric"
                      maxLength={5}
                      value={apprForm.zip}
                      onChange={e => setApprForm({ ...apprForm, zip: e.target.value.replace(/\D/g, '') })}
                    />
                  </div>
                </div>

                {/* Section: Anything else */}
                <div style={{ fontSize: 11, fontWeight: 700, letterSpacing: '0.16em', textTransform: 'uppercase', color: 'var(--color-muted)', marginBottom: 12 }}>
                  Anything else we should know
                </div>
                <div className="field" style={{ marginBottom: 14 }}>
                  <label>Will media be present?</label>
                  <div style={{ display: 'flex', gap: 20, marginTop: 6 }}>
                    {[['yes', 'Yes'], ['no', 'No'], ['unsure', 'Not sure']].map(([val, label]) => (
                      <label key={val} style={{ display: 'flex', alignItems: 'center', gap: 6, fontSize: 14, fontWeight: 400, cursor: 'pointer' }}>
                        <input
                          type="radio"
                          name="media_present"
                          value={val}
                          checked={apprForm.media_present === val}
                          onChange={() => setApprForm({ ...apprForm, media_present: val })}
                        />
                        {label}
                      </label>
                    ))}
                  </div>
                </div>
                <div className="field" style={{ marginBottom: 14 }}>
                  <label>Other candidates or officials attending?</label>
                  <input
                    value={apprForm.other_officials}
                    onChange={e => setApprForm({ ...apprForm, other_officials: e.target.value })}
                  />
                </div>
                <div className="field" style={{ marginBottom: 22 }}>
                  <label>Notes</label>
                  <textarea
                    rows={4}
                    value={apprForm.notes}
                    onChange={e => setApprForm({ ...apprForm, notes: e.target.value })}
                  />
                </div>

                {apprErr && <div style={{ fontSize: 13, color: 'var(--color-gold-900)', marginBottom: 14 }}>{apprErr}</div>}
                <div style={{ display: 'flex', gap: 10, justifyContent: 'flex-end' }}>
                  <Button variant="ghost" onClick={() => setApprOpen(false)}>Cancel</Button>
                  <Button variant="primary" type="submit" disabled={apprSubmitting}>
                    {apprSubmitting ? 'Submitting…' : 'Send request'}
                  </Button>
                </div>
              </form>
            )}
          </div>
        </div>
      )}

      {/* RSVP modal */}
      {modal && (
        <div
          onClick={closeRsvp}
          style={{
            position: 'fixed', inset: 0, zIndex: 200,
            background: 'rgba(10, 39, 84, 0.5)',
            backdropFilter: 'blur(4px)',
            display: 'flex', alignItems: 'center', justifyContent: 'center',
            padding: 20,
            animation: 'fadeInUp 200ms var(--ease-standard) both',
          }}>
          <form onClick={e => e.stopPropagation()} onSubmit={submit}
            style={{
              background: '#fff', borderRadius: 4, padding: 36,
              width: '100%', maxWidth: 480,
              borderTop: '3px solid var(--color-gold-base)',
              animation: 'fadeInUp 280ms var(--ease-standard) both',
            }}>
            <input
              type="text"
              name="website"
              tabIndex={-1}
              autoComplete="off"
              value={honeypotR}
              onChange={e => setHoneypotR(e.target.value)}
              aria-hidden="true"
              style={{
                position: 'absolute',
                left: '-9999px',
                width: 1,
                height: 1,
                opacity: 0,
                pointerEvents: 'none',
              }}
            />
            {(() => {
              const evt = EVENTS.find(e => e.id === modal);
              const d = dateFor(evt.date);
              return (
                <>
                  <Eyebrow>RSVP</Eyebrow>
                  <h3 className="h2" style={{ margin: '8px 0 6px', fontSize: 28 }}>{evt.title}</h3>
                  <div style={{ fontSize: 14, color: 'var(--color-ink-soft)', marginBottom: 24 }}>
                    {d.dow}, {d.month} {d.day} · {evt.time} · {evt.loc}
                  </div>
                  <div className="field" style={{ marginBottom: 14 }}>
                    <label>Full name</label>
                    <input value={form.name} onChange={e => setForm({ ...form, name: e.target.value })} />
                  </div>
                  <div className="field" style={{ marginBottom: 14 }}>
                    <label>Email</label>
                    <input type="email" value={form.email} onChange={e => setForm({ ...form, email: e.target.value })} />
                  </div>
                  <div className="field" style={{ marginBottom: 22 }}>
                    <label>How many in your party?</label>
                    <select value={form.guests} onChange={e => setForm({ ...form, guests: Number(e.target.value) })}>
                      {[1,2,3,4,5,6].map(n => <option key={n} value={n}>{n}</option>)}
                    </select>
                  </div>
                  {err && <div style={{ fontSize: 13, color: 'var(--color-gold-900)', marginBottom: 14 }}>{err}</div>}
                  <div style={{ display: 'flex', gap: 10, justifyContent: 'flex-end' }}>
                    <Button variant="quiet" onClick={closeRsvp}>Cancel</Button>
                    <Button variant="primary" type="submit">Confirm RSVP</Button>
                  </div>
                </>
              );
            })()}
          </form>
        </div>
      )}
    </section>
  );
};

Object.assign(window, { EventsScreen });
