// Contact + Footer + Sticky CTA
const Contact = () => {
  const t = CONTENT.contact;
  const [form, setForm] = React.useState({ name: '', email: '', phone: '', service: 0, property: 0, msg: '' });
  const [sent, setSent] = React.useState(false);
  const [sending, setSending] = React.useState(false);
  const [sendError, setSendError] = React.useState('');
  const [fieldErrors, setFieldErrors] = React.useState({});
  const set = (k, v) => setForm(f => ({ ...f, [k]: v }));

  const validate = () => {
    const errors = {};
    if (!form.name.trim()) errors.name = 'Name is required';
    if (!form.email.trim()) {
      errors.email = 'Email is required';
    } else if (!/^[^\s@]+@[^\s@]+\.[^\s@]{2,}$/.test(form.email)) {
      errors.email = 'Enter a valid email address';
    }
    if (!form.phone.trim()) {
      errors.phone = 'Phone is required';
    } else if (!/^\+?[\d\s\-\(\)]{7,20}$/.test(form.phone)) {
      errors.phone = 'Numbers only (e.g. +971 50 446 9392)';
    }
    return errors;
  };

  const onSubmit = async (e) => {
    e.preventDefault();
    const errors = validate();
    if (Object.keys(errors).length) { setFieldErrors(errors); return; }
    setFieldErrors({});
    if (sending || sent) return;
    setSending(true);
    setSendError('');
    try {
      let recaptchaToken = '';
      const siteKey = window.__RECAPTCHA_SITE_KEY__;
      if (window.grecaptcha && siteKey) {
        recaptchaToken = await window.grecaptcha.execute(siteKey, { action: 'contact' });
      }
      const res = await fetch('/api/send', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          name: form.name.trim(),
          email: form.email.trim(),
          phone: form.phone.trim(),
          service: t.services[form.service],
          property: t.propertyTypes[form.property],
          msg: form.msg.trim(),
          honeypot: '',
          recaptchaToken,
        }),
      });
      if (res.ok) {
        setSent(true);
      } else {
        const data = await res.json().catch(() => ({}));
        setSendError(data.error || 'Failed to send. Please call us directly.');
      }
    } catch {
      setSendError('Failed to send. Please call us directly.');
    } finally {
      setSending(false);
    }
  };

  return (
    <section id="contact" style={{ background: 'var(--bg-2)' }}>
      <div className="container">
        <div className="section-head" style={{ maxWidth: 720 }}>
          <div className="eyebrow"><span className="dot">●</span>{t.eyebrow}</div>
          <h2 style={{ fontFamily: 'var(--font-display)', fontSize: 'clamp(28px, 3.5vw, 40px)', fontWeight: 600, lineHeight: 1.1, letterSpacing: '-0.01em', margin: '8px 0 12px' }}>{t.h}</h2>
          <p style={{ color: 'var(--ink-2)', margin: 0 }}>{t.sub}</p>
        </div>

        <div className="contact-grid">
          <div className="contact-info">
            <a className="contact-row" href={`tel:${CONTENT.phoneTel}`}>
              <div>
                <div className="ck">Call · 24/7</div>
                <div className="cv">{CONTENT.phone}</div>
              </div>
              <span className="arrow">→</span>
            </a>
            <a className="contact-row" href={`https://wa.me/${CONTENT.whatsapp.replace(/\D/g,'')}`}>
              <div>
                <div className="ck">WhatsApp</div>
                <div className="cv">{CONTENT.phone}</div>
              </div>
              <span className="arrow">→</span>
            </a>
            <a className="contact-row" href={`mailto:${CONTENT.email}`}>
              <div>
                <div className="ck">Email</div>
                <div className="cv" style={{ fontSize: 16 }}>{CONTENT.email}</div>
              </div>
              <span className="arrow">→</span>
            </a>
            <div className="contact-row" style={{ cursor: 'default' }}>
              <div>
                <div className="ck">Location</div>
                <div className="cv">{CONTENT.location}</div>
              </div>
            </div>
          </div>

          {sent ? (
            <div className="cf-success" style={{ display: 'flex', alignItems: 'center', justifyContent: 'center', textAlign: 'center', minHeight: 320, fontSize: 18 }}>
              {t.success || 'Thank you! We\'ll respond within 24 hours.'}
            </div>
          ) : (
            <form className="contact-form" onSubmit={onSubmit} noValidate>
              {/* Honeypot — hidden from real users, bots fill it */}
              <input type="text" name="honeypot" style={{ display: 'none' }} tabIndex={-1} autoComplete="off" />
              {sendError && <div style={{ color: '#E8651F', fontSize: 14, marginBottom: 12 }}>{sendError}</div>}
              <div className="cf-row">
                <div className="cf-field">
                  <label>Full Name</label>
                  <input value={form.name} onChange={e => set('name', e.target.value)} placeholder="Your name" />
                  {fieldErrors.name && <span style={{ color: '#E8651F', fontSize: 12 }}>{fieldErrors.name}</span>}
                </div>
                <div className="cf-field">
                  <label>Phone</label>
                  <input value={form.phone} onChange={e => set('phone', e.target.value.replace(/[^\d\s\+\-\(\)]/g, ''))} placeholder="+971 50 …" inputMode="tel" />
                  {fieldErrors.phone && <span style={{ color: '#E8651F', fontSize: 12 }}>{fieldErrors.phone}</span>}
                </div>
              </div>
              <div className="cf-field">
                <label>Email</label>
                <input type="email" value={form.email} onChange={e => set('email', e.target.value)} placeholder="you@example.com" />
                {fieldErrors.email && <span style={{ color: '#E8651F', fontSize: 12 }}>{fieldErrors.email}</span>}
              </div>
              <div className="cf-row">
                <div className="cf-field">
                  <label>Service Needed</label>
                  <select value={form.service} onChange={e => set('service', e.target.value)}>
                    {t.services.map((s,i)=> <option key={i} value={i} style={{ background: 'var(--bg)' }}>{s}</option>)}
                  </select>
                </div>
                <div className="cf-field">
                  <label>Property Type</label>
                  <select value={form.property} onChange={e => set('property', e.target.value)}>
                    {t.propertyTypes.map((s,i)=> <option key={i} value={i} style={{ background: 'var(--bg)' }}>{s}</option>)}
                  </select>
                </div>
              </div>
              <div className="cf-field">
                <label>Project Details</label>
                <textarea rows={3} value={form.msg} onChange={e => set('msg', e.target.value)} placeholder="Brief description of the work, location, urgency…" />
              </div>
              <div className="cf-foot">
                <span className="cf-note">{t.note}</span>
                <button type="submit" className="btn btn-primary" disabled={sending}>{sending ? 'Sending…' : `${t.submit} →`}</button>
              </div>
            </form>
          )}
        </div>
      </div>
    </section>
  );
};
window.Contact = Contact;

