// Multi-step RSVP card with validation
const { useState: rUseState } = React;

function RsvpCard({ onConfirm, compact = false }) {
  const [step, setStep] = rUseState(1);
  const [data, setData] = rUseState({
    name: '', email: '', firm: '',
    role: '', tier: '',
    dietary: '',
  });
  const [errors, setErrors] = rUseState({});
  const [submitting, setSubmitting] = rUseState(false);

  const update = (k, v) => setData((d) => ({ ...d, [k]: v }));

  const validateStep1 = () => {
    const e = {};
    if (!data.name.trim()) e.name = 'Required';
    if (!data.email.trim()) e.email = 'Required';
    else if (!/^\S+@\S+\.\S+$/.test(data.email)) e.email = 'Invalid email';
    setErrors(e);
    return Object.keys(e).length === 0;
  };

  const validateStep2 = () => {
    const e = {};
    if (!data.role) e.role = 'Pick one';
    if (!data.tier) e.tier = 'Pick one';
    setErrors(e);
    return Object.keys(e).length === 0;
  };

  const next = () => {
    if (step === 1 && !validateStep1()) return;
    if (step === 2 && !validateStep2()) return;
    setStep((s) => Math.min(3, s + 1));
  };

  const submit = async () => {
    setSubmitting(true);
    await new Promise((r) => setTimeout(r, 900));
    setSubmitting(false);
    onConfirm({ ...data, ts: new Date().toISOString() });
  };

  const totalSteps = 3;
  const pct = (step / totalSteps) * 100;

  const onSubmitForm = (e) => {
    e.preventDefault();
    if (step < 3) next();
    else submit();
  };

  return (
    <div className="rsvp-card">
      <div className="rsvp-card-head">
        <div>
          <div className="rsvp-card-eyebrow">Confirm Attendance</div>
          <h3 className="rsvp-card-title">Reserve your seat</h3>
        </div>
      </div>

      <div className="rsvp-progress">
        <span>Step {step} / {totalSteps}</span>
        <div className="rsvp-progress-track">
          <div className="rsvp-progress-fill" style={{ width: `${pct}%` }}></div>
        </div>
      </div>

      {step === 1 && (
        <form onSubmit={onSubmitForm} noValidate>
          <div className={`field ${errors.name ? 'error' : ''}`}>
            <label htmlFor="rsvp-name">Full name</label>
            <input id="rsvp-name" name="name" type="text" autoComplete="name"
              value={data.name} onChange={(e) => update('name', e.target.value)} placeholder="Full name" />
            {errors.name && <div className="field-error">{errors.name}</div>}
          </div>
          <div className={`field ${errors.email ? 'error' : ''}`}>
            <label htmlFor="rsvp-email">Email</label>
            <input id="rsvp-email" name="email" type="email" autoComplete="email" inputMode="email"
              value={data.email} onChange={(e) => update('email', e.target.value)} placeholder="you@firm.com" />
            {errors.email && <div className="field-error">{errors.email}</div>}
          </div>
          <div className="field">
            <label htmlFor="rsvp-firm">Firm or company</label>
            <input id="rsvp-firm" name="firm" type="text" autoComplete="organization"
              value={data.firm} onChange={(e) => update('firm', e.target.value)} placeholder="Optional" />
          </div>
          <button type="submit" className="btn">
            Continue <span className="arrow">→</span>
          </button>
        </form>
      )}

      {step === 2 && (
        <form onSubmit={onSubmitForm} noValidate>
          <div className={`field ${errors.role ? 'error' : ''}`}>
            <label>I am attending as</label>
            <div className="choice-grid">
              {[
                { v: 'owner', t: 'Business Owner' },
                { v: 'client', t: 'Existing Client' },
                { v: 'partner', t: 'Professional Partner' },
              ].map((o) => (
                <button key={o.v} type="button" className="choice"
                  aria-pressed={data.role === o.v}
                  onClick={() => update('role', o.v)}>
                  {o.t}
                </button>
              ))}
            </div>
            {errors.role && <div className="field-error">{errors.role}</div>}
          </div>
          <div className={`field ${errors.tier ? 'error' : ''}`} style={{ marginTop: 18 }}>
            <label>Joining for</label>
            <div className="choice-grid">
              {[
                { v: 'full', t: 'Full Day', tag: 'Summit + Golf + Reception' },
                { v: 'summit', t: 'Summit Only', tag: 'AM Sessions' },
                { v: 'golf', t: 'Golf + Reception', tag: 'PM Only' },
              ].map((o) => (
                <button key={o.v} type="button" className="choice"
                  aria-pressed={data.tier === o.v}
                  onClick={() => update('tier', o.v)}>
                  <span className="mono-tag">{o.tag}</span>
                  {o.t}
                </button>
              ))}
            </div>
            {errors.tier && <div className="field-error">{errors.tier}</div>}
          </div>
          <div className="btn-row" style={{ marginTop: 22 }}>
            <button type="button" className="btn btn-ghost" onClick={() => setStep(1)} style={{ flex: '0 0 auto', padding: '14px 18px' }}>← Back</button>
            <button type="submit" className="btn" style={{ flex: 1 }}>
              Continue <span className="arrow">→</span>
            </button>
          </div>
        </form>
      )}

      {step === 3 && (
        <form onSubmit={onSubmitForm} noValidate>
          <div className="field">
            <label htmlFor="rsvp-dietary">Dietary or accessibility notes</label>
            <input id="rsvp-dietary" name="dietary" type="text"
              value={data.dietary} onChange={(e) => update('dietary', e.target.value)} placeholder="Optional" />
          </div>
          <div style={{ fontSize: 12, color: 'var(--forest-500)', fontFamily: 'var(--mono)', letterSpacing: '0.08em', marginTop: 14, marginBottom: 18, lineHeight: 1.6 }}>
            By confirming, you agree to our event terms. We will follow up via email with venue details and your personal calendar invite.
          </div>
          <div className="btn-row">
            <button type="button" className="btn btn-ghost" onClick={() => setStep(2)} style={{ flex: '0 0 auto', padding: '14px 18px' }}>← Back</button>
            <button type="submit" className="btn" disabled={submitting} style={{ flex: 1 }}>
              {submitting ? 'Confirming…' : 'Confirm RSVP'} {!submitting && <span className="arrow">→</span>}
            </button>
          </div>
        </form>
      )}
    </div>
  );
}

Object.assign(window, { RsvpCard });
