function VisitScreen({ onNav }) {
  const mob = useIsMobile();
  const [step, setStep] = React.useState(1);
  const [form, setForm] = React.useState({ pet: '', species: '', owner: '', phone: '', reason: 'Annual exam', date: '', time: '' });
  const [submitState, setSubmitState] = React.useState('idle'); // 'idle' | 'sending' | 'error'
  const [submitError, setSubmitError] = React.useState('');
  const [feedbackState, setFeedbackState] = React.useState('hidden'); // 'hidden' | 'open' | 'sending' | 'sent' | 'error'
  const [feedbackText, setFeedbackText] = React.useState('');
  const [feedbackError, setFeedbackError] = React.useState('');
  const slots = ['Morning', 'Afternoon'];

  // Web3Forms config — the access key is public-by-design (it ships in client JS).
  // Locked to the davievet domains in the Web3Forms dashboard for abuse protection.
  // To change the recipient: log into web3forms.com and update the email on this key.
  const WEB3FORMS_KEY = '37597c66-aa26-4efd-ab14-31ea1838d082';
  const WEB3FORMS_ENDPOINT = 'https://api.web3forms.com/submit';

  const step1Valid = form.pet.trim() && form.owner.trim() && form.phone.trim();
  const step2Valid = form.date && form.time;

  async function postToWeb3Forms(fields) {
    const res = await fetch(WEB3FORMS_ENDPOINT, {
      method: 'POST',
      headers: { 'Content-Type': 'application/json', 'Accept': 'application/json' },
      body: JSON.stringify({ access_key: WEB3FORMS_KEY, ...fields }),
    });
    const data = await res.json().catch(() => ({}));
    if (!res.ok || data.success === false) {
      throw new Error(data.message || `Request failed (${res.status})`);
    }
    return data;
  }

  async function submitBooking() {
    setSubmitState('sending');
    setSubmitError('');
    try {
      await postToWeb3Forms({
        subject: `New appointment request — ${form.pet} (${form.owner})`,
        from_name: 'Davie Vet Website',
        'Pet name': form.pet,
        'Species': form.species,
        'Owner name': form.owner,
        'Phone': form.phone,
        'Reason for visit': form.reason,
        'Additional details': form.notes || '',
        'Requested day': form.date,
        'Requested time': form.time,
      });
      console.log('[booking] sent via Web3Forms');
      setSubmitState('idle');
      setStep(3);
    } catch (err) {
      console.error('[booking] error:', err);
      setSubmitState('error');
      setSubmitError(`We couldn't send your request. Please try again, or call us at (954) 581-4971. (Debug: ${err.message || err})`);
    }
  }

  async function submitFeedback() {
    if (!feedbackText.trim() || feedbackState === 'sending') return;
    setFeedbackState('sending');
    setFeedbackError('');
    try {
      await postToWeb3Forms({
        subject: `Website feedback — ${form.owner || 'Anonymous'}`,
        from_name: 'Davie Vet Website',
        'Feedback': feedbackText,
        'From (owner)': form.owner || '',
        'Pet name': form.pet || '',
        'Phone': form.phone || '',
      });
      setFeedbackState('sent');
    } catch (err) {
      console.error('[feedback] error:', err);
      setFeedbackState('error');
      setFeedbackError("We couldn't send your feedback. Please try again.");
    }
  }

  function handleNext() {
    if (step === 1) {
      if (!step1Valid) return;
      setStep(2);
    } else if (step === 2) {
      if (!step2Valid || submitState === 'sending') return;
      submitBooking();
    } else {
      setStep(Math.min(3, step + 1));
    }
  }

  // Generate today + next 10 weekdays (Mon–Fri)
  const days = React.useMemo(() => {
    const result = [];
    const d = new Date();
    const dayNames = ['Sun','Mon','Tue','Wed','Thu','Fri','Sat'];
    const monthNames = ['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec'];
    // Include today if it's a weekday
    const todayDow = d.getDay();
    if (todayDow >= 1 && todayDow <= 5) {
      result.push(`Today · ${monthNames[d.getMonth()]} ${d.getDate()}`);
    }
    const next = new Date(d);
    while (result.length < 10) {
      next.setDate(next.getDate() + 1);
      const dow = next.getDay();
      if (dow >= 1 && dow <= 5) {
        result.push(`${dayNames[dow]} · ${monthNames[next.getMonth()]} ${next.getDate()}`);
      }
    }
    return result;
  }, []);

  return (
    <div style={{ background: 'var(--cream-50)', minHeight: '100vh' }}>
      <NavBar active="Visit" onNav={onNav} />
      <div style={{ maxWidth: 960, margin: '0 auto', padding: mob ? '36px 20px' : '56px 40px' }}>
        <Eyebrow>Book a visit</Eyebrow>
        <h1 style={{ fontFamily: 'var(--font-display)', fontSize: mob ? 38 : 56, color: 'var(--ink-900)', lineHeight: 1, margin: '10px 0 20px' }}>
          Let's get {form.pet || 'your pet'} on the books.
        </h1>

        {/* Stepper */}
        <div style={{ display: 'flex', gap: 8, marginBottom: 24 }}>
          {[1,2,3].map(n => (
            <div key={n} style={{ flex: 1, height: 6, borderRadius: 3, background: n <= step ? 'var(--orange-500)' : 'var(--cream-200)' }}/>
          ))}
        </div>

        <div style={{ background: '#fff', border: '1.5px solid var(--border)', borderRadius: 14, padding: mob ? 20 : 32, boxShadow: 'var(--shadow-sm)' }}>

          {step === 1 && (
            <div>
              <h2 style={{ fontFamily: 'var(--font-display)', fontSize: mob ? 22 : 26, marginTop: 0, marginBottom: 16 }}>Tell us about your pet</h2>
              <div style={{ display: 'grid', gridTemplateColumns: mob ? '1fr' : '1fr 1fr', gap: mob ? 14 : 18 }}>
                <Field label="Pet's Name" value={form.pet} onChange={v => setForm({...form, pet: v})} placeholder="e.g. Biscuit"/>
                <Field label="Species" value={form.species} onChange={v => setForm({...form, species: v})} placeholder="e.g. Dog, Cat, Rabbit…"/>
                <Field label="Your name" value={form.owner} onChange={v => setForm({...form, owner: v})} placeholder="Sam Alvarez"/>
                <Field label="Phone" value={form.phone} onChange={v => setForm({...form, phone: v})} placeholder="(954) ___-____"/>
                <div style={{ gridColumn: mob ? 'auto' : '1 / -1' }}>
                  <Field label="Reason for visit" value={form.reason} onChange={v => setForm({...form, reason: v})} options={['Annual exam', 'Vaccines', 'Dental', "Something's off", 'Surgery consult']}/>
                </div>
                <div style={{ gridColumn: mob ? 'auto' : '1 / -1' }}>
                  <Field label="Additional details" value={form.notes || ''} onChange={v => setForm({...form, notes: v})} placeholder="Anything else we should know — symptoms, concerns, questions…" multiline />
                </div>
              </div>
            </div>
          )}

          {step === 2 && (
            <div>
              <h2 style={{ fontFamily: 'var(--font-display)', fontSize: mob ? 22 : 26, marginTop: 0, marginBottom: 16 }}>Pick a day & time</h2>
              <div style={{ fontFamily: 'var(--font-body)', fontSize: 11, fontWeight: 700, textTransform: 'uppercase', letterSpacing: '0.12em', color: 'var(--fg2)', marginBottom: 8 }}>Day</div>
              <div style={{ display: 'flex', gap: 8, marginBottom: 24, flexWrap: 'wrap' }}>
                {days.map(d => (
                  <button key={d} onClick={() => setForm({...form, date: d})} style={{
                    padding: mob ? '10px 14px' : '12px 18px', borderRadius: 8,
                    border: '1.5px solid ' + (form.date === d ? 'var(--navy-600)' : 'var(--border-strong)'),
                    background: form.date === d ? 'var(--navy-600)' : '#fff',
                    color: form.date === d ? '#fff' : 'var(--fg1)',
                    fontFamily: 'var(--font-body)', fontWeight: 600, fontSize: mob ? 12 : 14, cursor: 'pointer', flex: mob ? '1 1 calc(50% - 4px)' : 'none'
                  }}>{d}</button>
                ))}
              </div>
              <div style={{ fontFamily: 'var(--font-body)', fontSize: 11, fontWeight: 700, textTransform: 'uppercase', letterSpacing: '0.12em', color: 'var(--fg2)', marginBottom: 8 }}>Time</div>
              <div style={{ display: 'flex', gap: 8, flexWrap: 'wrap' }}>
                {slots.map(t => (
                  <button key={t} onClick={() => setForm({...form, time: t})} style={{
                    padding: mob ? '10px 14px' : '10px 16px', borderRadius: 999,
                    border: '1.5px solid ' + (form.time === t ? 'var(--orange-500)' : 'var(--border-strong)'),
                    background: form.time === t ? 'var(--orange-500)' : '#fff',
                    color: form.time === t ? '#fff' : 'var(--fg1)',
                    fontFamily: 'var(--font-body)', fontWeight: 600, fontSize: mob ? 12 : 13, cursor: 'pointer'
                  }}>{t}</button>
                ))}
              </div>
            </div>
          )}

          {step === 3 && (
            <div style={{ textAlign: 'center', padding: '20px 0' }}>
              <svg width="56" height="56" viewBox="0 0 24 24" style={{ color: 'var(--navy-600)', marginBottom: 10 }}>
                <circle cx="12" cy="12" r="10" fill="none" stroke="currentColor" strokeWidth="2"/>
                <path d="M8 12.5l3 3 5-6" fill="none" stroke="currentColor" strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round"/>
              </svg>
              <h2 style={{ fontFamily: 'var(--font-display)', fontSize: mob ? 28 : 36, color: 'var(--ink-900)', margin: '8px 0 10px' }}>Request received!</h2>
              <p style={{ fontFamily: 'var(--font-body)', fontSize: mob ? 14 : 16, color: 'var(--fg2)', lineHeight: 1.6, maxWidth: 420, margin: '0 auto 18px' }}>
                Thanks{form.owner ? `, ${form.owner}` : ''}! We've received your appointment request for <b style={{ color: 'var(--fg1)' }}>{form.date}{form.time ? ` · ${form.time}` : ''}</b>. A member of our team will call you to confirm the time within 24 hours.
              </p>
              <p style={{ fontFamily: 'var(--font-body)', fontSize: mob ? 13 : 14, color: 'var(--fg2)', margin: '0 auto', maxWidth: 360 }}>
                Questions? Call us at <a href="tel:9545814971" style={{ color: 'var(--navy-600)', fontWeight: 700 }}>(954) 581-4971</a> or text <a href="sms:+19545814971" style={{ color: 'var(--navy-600)', fontWeight: 700 }}>(954) 581-4971</a>.
              </p>

              <div style={{
                marginTop: 18, maxWidth: 460, margin: '18px auto 0',
                padding: '14px 18px',
                background: 'var(--cream-100)',
                border: '1.5px solid var(--border)',
                borderRadius: 10,
                display: 'flex', gap: 12, alignItems: 'flex-start', textAlign: 'left'
              }}>
                <svg width="22" height="22" viewBox="0 0 24 24" fill="none" stroke="var(--navy-600)" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" style={{ flexShrink: 0, marginTop: 1 }}>
                  <path d="M22 12h-4l-3 9L9 3l-3 9H2"/>
                </svg>
                <div style={{ fontFamily: 'var(--font-body)', fontSize: mob ? 13 : 14, color: 'var(--fg1)', lineHeight: 1.55 }}>
                  <b style={{ color: 'var(--ink-900)' }}>Have prior medical records?</b><br/>
                  Email them ahead of your visit to <a href="mailto:hello@davievetcenter.com" style={{ color: 'var(--navy-600)', fontWeight: 700, wordBreak: 'break-all' }}>hello@davievetcenter.com</a> so we're ready when you arrive.
                </div>
              </div>

              <div style={{ marginTop: 32, paddingTop: 24, borderTop: '1px solid var(--border)', maxWidth: 480, margin: '32px auto 0' }}>
                {feedbackState === 'hidden' && (
                  <button
                    onClick={() => setFeedbackState('open')}
                    style={{
                      background: 'transparent', border: '1.5px solid var(--border-strong)', borderRadius: 999,
                      padding: '10px 20px', fontFamily: 'var(--font-body)', fontWeight: 600, fontSize: 14,
                      color: 'var(--fg1)', cursor: 'pointer'
                    }}
                  >
                    Got a sec? Tell us what we could improve.
                  </button>
                )}

                {(feedbackState === 'open' || feedbackState === 'sending' || feedbackState === 'error') && (
                  <div style={{ textAlign: 'left' }}>
                    <label style={{ fontFamily: 'var(--font-body)', fontSize: 11, fontWeight: 700, textTransform: 'uppercase', letterSpacing: '0.12em', color: 'var(--fg2)', display: 'block', marginBottom: 6 }}>
                      What could we improve?
                    </label>
                    <textarea
                      value={feedbackText}
                      onChange={e => setFeedbackText(e.target.value)}
                      placeholder="Anything — the booking flow, the website, how we treated you last time…"
                      rows={4}
                      disabled={feedbackState === 'sending'}
                      style={{ ...visitFieldStyle, resize: 'vertical', minHeight: 90 }}
                    />
                    {feedbackState === 'error' && (
                      <div style={{ marginTop: 10, padding: '8px 12px', background: '#fdecea', border: '1.5px solid #e57373', borderRadius: 8, fontFamily: 'var(--font-body)', fontSize: 13, color: '#b71c1c' }}>
                        {feedbackError}
                      </div>
                    )}
                    <div style={{ display: 'flex', justifyContent: 'flex-end', gap: 8, marginTop: 12 }}>
                      <Button variant="ghost" onClick={() => { setFeedbackState('hidden'); setFeedbackText(''); }}>Cancel</Button>
                      <Button
                        variant="accent"
                        onClick={submitFeedback}
                        style={{
                          opacity: !feedbackText.trim() || feedbackState === 'sending' ? 0.5 : 1,
                          pointerEvents: !feedbackText.trim() || feedbackState === 'sending' ? 'none' : 'auto'
                        }}
                      >
                        {feedbackState === 'sending' ? 'Sending…' : 'Send feedback'}
                      </Button>
                    </div>
                  </div>
                )}

                {feedbackState === 'sent' && (
                  <p style={{ fontFamily: 'var(--font-body)', fontSize: mob ? 14 : 15, color: 'var(--navy-600)', fontWeight: 600, margin: 0 }}>
                    Thanks for the feedback — it goes straight to our team.
                  </p>
                )}
              </div>
            </div>
          )}

          {submitState === 'error' && (
            <div style={{ marginTop: 16, padding: '10px 14px', background: '#fdecea', border: '1.5px solid #e57373', borderRadius: 8, fontFamily: 'var(--font-body)', fontSize: 14, color: '#b71c1c' }}>
              {submitError}
            </div>
          )}

          <div style={{ display: 'flex', justifyContent: 'space-between', marginTop: 24, gap: 12 }}>
            <Button variant="ghost" onClick={() => setStep(Math.max(1, step - 1))} style={{ opacity: step === 1 || submitState === 'sending' ? 0.4 : 1, pointerEvents: step === 1 || submitState === 'sending' ? 'none' : 'auto', ...(mob ? { flex: 1 } : {}) }}>Back</Button>
            <Button
              variant="accent"
              onClick={handleNext}
              style={{
                opacity: (step === 1 && !step1Valid) || (step === 2 && (!step2Valid || submitState === 'sending')) ? 0.5 : 1,
                pointerEvents: (step === 1 && !step1Valid) || (step === 2 && (!step2Valid || submitState === 'sending')) ? 'none' : 'auto',
                ...(mob ? { flex: 1 } : {})
              }}
            >
              {step === 3 ? 'Done' : step === 2 ? (submitState === 'sending' ? 'Sending…' : 'Confirm') : 'Next'}
            </Button>
          </div>
        </div>
      </div>
      <Footer />
    </div>
  );
}

function Field({ label, value, onChange, placeholder, options, multiline }) {
  return (
    <div>
      <label style={{ fontFamily: 'var(--font-body)', fontSize: 11, fontWeight: 700, textTransform: 'uppercase', letterSpacing: '0.12em', color: 'var(--fg2)', display: 'block', marginBottom: 6 }}>{label}</label>
      {options ? (
        <select value={value} onChange={e => onChange(e.target.value)} style={visitFieldStyle}>
          {options.map(o => <option key={o}>{o}</option>)}
        </select>
      ) : multiline ? (
        <textarea value={value} placeholder={placeholder} onChange={e => onChange(e.target.value)} rows={3} style={{ ...visitFieldStyle, resize: 'vertical', minHeight: 80 }}></textarea>
      ) : (
        <input value={value} placeholder={placeholder} onChange={e => onChange(e.target.value)} style={visitFieldStyle}/>
      )}
    </div>
  );
}

const visitFieldStyle = {
  width: '100%', padding: '12px 14px',
  fontFamily: 'var(--font-body)', fontSize: 15,
  border: '1.5px solid var(--border-strong)', borderRadius: 8,
  background: '#fff', color: 'var(--fg1)', boxSizing: 'border-box'
};

window.VisitScreen = VisitScreen;