const Footer = () => {
  const t = CONTENT.footer;
  return (
    <footer className="footer">
      <div className="container">
        <div className="footer-row">
          <div className="footer-col">
            <img src="assets/IMG_4834.svg" alt="Forgefix" style={{ height: 80, width: 'auto', marginBottom: 12 }} />
            <p style={{ color: 'var(--ink-2)', fontSize: 14, maxWidth: 320, margin: 0 }}>{t.desc}</p>
          </div>
          <div className="footer-col">
            <h5>Services</h5>
            <ul>{CONTENT.services.items.map(s => <li key={s.name}><a href="#services">{s.name}</a></li>)}</ul>
          </div>
          <div className="footer-col">
            <h5>Company</h5>
            <ul>{t.company.map(c => <li key={c}><a href="#">{c}</a></li>)}</ul>
          </div>
          <div className="footer-col">
            <h5>Contact</h5>
            <ul>
              <li><a href={`tel:${CONTENT.phoneTel}`}>{CONTENT.phone}</a></li>
              <li><a href={`mailto:${CONTENT.email}`}>{CONTENT.email}</a></li>
              <li><a href="#">WhatsApp</a></li>
              <li>{CONTENT.location}</li>
            </ul>
          </div>
        </div>
        <div className="footer-bottom">
          <span className="footer-rights">{t.rights}</span>
          <div className="footer-legal">
            {t.legal.map(l => <a key={l} href="#">{l}</a>)}
          </div>
        </div>
      </div>
    </footer>
  );
};
window.Footer = Footer;

const StickyCta = () => (
  <div className="sticky-cta">
    <a href={`tel:${CONTENT.phoneTel}`} className="call">Call</a>
    <a href="#contact" className="quote">Get a Quote →</a>
  </div>
);
window.StickyCta = StickyCta;
