/* Events: EventCard, RSVP modal, and the Events page. Exports window.EventCard, window.RSVPModal, window.Pages.events */
const evDS = window.WKYHBHutchinsonBellDesignSystem_7985db || {};

function EventCard({ e, onRSVP, compact }) {
  const { Badge, Button } = evDS; const U = window.U; const data = window.WKYHB;
  return (
    <article style={{ display: 'flex', flexDirection: 'column', background: 'var(--surface)', borderRadius: 'var(--radius-lg)', border: '1px solid var(--border)', boxShadow: 'var(--shadow-md)', overflow: 'hidden' }}>
      <div style={{ height: 140, background: 'linear-gradient(135deg, #9E1B2F, #C4122E)', position: 'relative', display: 'flex', alignItems: 'flex-end', padding: 14 }}>
        <div style={{ position: 'absolute', inset: 0, backgroundImage: `url(${U.texSrc})`, backgroundSize: 'cover', backgroundPosition: 'center', opacity: 0.22, mixBlendMode: 'overlay' }} />
        <div style={{ position: 'absolute', top: 14, left: 14, background: '#fff', borderRadius: 'var(--radius-md)', padding: '6px 12px', textAlign: 'center', boxShadow: 'var(--shadow-sm)' }}>
          <span style={{ display: 'block', fontFamily: 'var(--font-condensed)', fontSize: 11, fontWeight: 600, letterSpacing: '0.1em', color: 'var(--bell-crimson)', textTransform: 'uppercase' }}>{e.mon}</span>
          <span style={{ display: 'block', fontFamily: 'var(--font-display)', fontSize: 22, fontWeight: 800, color: 'var(--ink)', lineHeight: 1 }}>{e.day}</span>
        </div>
        <div style={{ position: 'relative', display: 'flex', gap: 6 }}>
          <Badge variant="solid" style={{ background: '#fff', color: 'var(--bell-crimson)' }}>{e.category}</Badge>
          {e.ticketed && <Badge variant="solid" style={{ background: 'var(--ink)', color: '#fff' }}>Ticketed</Badge>}
        </div>
      </div>
      <div style={{ padding: 'var(--space-5)', display: 'flex', flexDirection: 'column', gap: 7, flex: 1 }}>
        <h3 style={{ fontFamily: 'var(--font-display)', fontWeight: 800, fontSize: 'var(--text-lg)', color: 'var(--text-strong)', margin: 0, letterSpacing: '-0.01em' }}>{e.title}</h3>
        <span style={{ fontFamily: 'var(--font-body)', fontSize: 13.5, color: 'var(--text-muted)' }}>{e.weekday}, {e.mon} {parseInt(e.day, 10)} · {e.time} · {e.location}</span>
        <p style={{ fontFamily: 'var(--font-body)', fontSize: 14.5, lineHeight: 1.55, color: 'var(--text-body)', margin: '2px 0 12px', flex: 1 }}>{e.blurb}</p>
        {e.ticketed
          ? <Button size="sm" onClick={() => window.open(data.links.donate, '_blank')} style={{ whiteSpace: 'nowrap' }} iconRight={<U.IconExternal />}>{`Get tickets · $${e.price}`}</Button>
          : <Button size="sm" onClick={() => onRSVP && onRSVP(e)}>RSVP</Button>}
      </div>
    </article>
  );
}

