// RSVPForm.jsx — guest confirmation

function RSVPForm({ onSubmit }) {
  const [form, setForm] = React.useState({
    name: '', attending: 'yes', phone: '', plusOne: '', wish: '',
  });
  const [submitted, setSubmitted] = React.useState(false);
  const [burst, setBurst] = React.useState(false);

  const update = k => e => setForm(f => ({ ...f, [k]: e.target.value }));

  const [loading, setLoading] = React.useState(false);
  const [error, setError] = React.useState(null);

  const handle = async (e) => {
    e.preventDefault();
    if (!form.name.trim()) return;
    setLoading(true);
    setError(null);
    try {
      if (window.LL) {
        await window.LL.addRSVP(form);
        if (form.wish && form.wish.trim()) {
          await window.LL.addWish({ name: form.name, text: form.wish });
        }
      }
      setBurst(true);
      setTimeout(() => setBurst(false), 2500);
      setSubmitted(true);
      onSubmit && onSubmit(form);
    } catch (err) {
      setError(err.message || 'Gửi thất bại, vui lòng thử lại.');
    } finally {
      setLoading(false);
    }
  };

  if (submitted) {
    return (
      <section id="rsvp" className="sec-gradient">
        <div className="container" style={{ maxWidth: 560, textAlign: 'center' }}>
          <img src="assets/icons/rings.svg" style={{ width: 100, margin: '0 auto 20px' }}/>
          <h2 style={{ fontFamily: 'var(--font-display-script)', fontSize: 72, color: 'var(--pink-700)', margin: 0, lineHeight: 1 }}>
            Cảm ơn {form.name}!
          </h2>
          <p style={{ fontSize: 17, color: 'var(--fg-2)', marginTop: 16, lineHeight: 1.7 }}>
            {form.attending === 'yes'
              ? `Hẹn gặp ${form.name} ngày 03/05 nha ♡ Lời chúc của bạn sẽ xuất hiện trong Guestbook ở dưới.`
              : `Tiếc là không có bạn, nhưng chúng mình vẫn cảm ơn lời chúc thật nhiều ♡`}
          </p>
          <button onClick={() => setSubmitted(false)} className="btn btn-secondary" style={{ marginTop: 28 }}>
            ← Chỉnh sửa phản hồi
          </button>
        </div>
      </section>
    );
  }

  return (
    <section id="rsvp" className="sec-gradient" style={{ position: 'relative' }}>
      {burst && <ConfettiBurst/>}
      <div className="container" style={{ maxWidth: 620 }}>
        <div className="sec-head reveal">
          <span className="eyebrow">RSVP · trước ngày 20/04</span>
          <h2>Xác nhận tham dự</h2>
          <div className="sub">để chúng mình chuẩn bị bàn cho bạn ♡</div>
        </div>

        <form onSubmit={handle} className="card reveal" data-rv="zoom" style={{ padding: '36px 32px', display: 'flex', flexDirection: 'column', gap: 20 }}>
          <div>
            <label className="field-label">Tên của bạn</label>
            <input className="input" placeholder="Nguyễn Thu Hà" value={form.name} onChange={update('name')} required/>
          </div>

          <div>
            <label className="field-label">Bạn sẽ đến chứ?</label>
            <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 10 }}>
              {[
                ['yes', '✓ Có, mình sẽ đến'],
                ['no', 'Tiếc là không'],
              ].map(([v, l]) => (
                <label key={v} style={{
                  padding: '14px', borderRadius: 'var(--r-md)',
                  border: '1.5px solid ' + (form.attending === v ? 'var(--pink-500)' : 'var(--border-rose)'),
                  background: form.attending === v ? 'var(--pink-500)' : 'var(--cream-50)',
                  color: form.attending === v ? 'var(--cream-50)' : 'var(--ink-700)',
                  fontFamily: 'var(--font-ui)', fontSize: 14, fontWeight: 600,
                  textAlign: 'center', cursor: 'pointer',
                  boxShadow: form.attending === v ? 'var(--shadow-md)' : 'none',
                  transition: 'all .2s',
                }}>
                  <input type="radio" name="att" value={v} checked={form.attending === v}
                    onChange={update('attending')} style={{ display: 'none' }}/>
                  {l}
                </label>
              ))}
            </div>
          </div>

          {form.attending === 'yes' && (
            <>
              <div>
                <label className="field-label">Số điện thoại</label>
                <input className="input" type="tel" placeholder="090 123 4567" value={form.phone} onChange={update('phone')}/>
              </div>
              <div>
                <label className="field-label">Tham dự cùng với... (nếu có)</label>
                <input className="input" placeholder="Tên người đi cùng" value={form.plusOne} onChange={update('plusOne')}/>
              </div>
            </>
          )}

          <div>
            <label className="field-label">♡ Gửi lời chúc tới chúng mình</label>
            <textarea className="input" placeholder="Chúc hai bạn trăm năm hạnh phúc..." value={form.wish} onChange={update('wish')}/>
          </div>

          {error && <div style={{ color: '#C94C71', fontSize: 14, textAlign: 'center' }}>{error}</div>}
          <button type="submit" className="btn btn-primary" disabled={loading} style={{ justifyContent: 'center', fontSize: 16, padding: '16px 32px' }}>
            {loading ? 'Đang gửi…' : 'Gửi xác nhận ♡'}
          </button>
        </form>
      </div>
    </section>
  );
}

function ConfettiBurst() {
  const pieces = React.useMemo(() => {
    const kinds = ['heart-solid', 'heart-outline', 'cherry-blossom', 'sparkle-pink', 'sparkle', 'daisy'];
    return Array.from({ length: 40 }, (_, i) => ({
      id: i,
      kind: kinds[i % kinds.length],
      dx: (Math.random() - 0.5) * 800,
      dy: -(200 + Math.random() * 400),
      rot: (Math.random() - 0.5) * 720,
      size: 20 + Math.random() * 28,
      dur: 1.5 + Math.random() * 1.2,
    }));
  }, []);

  return (
    <div style={{
      position: 'fixed', inset: 0, pointerEvents: 'none', zIndex: 100, overflow: 'hidden',
    }}>
      <style>{`
        @keyframes burst {
          0% { transform: translate(0,0) rotate(0); opacity: 1; }
          100% { transform: translate(var(--dx), var(--dy)) rotate(var(--rot)) translateY(100vh); opacity: 0; }
        }
      `}</style>
      {pieces.map(p => (
        <img key={p.id} src={`assets/icons/${p.kind}.svg`} style={{
          position: 'absolute', left: '50%', top: '60%',
          width: p.size, height: p.size,
          '--dx': `${p.dx}px`, '--dy': `${p.dy}px`, '--rot': `${p.rot}deg`,
          animation: `burst ${p.dur}s cubic-bezier(.2,.6,.4,1) forwards`,
        }}/>
      ))}
    </div>
  );
}

Object.assign(window, { RSVPForm, ConfettiBurst });
