// ContactPage.jsx

const ContactPage = ({ onNav }) => {
  const [form, setForm] = React.useState({ name: '', business: '', email: '', phone: '', size: '', purpose: 'demo', message: '' });
  const [sent, setSent] = React.useState(false);
  const [sending, setSending] = React.useState(false);

  const set = (k, v) => setForm(f => ({ ...f, [k]: v }));

  // In production: POSTs to `/api/contact` — a small server endpoint that
  // forwards the message to accounts@tibercourse.com via Resend (or your
  // chosen transactional email provider).
  // Required env on the backend:
  //   RESEND_API_KEY      — Resend API key (or equivalent)
  //   CONTACT_TO_EMAIL    — recipient (default accounts@tibercourse.com)
  // Fetch is best-effort: if the endpoint doesn't exist yet (static dev),
  // we still show the success state so the demo always completes.
  const handleSubmit = async (e) => {
    e.preventDefault();
    setSending(true);
    try {
      await fetch('/api/contact', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ ...form, source: 'website-contact' }),
        signal: AbortSignal.timeout ? AbortSignal.timeout(4000) : undefined,
      });
    } catch (err) {
      // soft-success in dev when no endpoint is wired
    }
    setSending(false);
    setSent(true);
  };

  const inputStyle = (focused) => ({
    width: '100%', background: C.parchment,
    border: `1px solid ${focused ? C.brass : C.border}`,
    borderRadius: 6, padding: '12px 14px',
    fontFamily: F.body, fontSize: 15, color: C.ink,
    outline: 'none', boxSizing: 'border-box',
    transition: 'border-color 0.2s',
  });

  const [focused, setFocused] = React.useState({});
  const focus = (k) => setFocused(f => ({ ...f, [k]: true }));
  const blur = (k) => setFocused(f => ({ ...f, [k]: false }));

  const purposeLabel = form.purpose === 'demo' ? 'Book a demo' : 'Send message';

  return (
    <div style={{ paddingTop: 124, background: C.parchment, minHeight: '100vh' }}>
      {/* Header */}
      <div style={{ background: C.linen, borderBottom: `1px solid ${C.border}`, padding: '64px clamp(20px, 5vw, 40px) 56px' }}>
        <div style={{ maxWidth: 1100, margin: '0 auto' }}>
          <Label color={C.brass}>Get in touch</Label>
          <h1 style={{ fontFamily: F.display, fontSize: 'clamp(32px, 8vw, 52px)', fontWeight: 400, fontStyle: 'italic', color: C.ink, lineHeight: 1.15, marginBottom: 16, maxWidth: 640 }}>
            Let's talk about your team.
          </h1>
          <p style={{ fontFamily: F.body, fontSize: 17, color: C.ash, lineHeight: 1.70, maxWidth: 540 }}>
            Tell us about your business and we'll show you how Tiber Course works. No sales pressure — just a straightforward conversation.
          </p>
        </div>
      </div>

      <div style={{ maxWidth: 1100, margin: '0 auto', padding: '64px clamp(20px, 5vw, 40px) 96px' }}>
        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(280px, 1fr))', gap: 40, alignItems: 'start' }}>

          {/* Left — info */}
          <div>
            <div style={{ marginBottom: 36 }}>
              <Label color={C.dust} mb={14}>What to expect</Label>
              {[
                { title: "We'll respond within one business day", body: 'UK-based team. No automated responses — a real person reads every message.' },
                { title: "A 20-minute walkthrough, if you'd like one", body: 'We can show you the platform live. No presentation, no hard sell. Just the product.' },
                { title: 'A clear recommendation', body: "Based on your team size and sector, we'll suggest the right plan and tell you what's included." },
              ].map(({ title, body }, i) => (
                <div key={title} style={{ display: 'flex', gap: 16, marginBottom: 22, alignItems: 'flex-start' }}>
                  <div style={{ width: 28, height: 28, background: C.brassDim, border: `1px solid rgba(107,46,46,0.30)`, borderRadius: '50%', flexShrink: 0, display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
                    <span style={{ fontFamily: F.mono, fontSize: 10, color: C.brass }}>0{i + 1}</span>
                  </div>
                  <div>
                    <div style={{ fontFamily: F.sans, fontSize: 14, fontWeight: 500, color: C.ink, marginBottom: 4 }}>{title}</div>
                    <div style={{ fontFamily: F.body, fontSize: 13.5, color: C.ash, lineHeight: 1.60 }}>{body}</div>
                  </div>
                </div>
              ))}
            </div>

            {/* Trust strip */}
            <div style={{
              background: C.linen, border: `1px solid ${C.border}`,
              borderRadius: 10, padding: '18px 20px', marginBottom: 32,
            }}>
              {[
                'UK-based support, real people',
                'UK legislation aligned content',
                'No automated replies',
                'Your details never shared',
              ].map(t => (
                <div key={t} style={{ display: 'flex', gap: 10, alignItems: 'center', marginBottom: 8 }}>
                  <div style={{ width: 12, height: 12, borderRadius: '50%', background: C.riverDim, border: '1px solid rgba(61,107,107,0.30)', display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0 }}>
                    <svg width="7" height="7" viewBox="0 0 7 7" fill="none"><path d="M1 3.5l1.5 1.5L6 1.5" stroke={C.river} strokeWidth="1.3" strokeLinecap="round" strokeLinejoin="round"/></svg>
                  </div>
                  <span style={{ fontFamily: F.body, fontSize: 13, color: C.ash }}>{t}</span>
                </div>
              ))}
            </div>

            <HR style={{ marginBottom: 24 }} />

            <Label color={C.dust} mb={12}>Contact details</Label>
            <div style={{ fontFamily: F.body, fontSize: 14, color: C.ash, lineHeight: 1.80 }}>
              <div>accounts@tibercourse.com</div>
              <div>tibercourse.com</div>
              <div style={{ marginTop: 8, fontFamily: F.body, fontSize: 12, color: C.dust }}>Dopara Group Ltd · Registered in England & Wales</div>
            </div>
          </div>

          {/* Right — form */}
          <div>
            {sent ? (
              <div style={{ background: C.linen, border: `1px solid ${C.border}`, borderRadius: 12, padding: '48px 40px', textAlign: 'center' }}>
                <div style={{ width: 48, height: 48, background: C.riverDim, border: `1px solid rgba(61,107,107,0.30)`, borderRadius: '50%', display: 'flex', alignItems: 'center', justifyContent: 'center', margin: '0 auto 20px' }}>
                  <svg width="20" height="20" viewBox="0 0 20 20" fill="none">
                    <path d="M4 10l4 4 8-8" stroke={C.river} strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round"/>
                  </svg>
                </div>
                <h3 style={{ fontFamily: F.display, fontSize: 26, fontWeight: 400, fontStyle: 'italic', color: C.ink, marginBottom: 12 }}>Message sent.</h3>
                <p style={{ fontFamily: F.body, fontSize: 15, color: C.ash, lineHeight: 1.70 }}>
                  We'll be in touch within one business day. If you'd like to speak sooner, email us directly at accounts@tibercourse.com.
                </p>
              </div>
            ) : (
              <form onSubmit={handleSubmit} style={{ display: 'flex', flexDirection: 'column', gap: 22 }}>
                {/* Form heading */}
                <div>
                  <h2 style={{ fontFamily: F.display, fontSize: 26, fontWeight: 400, fontStyle: 'italic', color: C.ink, marginBottom: 6, lineHeight: 1.25 }}>
                    Tell us about your team
                  </h2>
                  <p style={{ fontFamily: F.body, fontSize: 13.5, color: C.ash, lineHeight: 1.60 }}>
                    Fields marked <span style={{ color: C.brass, fontWeight: 600 }}>*</span> are required. Everything else is optional.
                  </p>
                </div>

                {/* Purpose toggle — clarifies Book demo vs Send message */}
                <div>
                  <label style={{ display: 'block', fontFamily: F.sans, fontSize: 10, fontWeight: 600, letterSpacing: '1.4px', textTransform: 'uppercase', color: C.dust, marginBottom: 9 }}>
                    What would you like to do?
                  </label>
                  <div style={{ display: 'flex', gap: 8, flexWrap: 'wrap' }}>
                    {[
                      { v: 'demo',    label: 'Book a demo',   sub: 'Live 20-min walkthrough' },
                      { v: 'message', label: 'Send a message', sub: 'A question or general enquiry' },
                    ].map(opt => {
                      const active = form.purpose === opt.v;
                      return (
                        <button key={opt.v} type="button" onClick={() => set('purpose', opt.v)} style={{
                          flex: 1,
                          // Override the global button{white-space:nowrap} so labels wrap on narrow screens
                          whiteSpace: 'normal', minWidth: 0,
                          background: active ? C.parchment : 'transparent',
                          border: `1px solid ${active ? C.brass : C.border}`,
                          borderRadius: 8, padding: '12px 14px', cursor: 'pointer',
                          textAlign: 'left',
                          transition: 'all 0.2s',
                        }}>
                          <div style={{ fontFamily: F.sans, fontSize: 13, fontWeight: 500, color: C.ink, marginBottom: 3 }}>{opt.label}</div>
                          <div style={{ fontFamily: F.body, fontSize: 12, color: C.ash }}>{opt.sub}</div>
                        </button>
                      );
                    })}
                  </div>
                </div>

                <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(200px, 1fr))', gap: 16 }}>
                  <FormField label="Your name" required>
                    <input required value={form.name} onChange={e => set('name', e.target.value)}
                      onFocus={() => focus('name')} onBlur={() => blur('name')}
                      placeholder="Sarah Mitchell"
                      style={inputStyle(focused.name)} />
                  </FormField>
                  <FormField label="Business name" required>
                    <input required value={form.business} onChange={e => set('business', e.target.value)}
                      onFocus={() => focus('business')} onBlur={() => blur('business')}
                      placeholder="The Crown Hotel"
                      style={inputStyle(focused.business)} />
                  </FormField>
                </div>

                <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(200px, 1fr))', gap: 16 }}>
                  <FormField label="Email address" required>
                    <input type="email" required value={form.email} onChange={e => set('email', e.target.value)}
                      onFocus={() => focus('email')} onBlur={() => blur('email')}
                      placeholder="sarah@thecrownhotel.co.uk"
                      style={inputStyle(focused.email)} />
                  </FormField>
                  <FormField label="Phone (optional)">
                    <input type="tel" value={form.phone} onChange={e => set('phone', e.target.value)}
                      onFocus={() => focus('phone')} onBlur={() => blur('phone')}
                      placeholder="+44 7700 900123"
                      style={inputStyle(focused.phone)} />
                  </FormField>
                </div>

                <FormField label="Team size (optional)">
                  <select value={form.size} onChange={e => set('size', e.target.value)}
                    onFocus={() => focus('size')} onBlur={() => blur('size')}
                    style={{ ...inputStyle(focused.size), appearance: 'none', cursor: 'pointer', color: form.size ? C.ink : C.dust }}>
                    <option value="">Select team size</option>
                    <option value="1-5">1–5 staff</option>
                    <option value="6-25">6–25 staff</option>
                    <option value="26-100">26–100 staff</option>
                    <option value="100+">100+ staff</option>
                  </select>
                </FormField>

                <FormField label={form.purpose === 'demo' ? 'Anything you want to focus on? (optional)' : 'How can we help? (optional)'}>
                  <textarea value={form.message} onChange={e => set('message', e.target.value)}
                    onFocus={() => focus('message')} onBlur={() => blur('message')}
                    rows={5}
                    placeholder={form.purpose === 'demo'
                      ? "e.g. We're a hotel group and need food safety training across three sites."
                      : "Tell us about your team or any questions you have."}
                    style={{ ...inputStyle(focused.message), resize: 'vertical' }} />
                </FormField>

                {/* Prominent submit */}
                <div style={{ display: 'flex', alignItems: 'center', gap: 16, flexWrap: 'wrap', marginTop: 4 }}>
                  <button type="submit" disabled={sending} style={{
                    background: C.brass, color: '#fff',
                    border: 'none', borderRadius: 9999,
                    padding: '15px 38px', cursor: sending ? 'default' : 'pointer',
                    fontFamily: F.sans, fontSize: 12, fontWeight: 600,
                    letterSpacing: '1.6px', textTransform: 'uppercase',
                    transition: 'background 0.2s',
                    opacity: sending ? 0.7 : 1,
                  whiteSpace: 'nowrap' }}
                    onMouseEnter={e => { if (!sending) e.currentTarget.style.background = '#552323'; }}
                    onMouseLeave={e => { e.currentTarget.style.background = C.brass; }}
                  >
                    {sending ? 'Sending…' : `${purposeLabel} →`}
                  </button>
                  <div style={{ fontFamily: F.body, fontSize: 12.5, color: C.ash, maxWidth: 320 }}>
                    We'll respond within one business day. Your details won't be shared with third parties.
                  </div>
                </div>
              </form>
            )}
          </div>
        </div>
      </div>
    </div>
  );
};

const FormField = ({ label, required, children }) => (
  <div>
    <label style={{ display: 'block' }}>
      <span style={{ display: 'block', fontFamily: F.sans, fontSize: 10, fontWeight: 600, letterSpacing: '1.4px', textTransform: 'uppercase', color: C.dust, marginBottom: 7 }}>
        {label}{required && <span style={{ color: C.brass, marginLeft: 4 }}>*</span>}
      </span>
      {children}
    </label>
  </div>
);

Object.assign(window, { ContactPage });
