/* contact.jsx — Simple single-step contact form (dark, bilingual) */

const { useState: cUseState, useEffect: cUseEffect } = React;

function ContactPage({ onNavigate }) {
  const { t, lang } = useLang();
  const [submitted, setSubmitted] = cUseState(false);
  const [form, setForm] = cUseState({
    firstName: '',
    lastName: '',
    company: '',
    email: '',
    phone: '',
    interest: '',
    message: '',
  });
  const update = (k, v) => setForm(f => ({ ...f, [k]: v }));

  const [sending, setSending] = cUseState(false);
  const [error, setError] = cUseState('');

  const canSubmit =
    form.firstName.trim() &&
    form.lastName.trim() &&
    form.company.trim() &&
    /\S+@\S+\.\S+/.test(form.email);

  const submit = async (e) => {
    e.preventDefault();
    if (!canSubmit || sending) return;
    setSending(true);
    setError('');

    const subject = `New project inquiry — ${form.firstName} ${form.lastName}` +
                    (form.company ? ` (${form.company})` : '');

    const payload = {
      access_key: '6d875049-e9c3-4d7d-be07-bc1064a75c8d',
      subject,
      from_name: `${form.firstName} ${form.lastName}`,
      // Web3Forms uses `email` as the reply-to address
      email: form.email,
      cc: 'seanclark@jmcrealities.com',
      'Full name': `${form.firstName} ${form.lastName}`,
      Company: form.company,
      Email: form.email,
      Phone: form.phone || '—',
      'Interested in': form.interest || '—',
      Project: form.message.trim() || '(not specified)',
    };

    try {
      const res = await fetch('https://api.web3forms.com/submit', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json', Accept: 'application/json' },
        body: JSON.stringify(payload),
      });
      const data = await res.json();
      if (data.success) {
        setSubmitted(true);
        window.scrollTo({ top: 0, behavior: 'smooth' });
      } else {
        setError(lang === 'es'
          ? 'No pudimos enviar el mensaje. Escribinos a contact@jmcrealities.com.'
          : 'We couldn\'t send your message. Please email contact@jmcrealities.com.');
      }
    } catch (err) {
      setError(lang === 'es'
        ? 'No pudimos enviar el mensaje. Escribinos a contact@jmcrealities.com.'
        : 'We couldn\'t send your message. Please email contact@jmcrealities.com.');
    } finally {
      setSending(false);
    }
  };

  if (submitted) {
    return <ContactSuccess form={form} onNavigate={onNavigate} onReset={() => {
      setSubmitted(false);
      setForm({ firstName: '', lastName: '', company: '', email: '', phone: '',
                interest: '', message: '' });
    }} />;
  }

  const F = t.contact.form;

  return (
    <div className="dc-page-enter" data-screen-label="Contact">
      {/* Hero */}
      <section style={{ position: 'relative', padding: '160px 0 80px',
                         overflow: 'hidden', borderBottom: '1px solid var(--hairline)' }}>
        <div style={{ position: 'absolute', inset: 0,
                      backgroundImage: `url("${window.RES('assets/portfolio/qts-interior-red.png')}")`,
                      backgroundSize: 'cover', backgroundPosition: 'center',
                      opacity: 0.35 }} />
        <div style={{ position: 'absolute', inset: 0,
                      background: 'linear-gradient(to bottom, rgba(10,10,10,0.85) 0%, rgba(10,10,10,0.7) 60%, var(--canvas) 100%)' }} />
        <div className="dc-container" style={{ position: 'relative' }}>
          <div style={{ display: 'grid', gridTemplateColumns: '2fr 1fr', gap: 64, alignItems: 'end' }}>
            <div>
              <div className="dc-eyebrow">{t.contact.hero.eyebrow}</div>
              <h1 style={{ fontSize: 'clamp(40px, 5vw, 64px)', fontWeight: 700, lineHeight: 1.05,
                            margin: '20px 0 0', letterSpacing: '-0.5px' }}>
                {t.contact.hero.title}
              </h1>
              <p style={{ fontSize: 17, fontWeight: 300, lineHeight: 1.6,
                           color: 'var(--body)', margin: '24px 0 0', maxWidth: 620 }}>
                {t.contact.hero.sub}
              </p>
            </div>
            <ContactSidePanel />
          </div>
        </div>
      </section>

      {/* Form */}
      <section style={{ background: 'var(--canvas)', padding: '80px 0 96px' }}>
        <div className="dc-container">
          <div style={{ display: 'grid', gridTemplateColumns: '1fr 1.6fr', gap: 64 }}>
            {/* Left rail */}
            <div>
              <div className="dc-eyebrow">{F.title}</div>
              <h2 style={{ fontSize: 'clamp(28px, 3vw, 40px)', fontWeight: 700,
                            lineHeight: 1.1, margin: '20px 0 0', letterSpacing: '-0.5px' }}>
                {lang === 'es' ? 'Algunos datos y empezamos a conversar.' : 'A few details and we\'ll be in touch.'}
              </h2>
              <p style={{ fontSize: 15, fontWeight: 300, lineHeight: 1.65,
                           color: 'var(--body)', margin: '20px 0 0' }}>
                {lang === 'es'
                  ? 'No spam, sin newsletter, sin formularios infinitos. Solo una respuesta personal en un día hábil.'
                  : 'No spam, no newsletter, no infinite forms. Just a personal reply within one business day.'}
              </p>
            </div>

            {/* Form */}
            <form onSubmit={submit}
                  style={{ display: 'flex', flexDirection: 'column', gap: 24 }}>
              <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 16 }}>
                <div className="dc-field">
                  <label className="dc-label">{F.firstName}</label>
                  <input className="dc-input" required
                         value={form.firstName}
                         onChange={e => update('firstName', e.target.value)} />
                </div>
                <div className="dc-field">
                  <label className="dc-label">{F.lastName}</label>
                  <input className="dc-input" required
                         value={form.lastName}
                         onChange={e => update('lastName', e.target.value)} />
                </div>
              </div>

              <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 16 }}>
                <div className="dc-field">
                  <label className="dc-label">{F.email}</label>
                  <input className="dc-input" type="email" required
                         value={form.email}
                         onChange={e => update('email', e.target.value)} />
                </div>
                <div className="dc-field">
                  <label className="dc-label">{F.phone} <span style={{ color: 'var(--muted)', fontWeight: 400, letterSpacing: 0, textTransform: 'none' }}>{F.optional}</span></label>
                  <input className="dc-input" type="tel"
                         value={form.phone}
                         onChange={e => update('phone', e.target.value)} />
                </div>
              </div>

              <div className="dc-field">
                <label className="dc-label">{F.company}</label>
                <input className="dc-input" required
                       value={form.company}
                       onChange={e => update('company', e.target.value)} />
              </div>

              <div className="dc-field">
                <label className="dc-label">{F.interest} <span style={{ color: 'var(--muted)', fontWeight: 400, letterSpacing: 0, textTransform: 'none' }}>{F.optional}</span></label>
                <div style={{ display: 'flex', gap: 8, flexWrap: 'wrap' }}>
                  {F.interestOptions.map(opt => {
                    const active = form.interest === opt;
                    return (
                      <button
                        key={opt}
                        type="button"
                        onClick={() => update('interest', active ? '' : opt)}
                        style={{
                          padding: '12px 18px',
                          background: active ? 'var(--accent)' : 'transparent',
                          color: active ? '#fff' : 'var(--ink)',
                          border: '1px solid ' + (active ? 'var(--accent)' : 'var(--hairline-strong)'),
                          fontSize: 12, fontWeight: 700, letterSpacing: '1px',
                          cursor: 'pointer', fontFamily: 'inherit',
                          transition: 'all 180ms var(--ease-standard)',
                          textTransform: 'uppercase',
                        }}>{opt}</button>
                    );
                  })}
                </div>
              </div>

              <div className="dc-field">
                <label className="dc-label">{F.message} <span style={{ color: 'var(--muted)', fontWeight: 400, letterSpacing: 0, textTransform: 'none' }}>{F.optional}</span></label>
                <textarea className="dc-textarea" rows={6}
                          placeholder={F.messagePlaceholder}
                          value={form.message}
                          onChange={e => update('message', e.target.value)} />
              </div>

              <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between',
                            paddingTop: 16, borderTop: '1px solid var(--hairline)', gap: 24,
                            flexWrap: 'wrap' }}>
                <p style={{ fontSize: 12, color: 'var(--muted)', margin: 0, maxWidth: 380,
                            lineHeight: 1.5 }}>
                  {lang === 'es'
                    ? 'Al enviar acept\u00e1s que procesemos tu mensaje para responderte. No usamos tus datos para nada m\u00e1s.'
                    : 'By submitting you agree that we process your message to reply. We don\'t use your data for anything else.'}
                </p>
                <DcBtn type="submit" disabled={!canSubmit || sending}>
                  {sending ? (lang === 'es' ? 'Enviando…' : 'Sending…') : F.submit}
                </DcBtn>
              </div>
              {error && (
                <p style={{ fontSize: 13, color: 'var(--accent)', margin: '4px 0 0',
                            fontWeight: 500 }}>{error}</p>
              )}
            </form>
          </div>
        </div>
      </section>

      <ContactFAQ />
    </div>
  );
}

