// Contact page — form, offices, hours, FAQ

const FAQ = [
  { q: 'How quickly can you start?', a: 'Pilots typically start within 24–48 hours of NDA. A full team can be staffed in a week.' },
  { q: 'What\'s your minimum engagement?', a: 'No minimum. We\'ll happily quote a single drawing — though most pilots run 40–120 hours.' },
  { q: 'How do you bill?', a: 'Three ways: hourly (with weekly timesheets), fixed-price per project, or dedicated monthly seats. You pick.' },
  { q: 'Will you sign our NDA?', a: 'Yes — and we generally sign customer NDAs as-is. We have a mutual template if you\'d prefer to start from ours.' },
  { q: 'Whose software licenses?', a: 'Ours — we cover all licensing on our end. Revit, Navisworks, ArchiCAD, 3DS Max, Lumion, ReCap.' },
  { q: 'How do we share files?', a: 'Your CDE — BIM 360, ACC, SharePoint, Dropbox, Google Drive. We work in your environment, not ours.' },
];

const CONTACT_REASONS = [
  { id: 'quote',   label: 'Request a quote',     desc: 'Send a brief, get a quote within 24 hours.' },
  { id: 'pilot',   label: 'Start a free pilot',  desc: '40–120 hours of work, no commitment.' },
  { id: 'general', label: 'General enquiry',     desc: 'Partnerships, press, anything else.' },
  { id: 'careers', label: 'Careers',             desc: 'Apply or learn about open positions.' },
];

function ContactHero() {
  const { w } = useViewport();
  return (
    <section style={{ position: 'relative', padding: pick(w, '80px 0 40px', '48px 0 32px'), overflow: 'hidden' }}>
      <CursorSpotlight color="rgba(243, 119, 53, 0.10)" size={500} />
      <div style={{
        position: 'absolute', top: -200, right: -100, width: 600, height: 600,
        background: `radial-gradient(circle, ${BS.accentSoft}, transparent 65%)`,
        opacity: 0.6, pointerEvents: 'none',
      }} />
      <div style={{ ...bsStyles.container, position: 'relative', textAlign: 'center' }}>
        <div style={{ ...bsStyles.eyebrow, marginBottom: 22, justifyContent: 'center' }}>
          Get in touch
        </div>
        <h1 style={{ ...bsStyles.display, fontSize: fs(48, 124), margin: 0, marginBottom: 28 }}>
          Let's <span style={{ position: 'relative', display: 'inline-block' }}>
            talk.
            <svg style={{ position: 'absolute', left: '5%', right: '5%', bottom: -8, width: '90%' }} viewBox="0 0 200 12" preserveAspectRatio="none">
              <path d="M2 8 Q 50 0, 100 6 T 198 4" stroke={BS.accent} strokeWidth="4" fill="none" strokeLinecap="round" />
            </svg>
          </span>
        </h1>
        <p style={{ fontSize: fs(16, 19), color: BS.text2, lineHeight: 1.5, maxWidth: 620, margin: '0 auto' }}>
          Send a brief. We respond within four business hours and quote within one business day.
        </p>
      </div>
    </section>
  );
}

