const { Eyebrow, Input, Textarea, Select, Checkbox, Button, Card } = window.IndigoAdvisoryDesignSystem_fba97f;

const gutter = { paddingLeft: 'var(--gutter)', paddingRight: 'var(--gutter)' };
const wrap = { maxWidth: 'var(--container)', margin: '0 auto' };

function ContactScreen() {
  const [sent, setSent] = React.useState(false);
  const [busy, setBusy] = React.useState(false);
  const [err, setErr] = React.useState('');
  const [consent, setConsent] = React.useState(true);
  const ENDPOINT = window.CONTACT_ENDPOINT || '/api/contact';

  async function submit(e) {
    e.preventDefault();
    const f = new FormData(e.target);
    const payload = {
      name: f.get('name') || '',
      company: f.get('company') || '',
      email: f.get('email') || '',
      inquiry_type: f.get('inquiry_type') || 'Other',
      message: f.get('message') || '',
      consent: consent,
      website: f.get('website') || '',
    };
    if (!payload.consent) { setErr('Please agree to be contacted.'); return; }
    setErr(''); setBusy(true);
    try {
      const r = await fetch(ENDPOINT, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(payload) });
      const data = await r.json().catch(() => ({}));
      if (!r.ok) throw new Error(data.error || Object.values(data.errors || {})[0] || 'Something went wrong.');
      setSent(true);
    } catch (e2) {
      setErr(e2.message === 'Failed to fetch' ? 'Could not reach the server. Please try again.' : e2.message);
    } finally {
      setBusy(false);
    }
  }

  return (
    <section style={{ ...gutter, paddingTop: 'var(--space-9)', paddingBottom: 'var(--space-10)' }}>
      <div style={{ ...wrap, display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 'var(--space-9)', alignItems: 'start' }}>
        <div>
          <Eyebrow>Contact</Eyebrow>
          <h1 style={{ fontFamily: 'var(--font-display)', fontSize: 'var(--fs-h1)', fontWeight: 'var(--fw-med)', letterSpacing: 'var(--ls-tight)', lineHeight: 'var(--lh-tight)', margin: 'var(--space-4) 0 0', color: 'var(--text-primary)' }}>
            Start a conversation<span style={{ color: 'var(--accent)' }}>.</span>
          </h1>
          <p style={{ fontFamily: 'var(--font-body)', fontSize: 'var(--fs-lead)', fontWeight: 'var(--fw-light)', lineHeight: 'var(--lh-normal)', color: 'var(--text-secondary)', margin: 'var(--space-5) 0 var(--space-7)', maxWidth: 420 }}>
            Tell us what you're working on. A principal will reply — not a form autoresponder.
          </p>
          <div style={{ display: 'flex', flexDirection: 'column', gap: 'var(--space-4)' }}>
            {[['Dubai', 'DIFC'], ['London', 'Mayfair'], ['Hong Kong', 'Central'], ['Mumbai', 'BKC']].map(([c, d]) => (
              <div key={c} style={{ display: 'flex', justifyContent: 'space-between', maxWidth: 320, borderBottom: '1px solid var(--border-subtle)', paddingBottom: 'var(--space-2)' }}>
                <span style={{ fontFamily: 'var(--font-display)', fontSize: 'var(--fs-h4)', fontWeight: 'var(--fw-med)', color: 'var(--text-primary)' }}>{c}</span>
                <span style={{ fontFamily: 'var(--font-mono)', fontSize: 'var(--fs-xs)', color: 'var(--text-muted)', alignSelf: 'flex-end' }}>{d}</span>
              </div>
            ))}
          </div>
        </div>

        <Card padded style={{ padding: 'var(--space-7)' }}>
          {sent ? (
            <div style={{ padding: 'var(--space-6) 0', textAlign: 'center' }}>
              <div style={{ fontFamily: 'var(--font-display)', fontSize: 'var(--fs-h3)', fontWeight: 'var(--fw-med)', color: 'var(--text-primary)' }}>Thank you.</div>
              <p style={{ fontFamily: 'var(--font-body)', fontSize: 'var(--fs-sm)', color: 'var(--text-secondary)', marginTop: 'var(--space-3)' }}>We'll be in touch shortly.</p>
              <Button variant="link" onClick={() => setSent(false)} style={{ marginTop: 'var(--space-4)' }}>Send another</Button>
            </div>
          ) : (
            <form onSubmit={submit} style={{ display: 'flex', flexDirection: 'column', gap: 'var(--space-4)' }}>
              <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 'var(--space-4)' }}>
                <Input label="Name" name="name" placeholder="Your name" required />
                <Input label="Company" name="company" placeholder="Company" />
              </div>
              <Input label="Work email" name="email" type="email" placeholder="you@company.com" required />
              <Select label="Inquiry type" name="inquiry_type" options={['Capital raise', 'M&A advisory', 'Deal structuring', 'Investment', 'Other']} />
              <Textarea label="What are you working on?" name="message" rows={4} placeholder="A few lines is plenty." />
              <input type="text" name="website" tabIndex={-1} autoComplete="off" aria-hidden="true" style={{ position: 'absolute', left: '-9999px', width: 1, height: 1, opacity: 0 }} />
              <Checkbox label="I agree to be contacted about my inquiry." checked={consent} onChange={(e) => setConsent(e.target.checked)} />
              {err ? <p style={{ fontFamily: 'var(--font-body)', fontSize: 'var(--fs-sm)', color: 'var(--accent)', margin: 0 }}>{err}</p> : null}
              <Button variant="solid" size="lg" block type="submit" disabled={busy} style={{ marginTop: 'var(--space-2)' }}>{busy ? 'Sending…' : 'Send'}</Button>
            </form>
          )}
        </Card>
      </div>
    </section>
  );
}

Object.assign(window, { ContactScreen });