/* ─────────────────────── Side panel ───────────────────── */

function ContactSidePanel() {
  const { t } = useLang();
  return (
    <div style={{ background: 'var(--surface-card)',
                  border: '1px solid var(--hairline)',
                  padding: 32,
                  display: 'flex', flexDirection: 'column', gap: 20 }}>
      <div className="dc-eyebrow">{t.contact.side.contactDirect}</div>
      <div style={{ display: 'flex', flexDirection: 'column', gap: 16 }}>
        {[
          ['mail', 'contact@jmcrealities.com'],
          ['phone', '+54 (911) 2646 4578'],
          ['map', 'Buenos Aires, Argentina'],
        ].map(([icon, text]) => (
          <div key={text} style={{ display: 'flex', alignItems: 'center', gap: 12,
                                    color: 'var(--ink)' }}>
            <DcIcon name={icon} size={18} style={{ color: 'var(--accent)' }} />
            <span style={{ fontSize: 14, fontWeight: 300 }}>{text}</span>
          </div>
        ))}
      </div>
      <hr style={{ border: 0, borderTop: '1px solid var(--hairline)', margin: '8px 0' }} />
      <div>
        <div style={{ fontSize: 10, fontWeight: 700, letterSpacing: '2px',
                      textTransform: 'uppercase', color: 'var(--muted)', marginBottom: 10 }}>
          {t.contact.side.responseTitle}
        </div>
        <div style={{ fontSize: 14, fontWeight: 300, color: 'var(--body)', lineHeight: 1.6 }}>
          {t.contact.side.responseBody}
        </div>
      </div>
    </div>
  );
}

