// Contact page + unified form
const { useState: useStateC } = React;

const FORMSPREE = 'https://formspree.io/f/mzdyozyr';

function UnifiedContactForm() {
  const fields = [
    { name: 'name', label: 'Full Name', placeholder: 'Your full name', required: true },
    { name: 'email', label: 'Email Address', type: 'email', placeholder: 'your@email.com', required: true },
    { name: 'organisation', label: 'Organisation', placeholder: 'Company, agency, or fund name', required: true },
    { name: 'enquiryType', label: 'Enquiry Type', type: 'select', required: true,
      options: ['Enterprise Security', 'Government & Defence', 'Investment Enquiry', 'Strategic Partnership', 'General Enquiry', 'Other'] },
    { name: 'message', label: 'Message', type: 'textarea', placeholder: 'Please describe your enquiry', required: true },
  ];

  const [data, setData] = useStateC(fields.reduce((a, f) => { a[f.name] = ''; return a; }, {}));
  const [errors, setErrors] = useStateC({});
  const [status, setStatus] = useStateC('idle');

  const setField = (n, v) => { setData((d) => ({ ...d, [n]: v })); if (errors[n]) setErrors((e) => ({ ...e, [n]: '' })); };

  const handleSubmit = async (e) => {
    e.preventDefault();
    const errs = {};
    fields.forEach((f) => {
      if (f.required && !data[f.name].trim()) errs[f.name] = 'Required';
      if (f.type === 'email' && data[f.name] && !/^[^@\s]+@[^@\s]+\.[^@\s]+$/.test(data[f.name])) errs[f.name] = 'Invalid email';
    });
    setErrors(errs);
    if (Object.keys(errs).length) return;

    setStatus('submitting');
    try {
      const res = await fetch(FORMSPREE, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json', Accept: 'application/json' },
        body: JSON.stringify({
          _subject: `QDI Enquiry — ${data.enquiryType || 'General'}`,
          _replyto: data.email,
          _to: 'grant.jay@quantumdefenseinnovation.com',
          ...data,
        }),
      });
      setStatus(res.ok ? 'success' : 'error');
    } catch {
      setStatus('error');
    }
  };

  if (status === 'success') {
    return (
      <div style={{ textAlign: 'center', padding: '64px 16px' }}>
        <div style={{
          width: 56, height: 56, borderRadius: '50%', margin: '0 auto 24px',
          background: 'var(--accent-dim)', color: 'var(--accent-bright)',
          display: 'flex', alignItems: 'center', justifyContent: 'center',
        }}>
          <svg width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M5 12l5 5L20 7" /></svg>
        </div>
        <div style={{ fontSize: 18, fontWeight: 500, color: 'var(--accent-bright)', letterSpacing: '-0.01em', lineHeight: 1.5, maxWidth: 480, margin: '0 auto' }}>
          Thank you. Your enquiry has been received and will be responded to shortly.
        </div>
      </div>
    );
  }

  return (
    <form onSubmit={handleSubmit} noValidate style={{ display: 'flex', flexDirection: 'column', gap: 16 }}>
      {fields.map((f) => (
        <div key={f.name}>
          <label style={{ display: 'block', fontSize: 10, fontWeight: 500, color: 'var(--accent-bright)', marginBottom: 8, letterSpacing: '0.2em', textTransform: 'uppercase' }}>
            {f.label}{f.required && <span style={{ color: 'var(--accent-bright)', marginLeft: 4 }}>*</span>}
          </label>
          {f.type === 'textarea' ? (
            <textarea
              name={f.name} value={data[f.name]} onChange={(e) => setField(f.name, e.target.value)}
              placeholder={f.placeholder} rows={5}
              style={{ ...inputStyle, height: 'auto', padding: '14px 14px', resize: 'vertical', minHeight: 140 }}
            />
          ) : f.type === 'select' ? (
            <select name={f.name} value={data[f.name]} onChange={(e) => setField(f.name, e.target.value)} style={inputStyle}>
              <option value="">Select an option…</option>
              {f.options.map((o) => <option key={o} value={o}>{o}</option>)}
            </select>
          ) : (
            <input
              name={f.name} type={f.type || 'text'} value={data[f.name]}
              onChange={(e) => setField(f.name, e.target.value)} placeholder={f.placeholder} style={inputStyle}
            />
          )}
          {errors[f.name] && <div style={{ color: '#ff7a85', fontSize: 11, marginTop: 6, letterSpacing: '0.04em' }}>{errors[f.name]}</div>}
        </div>
      ))}
      <button type="submit" disabled={status === 'submitting'} style={{
        width: '100%', height: 48, borderRadius: 8,
        background: 'var(--accent-bright)', color: '#fff', border: 'none',
        fontFamily: "'IBM Plex Sans', sans-serif", fontSize: 14, fontWeight: 500, letterSpacing: '0.02em',
        cursor: 'pointer', marginTop: 8,
        boxShadow: '0 8px 24px rgba(14,158,136,0.28)',
        transition: 'transform 0.15s, box-shadow 0.25s',
      }}>
        {status === 'submitting' ? 'Sending…' : 'Send Enquiry'}
      </button>
      {status === 'error' && (
        <div style={{ marginTop: 4, fontSize: 13, color: '#ffb347', textAlign: 'center', fontWeight: 400 }}>
          Something went wrong. Please try again or email us directly.
        </div>
      )}
    </form>
  );
}