function RSVPModal({ event, open, onClose }) {
  const { Button, Input } = evDS; const U = window.U;
  const [done, setDone] = React.useState(false);
  const [form, setForm] = React.useState({ name: '', email: '', guests: '1' });
  React.useEffect(() => { if (open) { setDone(false); setForm({ name: '', email: '', guests: '1' }); } }, [open, event]);
  if (!event) return null;
  const submit = (ev) => {
    ev.preventDefault();
    const data = window.WKYHB;
    const subject = `RSVP: ${event.title} (${event.mon} ${parseInt(event.day, 10)}, ${event.year})`;
    const body = `Hi WKYHB,\n\nI'd like to RSVP for ${event.title}.\n\nName: ${form.name}\nEmail: ${form.email}\nNumber attending: ${form.guests}\n\nThank you!`;
    window.location.href = U.mailto(data.org.email, subject, body);
    setDone(true);
  };

  return (
    <U.Modal open={open} onClose={onClose}>
      {done ? (
        <U.SuccessPanel title="Almost there — send your RSVP" onReset={onClose} resetLabel="Close">
          Your email app should have opened with your RSVP for <strong>{event.title}</strong> ready to send to {window.WKYHB.org.email}. Just hit send and we'll save your spot. (Didn't open? Email us directly at {window.WKYHB.org.email}.)
        </U.SuccessPanel>
      ) : (
        <form onSubmit={submit} style={{ display: 'flex', flexDirection: 'column', gap: 16 }}>
          <div>
            <U.Eyebrow>RSVP · {event.mon} {parseInt(event.day, 10)}, {event.year}</U.Eyebrow>
            <h3 style={{ fontFamily: 'var(--font-display)', fontWeight: 800, fontSize: 'var(--text-xl)', color: 'var(--text-strong)', margin: '8px 0 4px', letterSpacing: '-0.02em' }}>{event.title}</h3>
            <p style={{ fontFamily: 'var(--font-body)', fontSize: 14, color: 'var(--text-muted)', margin: 0 }}>{event.weekday}, {event.time} · {event.location}</p>
          </div>
          <Input label="Full name" required value={form.name} onChange={(e) => setForm({ ...form, name: e.target.value })} placeholder="Your name" />
          <Input label="Email" type="email" required value={form.email} onChange={(e) => setForm({ ...form, email: e.target.value })} placeholder="you@email.com" />
          <U.Select label="Number attending" value={form.guests} onChange={(e) => setForm({ ...form, guests: e.target.value })}>
            {['1', '2', '3', '4', '5', '6+'].map((n) => <option key={n} value={n}>{n}</option>)}
          </U.Select>
          <div style={{ display: 'flex', gap: 12, marginTop: 4 }}>
            <Button type="submit" fullWidth>Send RSVP</Button>
            <Button type="button" variant="ghost" onClick={onClose}>Cancel</Button>
          </div>
        </form>
      )}
    </U.Modal>
  );
}

