const { TopNav, Footer, Button, Card, Icon, SectionHeading, Input, Select, Textarea, Checkbox, GlowPanel, Badge } = window[Object.keys(window).find(k => k.startsWith('DesignSystem_'))];
const TOPICS = [
  { value: 'use', label: 'What I want to do with structured light', prompt: 'What are you trying to do with structured light?' },
  { value: 'modes', label: 'Which modes I need', prompt: 'Which modes or beam profiles are you interested in?' },
  { value: 'questions', label: 'A general question', prompt: 'What would you like to know?' },
  { value: 'quote', label: 'Request a quote', prompt: 'Tell us about your setup, quantity and timeline.' },
  { value: 'notify', label: 'Notify me when a product launches', prompt: 'Which product would you like to hear about?' }
];
// Where enquiries go: the contact backend in /server. Its address is set in
// config.js (serverUrl), since `process.env` does not exist in the browser.
// If `endpoint` is empty the form opens a pre-filled email to `email` instead.
console.log('SITE_CONFIG:'+window.SITE_CONFIG)
const SERVER_URL = ((window.SITE_CONFIG && window.SITE_CONFIG.serverUrl) || '').replace(/\/+$/, '');
const CONTACT = { endpoint: SERVER_URL + '/api/contact', email: '' };

const AREAS = ['Microscopy & imaging', 'Optical communications', 'Metrology & sensing', 'Materials processing', 'Research & teaching', 'Something else'];
const EMPTY = { name: '', email: '', organisation: '', area: AREAS[0], topic :'', message: '', datasheet: true, website: '' };
const EMAIL_RE = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;

function validate(f) {
  const e = {};
  if (!f.name.trim()) e.name = 'Tell us who you are.';
  if (!f.email.trim()) e.email = 'We need an address to reply to.';
  else if (!EMAIL_RE.test(f.email.trim())) e.email = 'That does not look like an email address.';
  if (f.message.trim().length < 10) e.message = 'A sentence or two about the measurement, please.';
  return e;
}

async function deliver(f) {
  const body = { name: f.name.trim(), email: f.email.trim(), organisation: f.organisation.trim(), area: f.area, topic:f.topic, message: f.message.trim(), datasheet: f.datasheet };
  console.log('Endpoint'+CONTACT.endpoint)
  if (CONTACT.endpoint) {
    const res = await fetch(CONTACT.endpoint, { method: 'POST', headers: { 'Content-Type': 'application/json', Accept: 'application/json' }, body: JSON.stringify(body) });
    if (res.status === 400) {
      const data = await res.json().catch(() => ({}));
      if (data.errors) throw Object.assign(new Error('Rejected by server'), { fieldErrors: data.errors });
    }
    if (!res.ok) throw new Error('Status ' + res.status);
    return;
  }
  if (CONTACT.email) {
    const text = [body.message, '', '—', body.name + (body.organisation ? ', ' + body.organisation : ''), body.email, 'Area: ' + body.area, body.datasheet ? 'Please send the Lightweaver datasheet.' : ''].join('\n');
    window.location.href = 'mailto:' + CONTACT.email + '?subject=' + encodeURIComponent('Enquiry: ' + body.area) + '&body=' + encodeURIComponent(text);
    return;
  }
  throw new Error('Contact form is not connected: set CONTACT.endpoint or CONTACT.email in Contact.jsx');
}

