// RegistrationForm.jsx — interactive registration form with sponsorship tiers
const { useState, useEffect } = React;

const GIVELIVELY_URL = 'https://secure.givelively.org/event/neighbors-for-better-neighborhoods/neighborhoods-in-action-breakfast-for-better-neighborhoods';
window.GIVELIVELY_URL = GIVELIVELY_URL;

const TIERS = {
  ticket:    { label: 'Individual Ticket',   price: 35,   desc: 'One seat at the block' },
  supporter: { label: 'Community Supporter', price: 100,  desc: 'Includes 2 tickets' },
  partner:   { label: 'Neighborhood Partner',price: 200,  desc: 'Includes 4 tickets' },
  builder:   { label: 'Community Builder',   price: 300,  desc: 'Includes 6 tickets' },
  health:    { label: 'Health Equity Champion', price: 500, desc: 'Includes 8 + VIP Reception' },
  organizer: { label: "Organizer's Circle",  price: 750,  desc: 'Includes 10 + VIP Reception' },
  visionary: { label: 'Community Visionary', price: 1000, desc: 'Includes 12 + VIP Reception' },
};
const VIP_KEYS = ['health', 'organizer', 'visionary'];

function RegistrationForm({ stats, setStats }) {
  const [tier, setTier] = useState('ticket');
  const [form, setForm] = useState({
    firstName: '', lastName: '', email: '', phone: '',
    org: '', zip: '',
    designation: 'greatest',
    hearAbout: '',
    giftcard: true,
    updates: true,
  });
  const [errors, setErrors] = useState({});
  const [submitted, setSubmitted] = useState(false);

  const tierData = TIERS[tier];
  const isSponsor = tier !== 'ticket';
  const isVIP = VIP_KEYS.includes(tier);
  const total = tierData.price;

  function validate() {
    const e = {};
    if (!form.firstName.trim()) e.firstName = 'Required';
    if (!form.lastName.trim()) e.lastName = 'Required';
    if (!form.email.trim()) e.email = 'Required';
    else if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(form.email)) e.email = 'Enter a valid email';
    if (!form.zip.trim()) e.zip = 'Required';
    if (isSponsor && !form.org.trim()) e.org = 'Please enter your organization or name as you\'d like to be recognized';
    setErrors(e);
    return Object.keys(e).length === 0;
  }

  function handleSubmit(ev) {
    ev.preventDefault();
    if (!validate()) return;
    window.open(GIVELIVELY_URL, '_blank', 'noopener,noreferrer');
    setStats({
      ...stats,
      raised: stats.raised + total,
      seatsFilled: stats.seatsFilled + (isSponsor ? (tier === 'supporter' ? 2 : tier === 'partner' ? 4 : tier === 'builder' ? 6 : tier === 'health' ? 8 : tier === 'organizer' ? 10 : 12) : 1),
      donors: stats.donors + 1,
      giftsClaimed: Math.min(100, stats.giftsClaimed + (form.giftcard ? 1 : 0)),
    });
    setSubmitted(true);
  }

  const giftEligible = (stats.giftsClaimed + 1) <= 100 && form.giftcard;

  if (submitted) {
    const confirmId = 'NIA-' + Math.floor(100000 + Math.random() * 899999);
    return (
      <div className="form-card">
        <div className="form-success">
          <div className="success-icon">
            <svg width="32" height="32" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round">
              <path d="M20 6 9 17l-5-5" />
            </svg>
          </div>
          <h3>Finish on GiveLively to lock in your seat.</h3>
          <p>We opened <strong style={{ color: 'var(--navy-deep)' }}>GiveLively</strong> in a new tab to complete your <strong style={{ color: 'var(--navy-deep)' }}>${total}</strong> gift. After your gift posts, you&rsquo;ll be sent to a thank&#8209;you page that hands you straight to your Zoom join link &mdash; the receipt also goes to <strong style={{ color: 'var(--navy-deep)' }}>{form.email}</strong>.</p>
          <div className="confirm-detail">
            <dl>
              <dt>Confirmation</dt><dd style={{ fontFamily: 'var(--font-mono)' }}>{confirmId}</dd>
              <dt>Name</dt><dd>{form.firstName} {form.lastName}</dd>
              <dt>Level</dt><dd>{tierData.label} — ${total}</dd>
              <dt>Designated to</dt><dd>{DESIGNATIONS[form.designation]}</dd>
              <dt>Main Event</dt><dd>Wed, Jun 24, 2026 · 8:30 AM ET · Zoom</dd>
              {isVIP && <><dt>VIP Reception</dt><dd>8:00 AM ET · Same Zoom link</dd></>}
            </dl>
          </div>
          {giftEligible && (
            <div className="gift-award">
              <div className="ico"><Icon.Gift size={24} /></div>
              <div className="txt">
                <strong>Breakfast's on us.</strong>
                You're in the first 100! Your $10 Chick‑fil‑A gift card will arrive by email within 48 hours of the event.
              </div>
            </div>
          )}
          {isVIP && (
            <div className="gift-award" style={{ background: 'linear-gradient(135deg, var(--teal-light), #D4E9E6)', borderColor: 'var(--teal)' }}>
              <div className="ico"><Icon.Sparkle size={20} /></div>
              <div className="txt">
                <strong>VIP Reception access unlocked.</strong>
                Join Dr. Lewis and NBN leadership in a small‑group Zoom at 8:00 AM ET — details in your confirmation.
              </div>
            </div>
          )}
          <div className="zoom-cta-row" style={{ marginTop: 18, padding: '14px 16px', background: 'var(--cream)', border: '1px solid var(--gold-light)', borderRadius: 10, display: 'flex', gap: 12, alignItems: 'center', justifyContent: 'space-between', flexWrap: 'wrap' }}>
            <div style={{ fontSize: 13, color: 'var(--navy-deep)' }}>
              Didn&rsquo;t see the GiveLively tab open? Re&#8209;open it here.
            </div>
            <a className="btn btn-primary" href={GIVELIVELY_URL} target="_blank" rel="noopener">Open GiveLively <Icon.ArrowRight size={14} /></a>
          </div>
          <div style={{ marginTop: 18, display: 'flex', gap: 10, justifyContent: 'center', flexWrap: 'wrap' }}>
            <button className="btn btn-secondary" onClick={() => { setSubmitted(false); setForm({ ...form, firstName: '', lastName: '', email: '', org: '' }); }}>
              Register another
            </button>
            <a className="btn btn-gold" href="#impact">See your impact <Icon.ArrowRight size={16}/></a>
          </div>
        </div>
      </div>
    );
  }

  return (
    <form className="form-card" onSubmit={handleSubmit} noValidate>
      <div className="form-head">
        <h3>Reserve your seat</h3>
        <p>Secure checkout · 100% of proceeds support NBN's community work</p>
      </div>

      {/* Level picker */}
      <div className="field">
        <label>Choose your level</label>
        <div className="tier-list">
          {Object.entries(TIERS).map(([key, t]) => (
            <button
              type="button"
              key={key}
              className={'tier-row' + (tier === key ? ' active' : '')}
              onClick={() => setTier(key)}
            >
              <div className="tier-row-main">
                <div className="tier-row-label">
                  {t.label}
                  {VIP_KEYS.includes(key) && <span className="vip-chip">VIP</span>}
                </div>
                <div className="tier-row-desc">{t.desc}</div>
              </div>
              <div className="tier-row-price">${t.price}</div>
            </button>
          ))}
        </div>
      </div>

      <div className="field-row">
        <div className={'field' + (errors.firstName ? ' error' : '')}>
          <label>First name <span className="req">*</span></label>
          <input value={form.firstName} onChange={(e) => setForm({ ...form, firstName: e.target.value })} autoComplete="given-name" />
          {errors.firstName && <div className="err-msg">{errors.firstName}</div>}
        </div>
        <div className={'field' + (errors.lastName ? ' error' : '')}>
          <label>Last name <span className="req">*</span></label>
          <input value={form.lastName} onChange={(e) => setForm({ ...form, lastName: e.target.value })} autoComplete="family-name" />
          {errors.lastName && <div className="err-msg">{errors.lastName}</div>}
        </div>
      </div>

      <div className={'field' + (errors.email ? ' error' : '')}>
        <label>Email <span className="req">*</span></label>
        <input type="email" value={form.email} onChange={(e) => setForm({ ...form, email: e.target.value })} placeholder="you@example.com" autoComplete="email" />
        <div className="field-hint">Zoom link, receipt, and gift card (if eligible) arrive here.</div>
        {errors.email && <div className="err-msg">{errors.email}</div>}
      </div>

      <div className="field-row">
        <div className="field">
          <label>Phone <span style={{ color: 'var(--slate-light)', fontWeight: 500 }}>(optional)</span></label>
          <input type="tel" value={form.phone} onChange={(e) => setForm({ ...form, phone: e.target.value })} placeholder="(336) 555‑0000" />
        </div>
        <div className={'field' + (errors.zip ? ' error' : '')}>
          <label>ZIP code <span className="req">*</span></label>
          <input value={form.zip} onChange={(e) => setForm({ ...form, zip: e.target.value })} placeholder="27101" />
          {errors.zip && <div className="err-msg">{errors.zip}</div>}
        </div>
      </div>

      <div className={'field' + (errors.org ? ' error' : '')}>
        <label>
          {isSponsor ? <>Recognize as <span className="req">*</span></> : <>Organization / Neighborhood <span style={{ color: 'var(--slate-light)', fontWeight: 500 }}>(optional)</span></>}
        </label>
        <input value={form.org} onChange={(e) => setForm({ ...form, org: e.target.value })} placeholder={isSponsor ? 'e.g. Acme Corp · The Smith Family · Anonymous' : 'e.g. Happy Hill Residents\' Association'} />
        {isSponsor && <div className="field-hint">How you'd like to be thanked publicly. Enter "Anonymous" if you prefer.</div>}
        {errors.org && <div className="err-msg">{errors.org}</div>}
      </div>

      <div className="field">
        <label>Designate your gift to… <Icon.Sparkle size={12} /></label>
        <div className="designation-grid">
          {Object.entries(DESIGNATIONS).map(([key, label]) => (
            <button
              type="button"
              key={key}
              className={'desig-opt' + (form.designation === key ? ' active' : '')}
              onClick={() => setForm({ ...form, designation: key })}
            >
              {label}
            </button>
          ))}
        </div>
        <div className="field-hint">Your gift fuels one of NBN's three Building Blocks — or let us direct it where it's most needed.</div>
      </div>

      <div className="field">
        <label>How did you hear about us? <span style={{ color: 'var(--slate-light)', fontWeight: 500 }}>(optional)</span></label>
        <select value={form.hearAbout} onChange={(e) => setForm({ ...form, hearAbout: e.target.value })}>
          <option value="">Select one…</option>
          <option>A friend or neighbor</option>
          <option>Board member or resident leader</option>
          <option>NBN newsletter or social</option>
          <option>United Way / partner org</option>
          <option>Faith community</option>
          <option>Press or news</option>
          <option>Other</option>
        </select>
      </div>

      <label className="checkbox-row">
        <input type="checkbox" checked={form.giftcard} onChange={(e) => setForm({ ...form, giftcard: e.target.checked })} />
        <span>
          <strong style={{ color: 'var(--navy-deep)' }}>Yes — send me my $10 Chick‑fil‑A gift card</strong> if I'm among the first 100 registrants.
          <div style={{ color: 'var(--slate-light)', fontSize: 12, marginTop: 2 }}>Delivered by email within 48 hours of the event.</div>
        </span>
      </label>

      <label className="checkbox-row">
        <input type="checkbox" checked={form.updates} onChange={(e) => setForm({ ...form, updates: e.target.checked })} />
        <span>Keep me posted on NBN community events and Building Blocks updates.</span>
      </label>

      <div className="total-row">
        <div>
          <div className="lbl">Order total</div>
          <div style={{ fontSize: 12, color: 'var(--slate-light)', marginTop: 2 }}>{tierData.label} · {tierData.desc}</div>
        </div>
        <div className="val">${total}</div>
      </div>

      <button type="submit" className="form-submit">
        <Icon.Lock /> Continue to GiveLively · ${total} <Icon.ArrowRight size={16} />
      </button>

      <div className="form-footer">
        Payment is processed securely by GiveLively. NBN is a 501(c)(3); a receipt with your tax‑deductible amount will arrive by email. Refundable through Jun 17, 2026.
      </div>
    </form>
  );
}

const DESIGNATIONS = {
  greatest: 'Where it\'s needed most',
  connectors: 'Resident Health Connectors',
  collaborative: 'Health Disparities Collaborative',
  leadership: 'Resident Leadership Initiative',
};

window.RegistrationForm = RegistrationForm;
window.DESIGNATIONS = DESIGNATIONS;
