// Dedications page — checkbox form for all tiers, wired for Gravity Forms handoff

const DedicationsPage = ({ onNav, formStyle }) => {
  const [selected, setSelected] = React.useState(new Set());
  const [form, setForm] = React.useState({ name: '', email: '', phone: '', message: '' });
  const [submitted, setSubmitted] = React.useState(false);
  const [submitting, setSubmitting] = React.useState(false);
  const [submitError, setSubmitError] = React.useState('');

  React.useEffect(() => { if (window.lucide) lucide.createIcons(); }, [selected, submitted]);

  const toggle = (label) => {
    setSelected(prev => {
      const next = new Set(prev);
      if (next.has(label)) next.delete(label); else next.add(label);
      return next;
    });
  };

  const handleSubmit = async (e) => {
    e.preventDefault();
    setSubmitError('');
    setSubmitting(true);
    try {
      const res = await fetch('/wp-json/soul/v1/dedication', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          name: form.name,
          email: form.email,
          phone: form.phone,
          message: form.message,
          items: [...selected],
        }),
      });
      const data = await res.json().catch(() => ({}));
      if (!res.ok || data.ok === false) {
        const msg = data?.message || (data?.data?.messages && Object.values(data.data.messages).join(' ')) || 'Submission failed. Please try again or call us.';
        setSubmitError(msg);
        setSubmitting(false);
        return;
      }
      setSubmitted(true);
      window.scrollTo({ top: document.querySelector('.ded-form').offsetTop - 100, behavior: 'smooth' });
    } catch (err) {
      setSubmitError('Network error. Please try again.');
    } finally {
      setSubmitting(false);
    }
  };

  const renderList = (items) => {
    const useThree = formStyle === 'compact' && items.length > 4;
    return (
      <div className={`ded-list ${useThree ? 'three' : ''}`}>
        {items.map(it => {
          const checked = selected.has(it.label);
          return (
            <label key={it.label} className={`ded-item ${checked ? 'checked' : ''}`}>
              <input type="checkbox" checked={checked} onChange={() => toggle(it.label)} style={{ display: 'none' }} />
              <span className="ded-check"><Icon name="check" size={14} /></span>
              <span className="ded-name">{it.label}</span>
              <span className="ded-amt">{fmtMoneyFull(it.amount)}</span>
            </label>
          );
        })}
      </div>
    );
  };

  return (
    <div className="page">
      <PageHero
        crumbs="Dedication Opportunities"
        title="Your name,"
        titleAccent="on the walls that hold us."
        lead="From a $1,000 Soul Supporter to the $10M Campus Endowment — every dedication builds the Soul Center. Select the opportunities that speak to you; our team will follow up to finalize."
        bg="assets/rendering.jpg"
      />

      <section className="block">
        <div className="container">
          <div className="ded-aside-top">
            <div>
              <h3>How it works</h3>
              <p>
                Select any number of opportunities below — there's no limit and no commitment yet.
                Share your contact info and our development team will reach out within two business days
                to walk you through pledge options, timing, and naming details.
              </p>
            </div>
            <div className="ded-aside-contact">
              <p>
                Prefer to talk first?<br/>
                Call <a href="tel:9732510200">(973) 251-0200</a><br/>
                or email <a href="mailto:development@soulcenternj.com">development@soulcenternj.com</a>.
              </p>
              <Button variant="ghost-light" onClick={() => onNav('contact')}>Contact the team</Button>
            </div>
          </div>

          <div className="ded-tiers-full">
            {SC_TIERS.map(tier => (
              <div key={tier.name} className="ded-tier">
                <div className="ded-tier-head">
                  <div>
                    <h3>{tier.name}</h3>
                  </div>
                  <p>{tier.description}</p>
                </div>
                {renderList(tier.items)}
              </div>
            ))}
          </div>

          {/* Form */}
          <form className="ded-form" onSubmit={handleSubmit}>
            <div className="ded-form-head">
              <h2>Your dedication inquiry</h2>
              <div className="selection-count">
                <b>{selected.size}</b> {selected.size === 1 ? 'opportunity' : 'opportunities'} selected
              </div>
            </div>

            <div className="selection-chips">
              {[...selected].map(label => (
                <span key={label} className="sel-chip">
                  {label}
                  <button type="button" className="x" onClick={() => toggle(label)} aria-label="Remove">✕</button>
                </span>
              ))}
            </div>

            <div className="form-grid">
              <div className="form-field full">
                <label>Full Name <span className="req">*</span></label>
                <input type="text" required value={form.name} onChange={e => setForm({ ...form, name: e.target.value })} placeholder="Firstname Lastname" />
              </div>
              <div className="form-field">
                <label>Email <span className="req">*</span></label>
                <input type="email" required value={form.email} onChange={e => setForm({ ...form, email: e.target.value })} placeholder="you@example.com" />
              </div>
              <div className="form-field">
                <label>Phone <span className="req">*</span></label>
                <input type="tel" required value={form.phone} onChange={e => setForm({ ...form, phone: e.target.value })} placeholder="(973) 555-1234" />
              </div>
            </div>

            <div className="form-grid">
              <div className="form-field full">
                <label>Message (optional)</label>
                <textarea rows="4" value={form.message} onChange={e => setForm({ ...form, message: e.target.value })} placeholder="Anything we should know, or a specific naming wish?" />
              </div>
            </div>

            {submitError && (
              <div style={{
                marginTop: 16, padding: 12, borderRadius: 10,
                background: '#fff3f3', color: '#8a1f1f', border: '1px solid #e4b5b5'
              }}>
                {submitError}
              </div>
            )}

            <div className="form-submit">
              <p>
                By submitting, you agree to be contacted about your dedication inquiry.
                This is not a binding pledge. Soul Center is a project of Friendship Circle of New Jersey, a 501(c)(3).
              </p>
              <Button variant="primary" size="lg" icon="heart" type="submit" disabled={submitting}>
                {submitting ? 'Submitting…' : 'Submit inquiry'}
              </Button>
            </div>

            {submitted && (
              <div style={{
                marginTop: 20, padding: 20, borderRadius: 12,
                background: 'var(--sc-blue-20)', color: 'var(--sc-indigo)',
                border: '1px solid var(--sc-blue)'
              }}>
                <b>Thank you, {form.name || 'friend'}.</b> We've received your inquiry for {selected.size} dedication {selected.size === 1 ? 'opportunity' : 'opportunities'}.
                A member of our development team will be in touch within two business days.
              </div>
            )}
          </form>
        </div>
      </section>
    </div>
  );
};

window.DedicationsPage = DedicationsPage;
