// page-contact.jsx — "Get in touch"
const PORTAL = 'https://peacefulheartsdpc.atlas.md';

// Auto-format a US phone as you type: (555) 123-4567 (matches the enroll form).
const formatPhone = (v) => {
  let d = (v || '').replace(/\D/g, '');
  if (d.length > 10 && d[0] === '1') d = d.slice(1);
  d = d.slice(0, 10);
  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)}`;
};

function ContactForm() {
  const [name, setName] = useState('');
  const [email, setEmail] = useState('');
  const [phone, setPhone] = useState('');
  const [message, setMessage] = useState('');
  const [company, setCompany] = useState(''); // honeypot
  const [status, setStatus] = useState('idle'); // idle | sending | sent | error
  const [errMsg, setErrMsg] = useState('');

  const submit = async (e) => {
    e.preventDefault();
    if (!name.trim() || !email.trim() || !message.trim()) {
      setErrMsg('Please fill in your name, email, and message.'); setStatus('error'); return;
    }
    if (!/^[^@\s]+@[^@\s]+\.[^@\s]+$/.test(email)) {
      setErrMsg('Please enter a valid email address.'); setStatus('error'); return;
    }
    setStatus('sending'); setErrMsg('');
    try {
      const res = await fetch('api/send.php', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ type: 'contact', name: name.trim(), email: email.trim(), phone: phone.trim(), message: message.trim(), company }),
      });
      const data = await res.json().catch(() => ({}));
      if (res.ok && data.ok) { setStatus('sent'); }
      else { setErrMsg(data.error || 'Something went wrong sending your message. Please try again.'); setStatus('error'); }
    } catch (err) {
      setErrMsg('We couldn’t reach the server. Please email info@peacefulheartsdirect.com.');
      setStatus('error');
    }
  };

  if (status === 'sent') {
    return (
      <div className="ph-contact-card">
        <div className="ph-contact-done">
          <div className="ph-modal-done-ic"><Icon name="heart" size={32} color="#506330" /></div>
          <h3>Thank you, message sent.</h3>
          <p>We’ll be in touch within one business day.</p>
          <button className="btn btn-secondary" onClick={() => { setStatus('idle'); setName(''); setEmail(''); setPhone(''); setMessage(''); }}>Send another</button>
        </div>
      </div>
    );
  }
  return (
    <div className="ph-contact-card">
      <form onSubmit={submit} noValidate>
        <h3>Send us a note</h3>
        <div className="ph-field"><label>Name</label><input required value={name} onChange={e => setName(e.target.value)} placeholder="Jane Doe" /></div>
        <div className="ph-field-row">
          <div className="ph-field"><label>Email</label><input required type="email" value={email} onChange={e => setEmail(e.target.value)} placeholder="jane@email.com" /></div>
          <div className="ph-field"><label>Phone <span style={{ color: 'var(--fg3)', fontWeight: 400 }}>(optional)</span></label><input value={phone} inputMode="tel" autoComplete="tel" maxLength={14} onChange={e => setPhone(formatPhone(e.target.value))} placeholder="(555) 123-4567" /></div>
        </div>
        <div className="ph-field"><label>Message</label><textarea rows="4" value={message} onChange={e => setMessage(e.target.value)} placeholder="How can we help?"></textarea></div>
        <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' && <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 message'}
        </button>
        <p className="ph-contact-fineprint">Please don’t include sensitive medical details here. Members
          should use the secure portal for medical questions.</p>
      </form>
    </div>
  );
}

function ContactPage() {
  const info = [
    { icon: 'mail', label: 'Email', value: 'info@peacefulheartsdirect.com', sub: 'We reply within one business day' },
    { icon: 'pin', label: 'Address', value: '1010 Arthur Avenue, Suite C', sub: 'Orlando, FL 32804' },
    { icon: 'clock', label: 'Hours', value: 'By appointment', sub: 'Members reach us anytime by message' },
  ];
  return (
    <Page active="contact">
      <PageHead variant="warm" eyebrow="Contact" title="Get in touch" lead="We’d love to hear from you." />

      <section className="ph-section">
        <div className="ph-container ph-contact">
          <div className="ph-contact-info">
            <ul className="ph-contact-list" style={{ marginTop: 0 }}>
              {info.map(i => (
                <li key={i.label}>
                  <span className="ph-contact-ic"><Icon name={i.icon} size={20} color="#506330" /></span>
                  <div>
                    <span className="ph-contact-label">{i.label}</span>
                    <strong>{i.value}</strong>
                    <span className="ph-contact-sub">{i.sub}</span>
                  </div>
                </li>
              ))}
            </ul>
            <div className="ph-map" role="img" aria-label="Map of the Orlando, Florida clinic location">
              <div className="ph-map-pin"><Icon name="pin" size={26} color="#fff" /></div>
              <span className="ph-map-label">Orlando, FL 32804</span>
            </div>
            <div className="ph-contact-aside">
              <div className="ph-tile is-warm">
                <h3 style={{ fontSize: 'var(--text-md)' }}>Already a member?</h3>
                <p style={{ margin: '0 0 var(--space-3)' }}>The fastest way to reach your provider is the secure patient portal.</p>
                <a className="btn btn-secondary btn-sm" href={PORTAL} target="_blank" rel="noopener">Open patient portal ↗</a>
              </div>
              <div className="ph-tile is-warm">
                <h3 style={{ fontSize: 'var(--text-md)' }}>Interested in learning more?</h3>
                <p style={{ margin: '0 0 var(--space-3)' }}>Share your details and Azra will reach out personally. No commitment to start.</p>
                <a className="btn btn-primary btn-sm" href="enroll.html">Become a member</a>
              </div>
            </div>
          </div>
          <ContactForm />
        </div>
        <div className="ph-container" style={{ marginTop: 'var(--space-6)' }}><EmergencyNote /></div>
      </section>
    </Page>
  );
}
renderApp(<ContactPage />);