function Contact({ onNavigate }) {
  const [topic, setTopic] = React.useState(() => { const t = window.__contactTopic || 'use'; window.__contactTopic = null; return t; });
  const prompt = (TOPICS.find((t) => t.value === topic) || TOPICS[0]).prompt;
  const [form, setForm] = React.useState(EMPTY);
  const [errors, setErrors] = React.useState({});
  const [status, setStatus] = React.useState('idle'); // idle | sending | sent | failed
  const set = (k) => (e) => {
    const v = e.target.type === 'checkbox' ? e.target.checked : e.target.value;
    setForm((f) => ({ ...f, [k]: v }));
    if (errors[k]) setErrors((er) => ({ ...er, [k]: undefined }));
  };

  const submit = async (e) => {
    e.preventDefault();
    if (form.website) { setStatus('sent'); return; } // honeypot: bots fill hidden fields
    const er = validate(form);
    setErrors(er);
    if (Object.keys(er).length) return;
    setStatus('sending');
    try {
      await deliver(form);
      setStatus('sent');
      setForm(EMPTY);
    } catch (err) {
      if (err.fieldErrors) { setErrors(err.fieldErrors); setStatus('idle'); return; }
      console.error(err);
      setStatus('failed');
    }
  };

  const label = { fontFamily: 'var(--font-display)', fontSize: 11, fontWeight: 600, letterSpacing: '.22em', textTransform: 'uppercase', color: 'var(--text-muted)' };
  const set_send_topic = (e) => {
    setTopic(e.target.value);
    set('topic')(e);
  };

  return (
    <div>
      <TopNav base="../../" active="Contact" onNavigate={onNavigate} bordered />
      <section style={{ padding: 'var(--space-section) 0' }}>
        <div style={{ maxWidth: 'var(--container-max)', margin: '0 auto', padding: '0 var(--gutter)', display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(320px, 1fr))', gap: 'var(--space-huge)' }}>
          <div>
            <SectionHeading eyebrow="Contact" title="Tell us what you need the light to do" level={1} />
            <p style={{ margin: 'var(--space-md) 0 0', maxWidth: '40ch', fontSize: 'var(--type-body-size)', lineHeight: 'var(--type-body-lh)', color: 'var(--text-secondary)' }}>Describe the measurement, not the optics. We will tell you which mode gets you there.</p>
            <div style={{ marginTop: 'var(--space-xl)', display: 'flex', flexDirection: 'column', gap: 'var(--space-md)' }}>
              {[
                { t: 'Quotes', b: 'Lightweaver pricing, lead times and configurations.' },
                { t: 'Applications', b: 'Whether structured light fits your experiment or product.' },
                { t: 'Collaboration', b: 'Research partnerships with the Structured Light Laboratory.' }
              ].map((c) => (
                <div key={c.t}>
                  <div style={label}>{c.t}</div>
                  <p style={{ margin: '4px 0 0', fontSize: 'var(--type-body-sm-size)', lineHeight: 1.7, color: 'var(--text-secondary)' }}>{c.b}</p>
                </div>
              ))}
            </div>
            <div style={{ marginTop: 'var(--space-xl)', display: 'flex', gap: 8, flexWrap: 'wrap' }}>
              <Badge variant="outline" mono>JOHANNESBURG</Badge><Badge variant="outline" mono>WITS SCHOOL OF PHYSICS</Badge>
            </div>
          </div>
          {status === 'sent' ? (
            <GlowPanel padding="var(--space-xxl)" style={{ alignSelf: 'start' }}>
              <span style={{ color: 'var(--ok)' }}><Icon name="check" size={22} /></span>
              <h2 style={{ margin: 'var(--space-md) 0 var(--space-xs)', fontFamily: 'var(--font-display)', fontSize: 22, fontWeight: 600, color: 'var(--text-primary)' }}>Enquiry sent</h2>
              <p style={{ margin: 0, fontSize: 15, color: 'var(--text-secondary)' }}>We will come back to you with a mode recommendation.</p>
              <div style={{ marginTop: 'var(--space-lg)' }}><Button variant="secondary" onClick={() => setStatus('idle')}>Send another</Button></div>
            </GlowPanel>
          ) : (
            <Card variant="panel">
              <form onSubmit={submit} noValidate style={{ display: 'flex', flexDirection: 'column', gap: 'var(--space-md)' }}>
                <Input label="Name" placeholder="Your name" autoComplete="name" required value={form.name} onChange={set('name')} error={errors.name} />
                <Input label="Work email" type="email" placeholder="you@lab.ac.za" autoComplete="email" required value={form.email} onChange={set('email')} error={errors.email} />
                <Input label="Organisation" placeholder="University, company or lab (optional)" autoComplete="organization" value={form.organisation} onChange={set('organisation')} />
                <Select label="Area" options={AREAS} value={form.area} onChange={set('area')} />
                {/*<div style={{ display: 'flex', flexDirection: 'column', gap: 'var(--space-xs)' }}>
                //  <Textarea label="What are you trying to do with structured light?" rows={5} required value={form.message} onChange={set('message')} aria-invalid={!!errors.message} />
                //  {errors.message && <span style={{ fontSize: 12.5, color: 'var(--err)' }}>{errors.message}</span>}
                </div> */}
                <Select label="I would like to talk about" options={TOPICS} value={topic} onChange={set_send_topic} />
                <Textarea label={prompt} rows={4} required value={form.message} onChange={set('message')} aria-invalid={!!errors.message}/>
		{errors.message && <span style={{ fontSize: 12.5, color: 'var(--err)' }}>{errors.message}</span>}
                <Checkbox label="Send me the Lightweaver datasheet" checked={form.datasheet} onChange={set('datasheet')} />
                <input type="text" name="website" tabIndex={-1} autoComplete="off" aria-hidden="true" value={form.website} onChange={set('website')}
                  style={{ position: 'absolute', left: '-10000px', width: 1, height: 1, opacity: 0 }} />
                {status === 'failed' && (
                  <p role="alert" style={{ margin: 0, fontSize: 14, color: 'var(--err)' }}>Your enquiry did not go through. Please try again in a moment.</p>
                )}
                <div><Button type="submit" disabled={status === 'sending'}>{status === 'sending' ? 'Sending…' : 'Send enquiry'}</Button></div>
              </form>
            </Card>
          )}
        </div>
      </section>
      <Footer base="../../" />
    </div>
  );
}

window.Contact = Contact;
