// RSVP — minimalist single-focus form

const RSVP_STEPS = ['name', 'email', 'attending', 'guests', 'meals', 'songs', 'confirm'];

const EMAIL_RE = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;

const RSVPForm = () => {
  const [step, setStep] = React.useState(0);
  const [data, setData] = React.useState({
    name: '',
    email: '',
    attending: null,
    guests: 1,
    meals: { veg: false, allergies: '' },
    songs: '',
    submitted: false,
  });
  const [submitting, setSubmitting] = React.useState(false);
  const [submitError, setSubmitError] = React.useState(null);

  const update = (k, v) => setData(prev => ({ ...prev, [k]: v }));
  const next = () => setStep(s => Math.min(s + 1, RSVP_STEPS.length - 1));
  const back = () => setStep(s => Math.max(s - 1, 0));

  const submit = async () => {
    if (submitting) return;
    setSubmitting(true);
    setSubmitError(null);
    try {
      const res = await fetch('/api/rsvp', {
        method: 'POST',
        headers: { 'content-type': 'application/json' },
        body: JSON.stringify({
          name: data.name,
          email: data.email,
          attending: data.attending,
          guests: data.guests,
          veg: data.meals.veg,
          allergies: data.meals.allergies,
          song: data.songs,
        }),
      });
      const payload = await res.json().catch(() => ({}));
      if (!res.ok || !payload.ok) {
        throw new Error(payload.error || `Server returned ${res.status}`);
      }
      update('submitted', true);
      next();
    } catch (err) {
      setSubmitError(err.message || 'Could not reach the server. Please try again.');
    } finally {
      setSubmitting(false);
    }
  };

  const canProceed = () => {
    if (step === 0) return data.name.trim().length > 1;
    if (step === 1) return EMAIL_RE.test(data.email.trim());
    if (step === 2) return data.attending !== null;
    return true;
  };

  return (
    <section className="section rsvp-section" id="rsvp">
      <div className="section-head">
        <div>
          <div className="eyebrow" style={{ marginBottom: 12 }}>02 — RSVP</div>
          <h2 className="title">Will you be <em>there?</em></h2>
        </div>
        <div className="meta">
          Kindly reply<br/>by 15 June 2026
        </div>
      </div>

      <div className="rsvp-shell glass">
        <div className="rsvp-progress">
          {RSVP_STEPS.slice(0, -1).map((s, i) => (
            <div
              key={s}
              className={`rsvp-pip ${i <= step ? 'rsvp-pip-on' : ''}`}
              onClick={() => i < step && setStep(i)}
            />
          ))}
          <span className="rsvp-step-label mono">
            {step < RSVP_STEPS.length - 1 ? `Step ${step + 1} of ${RSVP_STEPS.length - 1}` : 'Confirmed'}
          </span>
        </div>

        <div className="rsvp-stage">
          {step === 0 && (
            <div className="rsvp-step">
              <span className="eyebrow">Your name</span>
              <h3 className="rsvp-q">As it appears on the invitation.</h3>
              <input
                className="field-input rsvp-input-large"
                value={data.name}
                onChange={e => update('name', e.target.value)}
                placeholder="Full name"
                autoFocus
              />
              <p className="rsvp-privacy mono">
                Your details are used only to plan the wedding — never shared, never sold, deleted after September 2026.
              </p>
            </div>
          )}

          {step === 1 && (
            <div className="rsvp-step">
              <span className="eyebrow">Your email</span>
              <h3 className="rsvp-q">Where should we send your confirmation?</h3>
              <input
                type="email"
                className="field-input rsvp-input-large"
                value={data.email}
                onChange={e => update('email', e.target.value)}
                placeholder="you@example.com"
                autoFocus
              />
              <p className="rsvp-hint">We'll send a copy of your reply along with the venue address.</p>
            </div>
          )}

          {step === 2 && (
            <div className="rsvp-step">
              <span className="eyebrow">Attendance</span>
              <h3 className="rsvp-q">Joyfully accepting?</h3>
              <div className="rsvp-choices">
                <button
                  className={`rsvp-choice ${data.attending === true ? 'on' : ''}`}
                  onClick={() => update('attending', true)}
                >
                  <span className="serif" style={{ fontSize: 32, fontStyle: 'italic' }}>Yes</span>
                  <span className="mono" style={{ fontSize: 10, letterSpacing: '0.18em' }}>WE'LL BE THERE</span>
                </button>
                <button
                  className={`rsvp-choice ${data.attending === false ? 'on' : ''}`}
                  onClick={() => update('attending', false)}
                >
                  <span className="serif" style={{ fontSize: 32, fontStyle: 'italic' }}>Regrets</span>
                  <span className="mono" style={{ fontSize: 10, letterSpacing: '0.18em' }}>WITH LOVE</span>
                </button>
              </div>
            </div>
          )}

          {step === 3 && (
            <div className="rsvp-step">
              <span className="eyebrow">Party size</span>
              <h3 className="rsvp-q">How many in your group?</h3>
              <div className="rsvp-stepper">
                <button onClick={() => update('guests', Math.max(1, data.guests - 1))}>−</button>
                <div className="stepper-num serif">{data.guests}</div>
                <button onClick={() => update('guests', Math.min(6, data.guests + 1))}>+</button>
              </div>
              <p className="rsvp-hint">Including yourself · max 6</p>
            </div>
          )}

          {step === 4 && (
            <div className="rsvp-step">
              <span className="eyebrow">Meals</span>
              <h3 className="rsvp-q">Anything we should know?</h3>
              <label className="rsvp-toggle">
                <input
                  type="checkbox"
                  checked={data.meals.veg}
                  onChange={e => update('meals', { ...data.meals, veg: e.target.checked })}
                />
                <span className="rsvp-toggle-track"><span className="rsvp-toggle-knob" /></span>
                <span>Vegetarian preferred</span>
              </label>
              <textarea
                className="field-input"
                rows="3"
                placeholder="Allergies or dietary notes (optional)"
                value={data.meals.allergies}
                onChange={e => update('meals', { ...data.meals, allergies: e.target.value })}
              />
            </div>
          )}

          {step === 5 && (
            <div className="rsvp-step">
              <span className="eyebrow">Soundtrack</span>
              <h3 className="rsvp-q">A song that will get you on the floor?</h3>
              <input
                className="field-input rsvp-input-large"
                placeholder="e.g. 'Stayin' Alive — Bee Gees'"
                value={data.songs}
                onChange={e => update('songs', e.target.value)}
              />
              <p className="rsvp-hint">You can add more in the Music Hub below.</p>
            </div>
          )}

          {step === 6 && (
            <div className="rsvp-step rsvp-confirm">
              <div className="confirm-mark">✓</div>
              <span className="eyebrow">Received</span>
              <h3 className="serif" style={{ fontSize: 56, fontStyle: 'italic', lineHeight: 1, color: 'var(--accent)' }}>
                Efharistó, {data.name.split(' ')[0]}.
              </h3>
              <p style={{ fontSize: 16, color: 'var(--ink-soft)', maxWidth: 420, textAlign: 'center', lineHeight: 1.6 }}>
                {data.attending
                  ? `We've reserved ${data.guests} ${data.guests === 1 ? 'seat' : 'seats'} at the long table on August 28th. A confirmation is on its way to ${data.email}.`
                  : `We'll miss you, but understand. A short note is on its way to ${data.email}.`}
              </p>
              <p className="mono" style={{ fontSize: 11, letterSpacing: '0.12em', color: 'var(--ink-mute)', maxWidth: 420, textAlign: 'center', lineHeight: 1.6, marginTop: 18 }}>
                Don't see it? Check your <strong>junk</strong> or <strong>spam</strong> folder — first messages from new senders sometimes land there.
              </p>
            </div>
          )}
        </div>

        {step < RSVP_STEPS.length - 1 && (
          <div className="rsvp-actions">
            <button className="btn btn-ghost" onClick={back} disabled={step === 0 || submitting}>
              {step === 0 ? '· · ·' : '← Back'}
            </button>
            <button
              className="btn"
              onClick={step === RSVP_STEPS.length - 2 ? submit : next}
              disabled={!canProceed() || submitting}
            >
              {step === RSVP_STEPS.length - 2
                ? (submitting ? 'Sending…' : 'Confirm Attendance')
                : 'Continue →'}
            </button>
          </div>
        )}

        {submitError && (
          <p className="rsvp-hint" style={{ color: '#b13b3b', marginTop: 12, textAlign: 'center' }}>
            {submitError}
          </p>
        )}
      </div>
    </section>
  );
};

window.RSVPForm = RSVPForm;