function ContactForm() {
  const [reason, setReason] = React.useState('quote');
  const [submitted, setSubmitted] = React.useState(false);
  const [sending, setSending] = React.useState(false);
  const [sendError, setSendError] = React.useState(null);
  const [errors, setErrors] = React.useState({});
  const nameRef = React.useRef();
  const emailRef = React.useRef();
  const projectRef = React.useRef();
  const companyRef = React.useRef();
  const phoneRef = React.useRef();
  const serviceRef = React.useRef();
  const ndaRef = React.useRef();

  async function onSubmit(e) {
    e.preventDefault();
    const errs = {};
    const name = nameRef.current.value.trim();
    const email = emailRef.current.value.trim();
    const project = projectRef.current.value.trim();
    if (!name) errs.name = true;
    if (!email || !/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email)) errs.email = true;
    if (!project) errs.project = true;
    if (Object.keys(errs).length) { setErrors(errs); return; }
    setErrors({});
    setSendError(null);
    setSending(true);

    const reasonLabel = CONTACT_REASONS.find(r => r.id === reason)?.label || reason;
    try {
      const res = await fetch('https://formspree.io/f/mnjwreqd', {
        method: 'POST',
        headers: { 'Accept': 'application/json', 'Content-Type': 'application/json' },
        body: JSON.stringify({
          name,
          email,
          company: companyRef.current.value.trim() || '—',
          phone: phoneRef.current.value.trim() || '—',
          reason: reasonLabel,
          service: serviceRef.current.value,
          project,
          nda_requested: ndaRef.current.checked ? 'Yes' : 'No',
        }),
      });
      if (res.ok) {
        setSubmitted(true);
      } else {
        const data = await res.json();
        setSendError(data?.errors?.[0]?.message || 'Something went wrong. Please email mail@thebimace.com directly.');
      }
    } catch {
      setSendError('Network error. Please email mail@thebimace.com directly.');
    } finally {
      setSending(false);
    }
  }

  const { w } = useViewport();
  return (
    <section style={{ padding: pick(w, '40px 0 120px', '24px 0 72px') }}>
      <div style={bsStyles.container}>
        <div style={{
          background: BS.bg2, border: `1px solid ${BS.border}`,
          borderRadius: 28, overflow: 'hidden',
          display: 'grid', gridTemplateColumns: pick(w, '0.85fr 1fr', '1fr'),
        }}>
          {/* Left: reasons + info */}
          <div style={{
            background: BS.bgDark, color: '#fff', padding: pick(w, 48, 28),
            display: 'flex', flexDirection: 'column',
          }}>
            <div style={{
              fontSize: 11, fontWeight: 700, letterSpacing: '0.08em',
              textTransform: 'uppercase', color: 'rgba(255,255,255,0.6)', marginBottom: 14,
            }}>What are you here for?</div>
            <div style={{ display: 'flex', flexDirection: 'column', gap: 8, marginBottom: 40 }}>
              {CONTACT_REASONS.map(r => (
                <button key={r.id} type="button" onClick={() => setReason(r.id)} style={{
                  textAlign: 'left',
                  padding: '14px 16px', borderRadius: 14,
                  background: reason === r.id ? BS.accent : 'rgba(255,255,255,0.04)',
                  border: `1px solid ${reason === r.id ? BS.accent : 'rgba(255,255,255,0.12)'}`,
                  color: '#fff', cursor: 'pointer', fontFamily: 'inherit',
                  transition: 'all 0.18s',
                }}>
                  <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
                    <span style={{ fontSize: 15, fontWeight: 700 }}>{r.label}</span>
                    <span style={{
                      width: 18, height: 18, borderRadius: '50%',
                      border: '1.5px solid #fff',
                      display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
                    }}>{reason === r.id && <span style={{ width: 8, height: 8, background: '#fff', borderRadius: '50%' }} />}</span>
                  </div>
                  <div style={{
                    fontSize: 12.5, color: reason === r.id ? 'rgba(255,255,255,0.9)' : 'rgba(255,255,255,0.6)',
                    marginTop: 4,
                  }}>{r.desc}</div>
                </button>
              ))}
            </div>

            <div style={{ marginTop: 'auto', paddingTop: 24, borderTop: '1px solid rgba(255,255,255,0.12)' }}>
              <div style={{ fontSize: 11, fontWeight: 700, letterSpacing: '0.08em', textTransform: 'uppercase', color: 'rgba(255,255,255,0.6)', marginBottom: 14 }}>
                Or reach us directly
              </div>
              <div style={{ display: 'flex', flexDirection: 'column', gap: 12 }}>
                {[
                  ['mail@thebimace.com',  'mailto:mail@thebimace.com'],
                  ['+1 (631) 464-0144',   'tel:+16314640144'],
                  ['New Delhi, IN',       null],
                ].map(([label, href]) => (
                  href ? (
                    <a key={label} href={href} style={{ color: '#fff', textDecoration: 'none', fontSize: 14, fontWeight: 600 }}>
                      {label}
                    </a>
                  ) : (
                    <div key={label} style={{ color: 'rgba(255,255,255,0.75)', fontSize: 14 }}>{label}</div>
                  )
                ))}
              </div>
            </div>
          </div>

          {/* Right: form */}
          <form onSubmit={onSubmit} style={{ padding: pick(w, 48, 28), display: 'flex', flexDirection: 'column', gap: 18 }}>
            {submitted ? (
              <div style={{ textAlign: 'center', padding: '40px 0' }}>
                <div style={{
                  width: 60, height: 60, borderRadius: '50%', background: BS.accentSoft,
                  display: 'inline-flex', alignItems: 'center', justifyContent: 'center', marginBottom: 22,
                }}>
                  <svg width="28" height="28" viewBox="0 0 28 28" fill="none">
                    <path d="M5 14l6 6 12-14" stroke={BS.accent} strokeWidth="3" strokeLinecap="round" strokeLinejoin="round" />
                  </svg>
                </div>
                <h3 style={{ ...bsStyles.display, fontSize: 32, margin: 0, marginBottom: 12 }}>Thanks — we've got it.</h3>
                <p style={{ fontSize: 15, color: BS.text2, lineHeight: 1.6, margin: 0, marginBottom: 24 }}>
                  Expect a reply from a studio lead within four business hours. If you don't hear from us, check spam or
                  drop a note to <a href="mailto:mail@thebimace.com" style={{ color: BS.accent, fontWeight: 600 }}>mail@thebimace.com</a>.
                </p>
                <button type="button" onClick={() => setSubmitted(false)} style={{
                  ...bsStyles.btnGhost, padding: '12px 20px', fontSize: 13,
                }}>Send another</button>
              </div>
            ) : (
              <>
                <div>
                  <div style={{ fontSize: 22, fontWeight: 700, marginBottom: 6 }}>Tell us about your project</div>
                  <div style={{ fontSize: 13, color: BS.muted }}>Marked fields required · NDA on request</div>
                </div>
                <div style={{ display: 'grid', gridTemplateColumns: pick(w, '1fr 1fr', '1fr 1fr', '1fr'), gap: 14 }}>
                  <Field label="Your name *" placeholder="Sarah Whitfield" fieldRef={nameRef} error={errors.name} />
                  <Field label="Company" placeholder="Whitfield + Bell" fieldRef={companyRef} />
                </div>
                <div style={{ display: 'grid', gridTemplateColumns: pick(w, '1fr 1fr', '1fr 1fr', '1fr'), gap: 14 }}>
                  <Field label="Work email *" placeholder="sarah@whitfield-bell.co.uk" type="email" fieldRef={emailRef} error={errors.email} />
                  <Field label="Phone" placeholder="+44 20 ..." type="tel" fieldRef={phoneRef} />
                </div>
                <div>
                  <label style={{ fontSize: 12, fontWeight: 700, color: BS.muted, display: 'block', marginBottom: 6, letterSpacing: '0.04em', textTransform: 'uppercase' }}>
                    Service needed
                  </label>
                  <select ref={serviceRef} defaultValue="bim-coord" style={fieldStyle}>
                    <option value="cad-to-bim">CAD / PDF to BIM conversion</option>
                    <option value="bim-coord">BIM coordination & clash detection</option>
                    <option value="viz">Visualization & renders</option>
                    <option value="docs">Construction documentation</option>
                    <option value="design">Design services</option>
                    <option value="other">Other / not sure yet</option>
                  </select>
                </div>
                <div>
                  <label style={{ fontSize: 12, fontWeight: 700, color: errors.project ? '#e03' : BS.muted, display: 'block', marginBottom: 6, letterSpacing: '0.04em', textTransform: 'uppercase' }}>
                    Tell us about the project *
                  </label>
                  <textarea ref={projectRef} rows={5} placeholder="One floor of an existing commercial property. Need CAD-to-Revit conversion at LOD 300, plus a federated model for MEP coordination. Timeline: 6 weeks."
                    style={{ ...fieldStyle, resize: 'vertical', fontFamily: 'inherit', borderColor: errors.project ? '#e03' : undefined }} />
                </div>
                <div style={{ display: 'flex', alignItems: 'center', gap: 10, marginTop: 4 }}>
                  <input ref={ndaRef} type="checkbox" id="nda" defaultChecked style={{ width: 16, height: 16, accentColor: BS.accent }} />
                  <label htmlFor="nda" style={{ fontSize: 13, color: BS.text2 }}>Send me an NDA template alongside the quote.</label>
                </div>
                <button type="submit" disabled={sending} style={{
                  ...bsStyles.btnAccent, padding: '16px 22px', fontSize: 15, fontWeight: 700,
                  marginTop: 8, justifyContent: 'center',
                  opacity: sending ? 0.7 : 1, cursor: sending ? 'wait' : 'pointer',
                }}>
                  {sending ? 'Sending…' : 'Send brief'}
                  {!sending && (
                    <span style={{
                      width: 26, height: 26, borderRadius: '50%', background: '#fff',
                      color: BS.accent, display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
                    }}>
                      <svg width="12" height="12" viewBox="0 0 12 12" fill="none"><path d="M1 6h10M7 2l4 4-4 4" stroke="currentColor" strokeWidth="1.6" /></svg>
                    </span>
                  )}
                </button>
                {sendError && (
                  <div style={{ fontSize: 13, color: '#e03', marginTop: 8, textAlign: 'center' }}>{sendError}</div>
                )}
                <div style={{ fontSize: 12, color: BS.muted, textAlign: 'center', marginTop: 4 }}>
                  By submitting, you agree to our privacy policy. We never share your brief.
                </div>
              </>
            )}
          </form>
        </div>
      </div>
    </section>
  );
}

