/* 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 EVENTS = [
  {
    id: 'kickoff',
    date: { month: 'MAY', day: '07', dow: 'Thu' },
    time: '5:00 PM until',
    title: 'Campaign Kick Off',
    loc: 'The Float Pub & Grill',
    addr: '14511 Sherman Drive, Gig Harbor, WA 98332',
    blurb: 'Live music provided by Whiskey Beach. Raffle for Seahawks gear. Come meet Chuck, bring a neighbor, and help launch this campaign.',
    tag: 'Kick off',
    poster: 'assets/launch-poster.png',
  },
];

const EventCard = ({ evt, rsvp, onRsvp, onPoster }) => {
  const [hover, setHover] = useStateE(false);
  const joined = rsvp[evt.id];
  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)' }}>
          {evt.date.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',
        }}>{evt.date.day}</div>
        <div style={{ fontSize: 12, color: 'var(--color-muted)', letterSpacing: '0.08em', textTransform: 'uppercase', fontWeight: 600 }}>
          {evt.date.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: 36, 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 */}
      <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 openRsvp = (id) => { setModal(id); setErr(''); setForm({ name: '', email: '', guests: 1 }); setRsvpOpenedAt(Date.now()); };
  const closeRsvp = () => setModal(null);
  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: '20ch' }}>
              Meet Chuck across Pierce 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 }}>
          {EVENTS.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 Chuck at your event?
            </div>
            <div style={{ fontSize: 14, color: 'var(--color-ink-soft)', marginTop: 4, maxWidth: '54ch' }}>
              Book clubs, union halls, PTAs, neighborhood gatherings — Chuck will show up. 34 years of being the guy who shows up doesn&rsquo;t stop now.
            </div>
          </div>
          <Button variant="primary" onClick={() => onNavigate('donate')}>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>
        );
      })()}

      {/* 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);
              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 }}>
                    {evt.date.dow}, {evt.date.month} {evt.date.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 });
