/* engage.jsx — RSVP + Guestbook */
const { useState: useStateEng, useEffect: useEffectEng } = React;

function Rsvp() {
  const [form, setForm] = useStateEng({ name: '', status: '', guests: '1', note: '' });
  const [done, setDone] = useStateEng(false);
  const [count, setCount] = useStateEng(0);
  const set = (k) => (e) => setForm({ ...form, [k]: e.target.value });

  const loadCount = async () => {
    const all = await R50.getRsvps();
    setCount(all.filter((r) => r.status === 'yes').reduce((n, r) => n + (parseInt(r.guests, 10) || 1), 0));
  };
  useEffectEng(() => { loadCount(); }, []);

  const submit = async (e) => {
    if (!form.name.trim() || !form.status) return;
    await R50.addRsvp(form);
    await loadCount();
    setDone(true);
    if (form.status === 'yes' && window.R50FX) {
      const r = e && e.currentTarget ? e.currentTarget.getBoundingClientRect() : null;
      window.R50FX.confetti(r ? { x: r.left + r.width / 2, y: r.top } : {});
    }
  };

  return (
    <section className="cream section-pad" id="rsvp">
      <div className="wrap">
        <Reveal className="section-head center">
          <span className="kicker">Kindly Reply by June 14<sup>th</sup></span>
          <h2>Will you <em>join us?</em></h2>
          {count > 0 && <p className="lead" style={{ fontSize: '20px' }}>{count} {count === 1 ? 'guest is' : 'guests are'} already celebrating 🥂</p>}
        </Reveal>

        <Reveal className="panel">
          {done ? (
            <div className="confirm">
              <div className="big script">
                {form.status === 'yes' ? "We can't wait to see you!" : "We'll miss you dearly."}
              </div>
              <p className="lead">
                {form.status === 'yes'
                  ? <span>Thank you, {form.name.split(' ')[0]}. Your reply is in — see you on <span style={{whiteSpace:'nowrap'}}>July 11th.</span></span>
                  : `Thank you for letting us know, ${form.name.split(' ')[0]}. You'll be with us in spirit.`}
              </p>
              <button className="btn btn-ghost" style={{ marginTop: 26 }} onClick={() => { setDone(false); setForm({ name: '', status: '', guests: '1', note: '' }); }}>Send another reply</button>
            </div>
          ) : (
            <>
              <div className="field">
                <label>Your name</label>
                <input value={form.name} onChange={set('name')} placeholder="First & last name" />
              </div>
              <div className="field">
                <label>Will you attend?</label>
                <div className="choice-row">
                  <button className={`choice ${form.status === 'yes' ? 'on' : ''}`} onClick={() => setForm({ ...form, status: 'yes' })}>Joyfully accepts</button>
                  <button className={`choice ${form.status === 'no' ? 'on' : ''}`} onClick={() => setForm({ ...form, status: 'no' })}>Regretfully declines</button>
                </div>
              </div>
              {form.status === 'yes' && (
                <div className="field" style={{ animation: 'popIn .4s both' }}>
                  <label>How many in your party?</label>
                  <select value={form.guests} onChange={set('guests')}>
                    {['1', '2', '3', '4', '5', '6+'].map((n) => <option key={n} value={n}>{n}</option>)}
                  </select>
                </div>
              )}
              <div className="field">
                <label>A note for Rajshree <span style={{ textTransform: 'none', letterSpacing: 0, color: 'var(--ink-soft)' }}>(optional)</span></label>
                <textarea value={form.note} onChange={set('note')} placeholder="A birthday wish, dietary note, or hello…" />
              </div>
              <div className="center">
                <button className="btn" disabled={!form.name.trim() || !form.status} onClick={submit}>Send my reply</button>
              </div>
            </>
          )}
        </Reveal>
      </div>
    </section>
  );
}

function Guestbook() {
  const [form, setForm] = useStateEng({ name: '', message: '' });
  const [msgs, setMsgs] = useStateEng([]);
  const load = async () => setMsgs(await R50.getMessages());
  useEffectEng(() => { load(); }, []);

  const submit = async (e) => {
    if (!form.message.trim()) return;
    await R50.addMessage({ name: form.name.trim() || 'A friend', message: form.message.trim() });
    setForm({ name: '', message: '' });
    await load();
    if (window.R50FX) {
      const r = e && e.currentTarget ? e.currentTarget.getBoundingClientRect() : null;
      window.R50FX.confetti(r ? { x: r.left + r.width / 2, y: r.top, count: 30 } : { count: 30 });
    }
    window.R50UI && window.R50UI.toast('Your message has been added 💛');
  };

  return (
    <section className="dark section-pad" id="guestbook">
      <div className="wrap">
        <Reveal className="section-head center">
          <span className="kicker">Guestbook</span>
          <h2 style={{ color: 'var(--paper)' }}>Leave her a <em>message</em></h2>
          <p className="lead" style={{ color: '#cdbfa6' }}>A wish, a memory, a thank you — she'll read every one.</p>
        </Reveal>

        <Reveal className="panel" style={{ marginBottom: 64 }}>
          <div className="field">
            <label>Your name</label>
            <input value={form.name} onChange={(e) => setForm({ ...form, name: e.target.value })} placeholder="Your name" />
          </div>
          <div className="field">
            <label>Your message</label>
            <textarea value={form.message} onChange={(e) => setForm({ ...form, message: e.target.value })} placeholder="Happy 50th, Rajshree…" />
          </div>
          <div className="center">
            <button className="btn" disabled={!form.message.trim()} onClick={submit}>Add to the guestbook</button>
          </div>
        </Reveal>

        {msgs.length === 0 ? (
          <Reveal className="empty-note">Be the first to leave Rajshree a birthday message.</Reveal>
        ) : (
          <div className="gb-grid">
            {msgs.map((m) => (
              <div className="gb-card" key={m.id}>
                <div className="msg">“{m.message}”</div>
                <div className="who">— {m.name}</div>
              </div>
            ))}
          </div>
        )}
      </div>
    </section>
  );
}

Object.assign(window, { Rsvp, Guestbook });