/* ─────────────────────── Success ───────────────────── */

function ContactSuccess({ form, onNavigate, onReset }) {
  const { t } = useLang();

  return (
    <div className="dc-page-enter" data-screen-label="Contact Success">
      <section style={{ position: 'relative', padding: '180px 0 100px', overflow: 'hidden' }}>
        <div style={{ position: 'absolute', inset: 0,
                      backgroundImage: `url("${window.RES('assets/portfolio/pampa-sunset.png')}")`,
                      backgroundSize: 'cover', backgroundPosition: 'center',
                      opacity: 0.5 }} />
        <div style={{ position: 'absolute', inset: 0,
                      background: 'linear-gradient(to bottom, rgba(10,10,10,0.7) 0%, rgba(10,10,10,0.85) 70%, var(--canvas) 100%)' }} />
        <div className="dc-container" style={{ position: 'relative',
                                                display: 'flex', flexDirection: 'column',
                                                gap: 24, alignItems: 'center', textAlign: 'center',
                                                maxWidth: 820, marginInline: 'auto' }}>
          <div style={{ width: 80, height: 80,
                        border: '1px solid var(--accent)',
                        background: 'rgba(226,39,24,0.10)',
                        display: 'flex', alignItems: 'center', justifyContent: 'center',
                        color: 'var(--accent)' }}>
            <DcIcon name="check" size={36} />
          </div>
          <div className="dc-eyebrow">{t.contact.success.eyebrow}</div>
          <h1 style={{ fontSize: 'clamp(40px, 5vw, 60px)', fontWeight: 700, lineHeight: 1.05,
                        color: 'var(--ink)', margin: 0, letterSpacing: '-0.5px' }}>
            {t.contact.success.title}
          </h1>
          <p style={{ fontSize: 17, fontWeight: 300, lineHeight: 1.6,
                       color: 'var(--body)', margin: 0, maxWidth: 580 }}>
            {t.contact.success.body} <strong style={{ color: 'var(--ink)' }}>{form.email}</strong>
            {t.contact.success.bodyAfter}
          </p>
          <div style={{ display: 'flex', gap: 12, marginTop: 20 }}>
            <DcBtn onClick={() => onNavigate('portfolio')}>{t.contact.success.primary}</DcBtn>
            <DcBtn variant="secondary" onClick={onReset}>{t.contact.success.secondary}</DcBtn>
          </div>
        </div>
      </section>

      <section className="dc-section" style={{ background: 'var(--canvas)' }}>
        <div className="dc-container" style={{ maxWidth: 800, textAlign: 'center' }}>
          <div className="dc-eyebrow" style={{ justifyContent: 'center' }}>{t.contact.success.nextEyebrow}</div>
          <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)',
                         gap: 40, marginTop: 48 }}>
            {t.contact.success.next.map(([n, ttl, b]) => (
              <div key={n} style={{ textAlign: 'left', display: 'flex', flexDirection: 'column', gap: 10 }}>
                <div style={{ fontSize: 14, fontWeight: 700, color: 'var(--accent)',
                              letterSpacing: '2px' }}>{n}</div>
                <h5 style={{ fontSize: 20, fontWeight: 700, margin: 0 }}>{ttl}</h5>
                <p style={{ fontSize: 14, fontWeight: 300, color: 'var(--body)',
                             lineHeight: 1.6, margin: 0 }}>{b}</p>
              </div>
            ))}
          </div>
        </div>
      </section>
    </div>
  );
}

