// page-enroll.jsx — "Become a member": one cohesive 2-step interest form -> api/send.php
const PORTAL_URL = 'https://peacefulheartsdpc.atlas.md';
const CONTACT_METHODS = ['Email', 'Phone', 'Text'];

// Read ?plan= from the URL so the membership-page buttons can pre-select a tier.
function getInitialPlan() {
  try {
    const p = new URLSearchParams(window.location.search).get('plan');
    if (p && phPlanById(p).id === p) return p;
  } catch (e) { /* ignore */ }
  return 'founding';
}

const emailOk = (v) => /^[^@\s]+@[^@\s]+\.[^@\s]+$/.test(v);
// US phone: must be exactly 10 digits (a leading country-code "1" is dropped).
const phoneDigits = (v) => {
  let d = (v || '').replace(/\D/g, '');
  if (d.length > 10 && d[0] === '1') d = d.slice(1);
  return d.slice(0, 10);
};
const formatPhone = (v) => {
  const d = phoneDigits(v);
  if (d.length < 4) return d;
  if (d.length < 7) return `(${d.slice(0, 3)}) ${d.slice(3)}`;
  return `(${d.slice(0, 3)}) ${d.slice(3, 6)}-${d.slice(6)}`;
};
const phoneOk = (v) => phoneDigits(v).length === 10;