const inputStyle = {
  width: '100%', height: 48, padding: '0 14px', borderRadius: 8,
  border: '1px solid var(--border)', background: 'var(--input-bg)', color: 'var(--text)',
  fontFamily: "'IBM Plex Sans', sans-serif", fontSize: 14, fontWeight: 400, outline: 'none',
  transition: 'border-color 0.2s', boxSizing: 'border-box',
};

function ContactPage() {
  return (
    <div style={{ position: 'relative', zIndex: 2, padding: '140px 40px 120px' }}>
      <div style={{ maxWidth: 1280, margin: '0 auto' }}>
        <div style={{ textAlign: 'center', marginBottom: 64, maxWidth: 820, marginLeft: 'auto', marginRight: 'auto' }}>
          <div style={{ display: 'flex', justifyContent: 'center', marginBottom: 24 }}>
            <Eyebrow>Get in Touch</Eyebrow>
          </div>
          <h1 style={{ fontSize: 'clamp(48px, 6vw, 80px)', fontWeight: 600, margin: 0, marginBottom: 24, lineHeight: 1.02, letterSpacing: '-0.035em', color: 'var(--text)' }}>
            Contact & <em style={{ fontWeight: 400, fontStyle: 'italic', color: 'var(--text-soft)' }}>Enquiries</em>.
          </h1>
          <p style={{ fontSize: 16, fontWeight: 400, color: 'var(--text-soft)', lineHeight: 1.6, margin: 0 }}>
            We welcome enquiries from enterprise operators, government agencies, defence organisations, and qualified investors. All materials are shared under NDA on request.
          </p>
        </div>

        <div style={{ maxWidth: 640, margin: '0 auto' }}>
          <Card style={{ padding: 48 }}>
            <h2 style={{ fontSize: 28, fontWeight: 600, margin: 0, marginBottom: 10, letterSpacing: '-0.02em', color: 'var(--text)', textAlign: 'center' }}>
              Send an Enquiry
            </h2>
            <p style={{ fontSize: 13, fontWeight: 400, color: 'var(--text-muted)', margin: '0 0 32px', lineHeight: 1.6, textAlign: 'center' }}>
              All enquiries are welcome — enterprise, government, investment, and partnership. We respond to every message.
            </p>
            <Rule style={{ marginBottom: 32 }} />
            <UnifiedContactForm />
          </Card>

          <div style={{
            marginTop: 40, textAlign: 'center',
            fontSize: 14, fontWeight: 400, letterSpacing: '0.02em', lineHeight: 1.7,
          }}>
            <div style={{
              fontSize: 11, fontWeight: 500, color: 'var(--accent-bright)',
              letterSpacing: '0.22em', textTransform: 'uppercase', marginBottom: 10,
            }}>
              Partnership, Investment & All Enquiries — Contact
            </div>
            <a
              href="mailto:grant.jay@quantumdefenseinnovation.com"
              style={{
                color: '#f0f4f8', textDecoration: 'none',
                transition: 'color 0.2s, text-decoration-color 0.2s',
                textDecorationColor: 'transparent',
              }}
              onMouseEnter={(e) => { e.currentTarget.style.color = 'var(--accent-bright)'; e.currentTarget.style.textDecoration = 'underline'; e.currentTarget.style.textDecorationColor = 'var(--accent-bright)'; }}
              onMouseLeave={(e) => { e.currentTarget.style.color = '#f0f4f8'; e.currentTarget.style.textDecoration = 'none'; }}
            >
              grant.jay@quantumdefenseinnovation.com
            </a>
          </div>
        </div>
      </div>
    </div>
  );
}

Object.assign(window, { ContactPage });