/* ─────────────────────── FAQ ───────────────────── */

function ContactFAQ() {
  const { t, lang } = useLang();
  const { FAQS } = window.JMC_DATA;
  const faqs = FAQS[lang];
  const [open, setOpen] = cUseState(0);
  return (
    <section className="dc-section" style={{ background: 'var(--surface-soft)' }}>
      <div className="dc-container" style={{ maxWidth: 980 }}>
        <DcSectionHeader eyebrow={t.contact.faq.eyebrow} title={t.contact.faq.title} maxWidth={640} />
        <div style={{ borderTop: '1px solid var(--hairline)' }}>
          {faqs.map((f, i) => {
            const isOpen = open === i;
            return (
              <div key={f.q} style={{ borderBottom: '1px solid var(--hairline)' }}>
                <button onClick={() => setOpen(isOpen ? -1 : i)}
                        style={{
                          width: '100%', textAlign: 'left',
                          padding: '28px 0', background: 'transparent', border: 0,
                          display: 'flex', justifyContent: 'space-between', alignItems: 'center',
                          gap: 24, cursor: 'pointer', fontFamily: 'inherit', color: 'var(--ink)',
                        }}>
                  <span style={{ fontSize: 20, fontWeight: 700, color: 'var(--ink)' }}>{f.q}</span>
                  <span style={{ transform: isOpen ? 'rotate(180deg)' : 'rotate(0)',
                                  transition: 'transform 240ms var(--ease-standard)',
                                  display: 'flex' }}>
                    <DcIcon name="chevronDown" size={22} />
                  </span>
                </button>
                <div style={{
                  maxHeight: isOpen ? 400 : 0, overflow: 'hidden',
                  transition: 'max-height 320ms var(--ease-standard), padding 320ms var(--ease-standard)',
                  padding: isOpen ? '0 0 28px' : '0',
                }}>
                  <p style={{ fontSize: 16, fontWeight: 300, lineHeight: 1.65,
                               color: 'var(--body)', margin: 0, maxWidth: 760 }}>{f.a}</p>
                </div>
              </div>
            );
          })}
        </div>
      </div>
    </section>
  );
}

window.ContactPage = ContactPage;