const fieldStyle = {
  width: '100%', padding: '12px 14px',
  borderRadius: 10, border: `1px solid #e8e2d5`,
  fontSize: 14, fontFamily: 'inherit', background: '#fafaf7',
  outline: 'none', transition: 'border 0.15s',
};
function Field({ label, placeholder, type = 'text', fieldRef, error }) {
  return (
    <div>
      <label style={{ fontSize: 12, fontWeight: 700, color: error ? '#e03' : BS.muted, display: 'block', marginBottom: 6, letterSpacing: '0.04em', textTransform: 'uppercase' }}>
        {label}
      </label>
      <input ref={fieldRef} type={type} placeholder={placeholder}
        style={{ ...fieldStyle, borderColor: error ? '#e03' : undefined }}
        onFocus={e => e.currentTarget.style.borderColor = BS.accent}
        onBlur={e => e.currentTarget.style.borderColor = error ? '#e03' : BS.border}
      />
    </div>
  );
}

function ContactOffices() {
  const offices = [
    { city: 'New Delhi', country: 'India',          hours: 'Mon–Sat · 09:00 — 21:00 IST', phone: 'mail@thebimace.com',  tag: 'Studio HQ',   isEmail: true },
    { city: 'USA',       country: 'United States',  hours: 'Mon–Fri · 09:00 — 18:00 EST', phone: '+1 (631) 464-0144',   tag: 'US liaison',  isEmail: false },
  ];
  const { w } = useViewport();
  return (
    <section style={{ padding: pick(w, '100px 0', '64px 0'), background: BS.bg3 }}>
      <div style={bsStyles.container}>
        <SectionHeader
          eyebrow="Offices"
          title={<>Two locations.<br />One studio.</>}
          align="split"
          lede="Our studio is in New Delhi. A US liaison line keeps us close to North American clients."
        />
        <div style={{ display: 'grid', gridTemplateColumns: pick(w, 'repeat(2, 1fr)', '1fr'), gap: 20 }}>
          {offices.map(o => (
            <div key={o.city} style={{
              background: BS.bg2, border: `1px solid ${BS.border}`,
              borderRadius: 20, padding: pick(w, 36, 24),
            }}>
              <div style={{
                display: 'inline-block', fontSize: 10, fontWeight: 700,
                letterSpacing: '0.08em', textTransform: 'uppercase',
                background: BS.accent, color: '#fff',
                padding: '4px 10px', borderRadius: 999, marginBottom: 22,
              }}>{o.tag}</div>
              <h3 style={{ ...bsStyles.display, fontSize: fs(30, 44), margin: 0, marginBottom: 4 }}>{o.city}</h3>
              <div style={{ fontSize: 14, color: BS.muted, marginBottom: 28 }}>{o.country}</div>
              <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 24, paddingTop: 22, borderTop: `1px solid ${BS.border}` }}>
                <div>
                  <div style={{ fontSize: 11, color: BS.muted, marginBottom: 6, fontWeight: 600, letterSpacing: '0.06em', textTransform: 'uppercase' }}>Hours</div>
                  <div style={{ fontSize: 13.5, fontWeight: 600 }}>{o.hours}</div>
                </div>
                <div>
                  <div style={{ fontSize: 11, color: BS.muted, marginBottom: 6, fontWeight: 600, letterSpacing: '0.06em', textTransform: 'uppercase' }}>{o.isEmail ? 'Email' : 'Phone'}</div>
                  <a href={o.isEmail ? `mailto:${o.phone}` : `tel:${o.phone}`} style={{ fontSize: 13.5, fontWeight: 700, color: BS.accent, textDecoration: 'none' }}>{o.phone}</a>
                </div>
              </div>
            </div>
          ))}
        </div>
      </div>
    </section>
  );
}