function EnrollFlow() {
  const [plan, setPlan] = useState(getInitialPlan());
  const [name, setName] = useState('');
  const [email, setEmail] = useState('');
  const [phone, setPhone] = useState('');
  const [contactMethod, setContactMethod] = useState('Email');
  const [comments, setComments] = useState('');
  const [company, setCompany] = useState(''); // honeypot — real people leave this blank
  const [errors, setErrors] = useState({});   // { name, email, phone }
  const [status, setStatus] = useState('idle'); // idle | sending | sent | error
  const [errMsg, setErrMsg] = useState('');
  const selected = phPlanById(plan);

  // Clear a field's error as the visitor fixes it.
  const setField = (setter, key) => (e) => {
    setter(e.target.value);
    if (errors[key]) setErrors((prev) => ({ ...prev, [key]: undefined }));
  };

  const validate = () => {
    const errs = {};
    if (!name.trim()) errs.name = 'Please enter your name.';
    if (!email.trim()) errs.email = 'Please enter your email.';
    else if (!emailOk(email.trim())) errs.email = 'Please enter a valid email address.';
    if (!phone.trim()) errs.phone = 'Please enter a phone number.';
    else if (!phoneOk(phone)) errs.phone = 'Please enter a valid 10-digit US phone number.';
    return errs;
  };

  const submit = async (e) => {
    e.preventDefault();
    const errs = validate();
    if (Object.keys(errs).length) { setErrors(errs); setStatus('error'); setErrMsg(''); return; }
    setStatus('sending'); setErrMsg(''); setErrors({});
    try {
      const res = await fetch('api/send.php', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          type: 'enroll',
          plan: selected.name, planId: selected.id, planPrice: selected.price,
          name: name.trim(), email: email.trim(), phone: phone.trim(),
          contactMethod, comments: comments.trim(), company,
        }),
      });
      const data = await res.json().catch(() => ({}));
      if (res.ok && data.ok) { setStatus('sent'); }
      else { setErrMsg(data.error || 'Something went wrong sending your request. Please try again.'); setStatus('error'); }
    } catch (err) {
      setErrMsg('We couldn’t reach the server. Please email info@peacefulheartsdirect.com and we’ll help.');
      setStatus('error');
    }
  };

  // Confirmation — echo the details back to the visitor.
  if (status === 'sent') {
    return (
      <div className="ph-enroll-form ph-enroll-form-done">
        <div className="ph-contact-done">
          <div className="ph-modal-done-ic"><Icon name="heart" size={32} color="#506330" /></div>
          <h3>Thanks, {name.split(' ')[0]} — we’ve noted your interest.</h3>
          <p>Azra will be in touch soon (by {contactMethod.toLowerCase()}) to answer your questions and talk
            through membership. There’s no commitment — this just lets her know you’re interested. We’ve also emailed a copy to you.</p>
        </div>
        <dl className="ph-enroll-summary">
          <div><dt>Interested in</dt><dd>{selected.name} — ${selected.price}/month</dd></div>
          <div><dt>Name</dt><dd>{name}</dd></div>
          <div><dt>Email</dt><dd>{email}</dd></div>
          <div><dt>Phone</dt><dd>{phone}</dd></div>
          <div><dt>Preferred contact</dt><dd>{contactMethod}</dd></div>
          {comments.trim() && <div><dt>Comments</dt><dd>{comments.trim()}</dd></div>}
        </dl>
        <button className="btn btn-secondary" style={{ width: '100%' }}
          onClick={() => { setStatus('idle'); setName(''); setEmail(''); setPhone(''); setComments(''); setContactMethod('Email'); }}>
          Send another
        </button>
      </div>
    );
  }

  return (
    <div className="ph-enroll-form">
      {/* Step 1 — choose a plan */}
      <div className="ph-enroll-step">
        <div className="ph-enroll-step-head">
          <span className="ph-enroll-step-num">1</span>
          <h3>Choose your membership</h3>
        </div>
        <PlanGrid selectable selected={plan} onSelect={setPlan} />
      </div>

      {/* Step 2 — details */}
      <div className="ph-enroll-step">
        <div className="ph-enroll-step-head">
          <span className="ph-enroll-step-num">2</span>
          <h3>Your details</h3>
        </div>

        <div className="ph-enroll-chosen">
          <span className="ph-enroll-chosen-label">You’re interested in</span>
          <strong>{selected.name} — ${selected.price}/month</strong>
        </div>
        <p className="ph-enroll-note">Submitting this isn’t a commitment — it just lets Azra know you’re
          interested. She’ll reach out personally to answer questions and help you decide before anything is set up.</p>

        <form onSubmit={submit} noValidate>
          <div className={'ph-field' + (errors.name ? ' has-error' : '')}>
            <label>Name</label>
            <input value={name} onChange={setField(setName, 'name')} placeholder="Jane Doe" />
            {errors.name && <span className="ph-field-error">{errors.name}</span>}
          </div>
          <div className="ph-field-row">
            <div className={'ph-field' + (errors.email ? ' has-error' : '')}>
              <label>Email</label>
              <input type="email" value={email} onChange={setField(setEmail, 'email')} placeholder="jane@email.com" />
              {errors.email && <span className="ph-field-error">{errors.email}</span>}
            </div>
            <div className={'ph-field' + (errors.phone ? ' has-error' : '')}>
              <label>Phone</label>
              <input value={phone} inputMode="tel" autoComplete="tel" maxLength={14}
                onChange={e => { setPhone(formatPhone(e.target.value)); if (errors.phone) setErrors(p => ({ ...p, phone: undefined })); }}
                placeholder="(555) 123-4567" />
              {errors.phone && <span className="ph-field-error">{errors.phone}</span>}
            </div>
          </div>
          <div className="ph-field">
            <label>Preferred contact method</label>
            <select value={contactMethod} onChange={e => setContactMethod(e.target.value)}>
              {CONTACT_METHODS.map(m => <option key={m} value={m}>{m}</option>)}
            </select>
          </div>
          <div className="ph-field">
            <label>Additional comments <span style={{ color: 'var(--fg3)', fontWeight: 400 }}>(optional)</span></label>
            <textarea rows="3" value={comments} onChange={e => setComments(e.target.value)}
              placeholder="Anything you'd like Azra to know, or questions you have."></textarea>
          </div>

          {/* honeypot: hidden from people, tempting to bots */}
          <div className="ph-hp" aria-hidden="true">
            <label>Company<input tabIndex={-1} autoComplete="off" value={company} onChange={e => setCompany(e.target.value)} /></label>
          </div>

          {status === 'error' && errMsg && <p className="ph-form-error" role="alert">{errMsg}</p>}
          <button className="btn btn-primary" type="submit" style={{ width: '100%' }} disabled={status === 'sending'}>
            {status === 'sending' ? 'Sending…' : 'Send my details'}
          </button>
          <p className="ph-contact-fineprint">Please don’t include sensitive medical details. We’ll gather those securely later, only if you decide to join.</p>
        </form>
      </div>
    </div>
  );
}

function EnrollPage() {
  return (
    <Page active="enroll">
      <PageHead variant="navy" eyebrow="Enroll" title="Become a member"
        lead="Let us know you’re interested — it only takes a minute, with no commitment." />

      <section className="ph-section">
        <div className="ph-container">
          <SectionHead center eyebrow="Get started" title="Request your membership info"
            sub="Two quick steps — pick a plan and share your details. Azra will reach out personally to talk it through. No commitment." />
          <EnrollFlow />
          <p className="ph-enroll-portal">Already a member?
            <a href={PORTAL_URL} target="_blank" rel="noopener" style={{ fontWeight: 700, marginLeft: 6 }}>Patient portal ↗</a>
          </p>
        </div>
      </section>

      <section className="ph-section is-warm">
        <div className="ph-container">
          <div className="ph-callout">
            <div className="ph-callout-ic"><Icon name="heart" size={26} color="#1E364E" /></div>
            <div>
              <h3>No surprises, ever</h3>
              <p>No copays, hidden fees, or surprise bills. Cancel with 30 days’ written notice.
                DPC works alongside insurance and isn’t insurance itself.</p>
            </div>
          </div>
        </div>
      </section>
    </Page>
  );
}
renderApp(<EnrollPage />);