function EventsPage({ onRSVP }) {
  const U = window.U; const data = window.WKYHB;
  const hasEvents = data.events.length > 0;
  const cats = ['All', ...Array.from(new Set(data.events.map((e) => e.category)))];
  const [cat, setCat] = React.useState('All');
  const [q, setQ] = React.useState('');
  const filtered = data.events.filter((e) =>
    (cat === 'All' || e.category === cat) &&
    (q.trim() === '' || (e.title + ' ' + e.location + ' ' + e.blurb).toLowerCase().includes(q.toLowerCase())));

  const chip = (active) => ({ fontFamily: 'var(--font-condensed)', textTransform: 'uppercase', letterSpacing: '0.08em', fontSize: 13, fontWeight: 600, padding: '8px 18px', borderRadius: 'var(--radius-pill)', cursor: 'pointer', border: `1.5px solid ${active ? 'var(--bell-crimson)' : 'var(--border-strong)'}`, background: active ? 'var(--bell-crimson)' : 'transparent', color: active ? '#fff' : 'var(--text-body)', transition: 'all var(--dur-fast)' });

  return (
    <React.Fragment>
      <U.PageHeader eyebrow="What's Happening" title="Chapter events &amp; gatherings" lead="Fellowship dinners, service days, and socials across Western Kentucky. RSVP for free events, or grab tickets for our fundraisers." />
      <U.Section bg="surface">
        <U.Container>
          {hasEvents && (
            <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: 18, flexWrap: 'wrap', marginBottom: 'var(--space-6)' }}>
              <div style={{ display: 'flex', gap: 10, flexWrap: 'wrap' }}>
                {cats.map((c) => <button key={c} style={chip(cat === c)} onClick={() => setCat(c)}>{c}</button>)}
              </div>
              <div style={{ position: 'relative', minWidth: 240 }}>
                <input value={q} onChange={(e) => setQ(e.target.value)} placeholder="Search events…"
                  style={{ fontFamily: 'var(--font-body)', fontSize: 15, padding: '11px 16px 11px 38px', borderRadius: 'var(--radius-pill)', border: '1.5px solid var(--border-strong)', outline: 'none', width: '100%', boxSizing: 'border-box' }}
                  onFocus={(e) => { e.currentTarget.style.borderColor = 'var(--bell-crimson)'; e.currentTarget.style.boxShadow = '0 0 0 3px var(--focus-ring)'; }}
                  onBlur={(e) => { e.currentTarget.style.borderColor = 'var(--border-strong)'; e.currentTarget.style.boxShadow = 'none'; }} />
                <span style={{ position: 'absolute', left: 15, top: '50%', transform: 'translateY(-50%)', color: 'var(--text-muted)', fontSize: 15 }}>⌕</span>
              </div>
            </div>
          )}

          {!hasEvents ? (
            <div style={{ textAlign: 'center', padding: '40px 0 8px', display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 12 }}>
              <h2 style={{ fontFamily: 'var(--font-display)', fontWeight: 800, fontSize: 'var(--text-2xl)', color: 'var(--text-strong)', margin: 0, letterSpacing: '-0.025em' }}>No events scheduled right now</h2>
              <p style={{ fontFamily: 'var(--font-serif)', fontSize: 'var(--text-md)', lineHeight: 1.6, color: 'var(--text-muted)', margin: 0, maxWidth: 560 }}>We don't have anything on the calendar at the moment — but we're always planning what's next. Subscribe to the chapter newsletter or follow us on social media and you'll be the first to know when the next gathering is announced.</p>
            </div>
          ) : filtered.length > 0 ? (
            <div className="wk-grid-3" style={{ display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: 'var(--space-5)' }}>
              {filtered.map((e) => <EventCard key={e.id} e={e} onRSVP={onRSVP} />)}
            </div>
          ) : (
            <p style={{ fontFamily: 'var(--font-serif)', fontSize: 18, color: 'var(--text-muted)', textAlign: 'center', padding: '48px 0' }}>No events match your search. Try clearing the filters.</p>
          )}

          <div style={{ marginTop: 'var(--space-8)', background: 'var(--surface-paper)', borderRadius: 'var(--radius-lg)', border: '1px solid var(--border)', padding: 'var(--space-7)', textAlign: 'center', display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 12 }}>
            <U.Eyebrow>Stay in the loop</U.Eyebrow>
            <h3 style={{ fontFamily: 'var(--font-display)', fontWeight: 800, fontSize: 'var(--text-xl)', color: 'var(--text-strong)', margin: 0, letterSpacing: '-0.02em' }}>Never miss a gathering</h3>
            <p style={{ fontFamily: 'var(--font-body)', fontSize: 'var(--text-base)', lineHeight: 1.6, color: 'var(--text-body)', margin: 0, maxWidth: 520 }}>Follow us on social media or subscribe to the chapter newsletter for new dates, details, and reminders.</p>
            <div style={{ display: 'flex', gap: 12, flexWrap: 'wrap', justifyContent: 'center', marginTop: 4 }}>
              {evDS.Button && <evDS.Button variant="outline" size="sm" onClick={() => U.goTo('involved')}>Get the newsletter</evDS.Button>}
              {evDS.Button && <evDS.Button variant="ghost" size="sm" onClick={() => window.open(data.links.instagram, '_blank')} iconLeft={<U.IconInstagram size={15} />} iconRight={<U.IconExternal />}>Follow on Instagram</evDS.Button>}
            </div>
          </div>
        </U.Container>
      </U.Section>
    </React.Fragment>
  );
}

window.EventCard = EventCard;
window.RSVPModal = RSVPModal;
window.Pages = window.Pages || {};
window.Pages.events = EventsPage;