function ContactFAQ() {
  const [open, setOpen] = React.useState(0);
  const { w } = useViewport();
  return (
    <section style={{ padding: pick(w, '120px 0', '72px 0') }}>
      <div style={bsStyles.container}>
        <SectionHeader
          eyebrow="FAQ"
          title={<>Things people<br />ask first.</>}
          align="split"
        />
        <div style={{ maxWidth: 880, margin: '0 auto' }}>
          {FAQ.map((f, i) => (
            <div key={i} style={{
              borderTop: i === 0 ? `1px solid ${BS.border2}` : 'none',
              borderBottom: `1px solid ${BS.border2}`,
            }}>
              <button onClick={() => setOpen(open === i ? -1 : i)} style={{
                width: '100%', padding: '24px 0',
                background: 'none', border: 0, textAlign: 'left', cursor: 'pointer',
                display: 'flex', justifyContent: 'space-between', alignItems: 'center', gap: 24,
                fontFamily: 'inherit', color: BS.text,
              }}>
                <span style={{ fontSize: 19, fontWeight: 700 }}>{f.q}</span>
                <span style={{
                  width: 32, height: 32, borderRadius: '50%',
                  border: `1px solid ${BS.border2}`,
                  display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
                  background: open === i ? BS.accent : 'transparent',
                  color: open === i ? '#fff' : BS.text,
                  transition: 'all 0.18s', flexShrink: 0,
                }}>
                  <svg width="14" height="14" viewBox="0 0 14 14" fill="none" style={{ transform: open === i ? 'rotate(45deg)' : 'none', transition: 'transform 0.18s' }}>
                    <path d="M7 1v12M1 7h12" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round" />
                  </svg>
                </span>
              </button>
              {open === i && (
                <div style={{
                  paddingBottom: 24, paddingRight: pick(w, 60, 0),
                  fontSize: 15, color: BS.text2, lineHeight: 1.65,
                }}>{f.a}</div>
              )}
            </div>
          ))}
        </div>
      </div>
    </section>
  );
}

function ContactPage() {
  return (
    <Page currentPage="contact">
      <ContactHero />
      <ContactForm />
      <ContactOffices />
      <ContactFAQ />
    </Page>
  );
}

window.ContactPage = ContactPage;
