/* global React */
const { useEffect, useRef, useState } = React;

function Why() {
  const { t } = window.useT();
  const w = t.why;
  const icons = [
    (<svg viewBox="0 0 24 24" width="20" height="20" fill="none" stroke="#4A7AFF" strokeWidth="1.6"><path d="M12 2 3 7v10l9 5 9-5V7l-9-5Z"/><path d="m3 7 9 5 9-5M12 12v10"/></svg>),
    (<svg viewBox="0 0 24 24" width="20" height="20" fill="none" stroke="#4A7AFF" strokeWidth="1.6"><circle cx="12" cy="12" r="3"/><path d="M12 3v3M12 18v3M3 12h3M18 12h3M5.6 5.6l2.1 2.1M16.3 16.3l2.1 2.1M5.6 18.4l2.1-2.1M16.3 7.7l2.1-2.1"/></svg>),
    (<svg viewBox="0 0 24 24" width="20" height="20" fill="none" stroke="#4A7AFF" strokeWidth="1.6"><circle cx="12" cy="8" r="3.5"/><path d="M5 21c0-3.5 3.1-6 7-6s7 2.5 7 6"/></svg>),
    (<svg viewBox="0 0 24 24" width="20" height="20" fill="none" stroke="#4A7AFF" strokeWidth="1.6"><path d="M3 12h4l3-7 4 14 3-7h4"/></svg>),
  ];
  return (
    <section id="why" className="section">
      <div className="container">
        <div className="section-head">
          <span className="eyebrow"><span className="dot"></span>{w.eyebrow}</span>
          <h2>{w.h2line1}<br />{w.h2line2}</h2>
        </div>
        <div className="why-grid">
          {w.items.map((it, i) => (
            <div className="card why-cell card-hover" key={i}>
              <div className="ico-wrap">{icons[i]}</div>
              <div>
                <h4>{it.title}</h4>
                <p>{it.body}</p>
              </div>
            </div>
          ))}
        </div>
      </div>
    </section>
  );
}

function ParentCompany() {
  const { t } = window.useT();
  const p = t.parent;
  return (
    <section id="parent" className="section-sm">
      <div className="container">
        <div className="card" style={{ padding: '40px 36px' }}>
          <div style={{ display: 'grid', gridTemplateColumns: '1fr 1.4fr', gap: 40, alignItems: 'center' }} className="parent-grid">
            <div>
              <span className="eyebrow"><span className="dot"></span>{p.eyebrow}</span>
              <h3 style={{ marginTop: 18, fontSize: 26, lineHeight: 1.2 }}>{p.title}</h3>
              <p style={{ color: 'var(--fg-2)', marginTop: 14, fontSize: 15 }}>{p.body}</p>
              {p.meta && (
                <div style={{ display: 'flex', flexWrap: 'wrap', gap: 24, marginTop: 22, paddingTop: 22, borderTop: '1px dashed var(--line)' }}>
                  {p.meta.map((m, i) => (
                    <div key={i} style={{ display: 'flex', flexDirection: 'column', gap: 4 }}>
                      <span style={{ fontFamily: 'var(--mono)', fontSize: 11, letterSpacing: '0.14em', textTransform: 'uppercase', color: 'var(--fg-3)' }}>{m.lbl}</span>
                      {m.href ? (
                        <a href={m.href} target="_blank" rel="noreferrer" style={{ color: 'var(--fg-0)', fontSize: 14, textDecoration: 'none', borderBottom: '1px solid var(--line-2)', alignSelf: 'flex-start' }}>{m.val}</a>
                      ) : (
                        <span style={{ color: 'var(--fg-0)', fontSize: 14 }}>{m.val}</span>
                      )}
                    </div>
                  ))}
                </div>
              )}
            </div>
            <div style={{ display: 'flex', flexWrap: 'wrap', gap: 8 }}>
              {p.services.map((s, i) => (
                <span key={i} style={{
                  fontFamily: 'var(--mono)', fontSize: 12, letterSpacing: '0.08em', textTransform: 'uppercase',
                  color: s === 'INEX AI' ? '#fff' : 'var(--fg-2)',
                  border: `1px solid ${s === 'INEX AI' ? 'var(--blue)' : 'var(--line-2)'}`,
                  background: s === 'INEX AI' ? 'rgba(30,91,255,0.12)' : 'transparent',
                  borderRadius: 999, padding: '8px 14px'
                }}>{s}</span>
              ))}
            </div>
          </div>
        </div>
      </div>
    </section>
  );
}

function PhoneField({ disabled, onChange, onValidityChange, invalid, placeholder }) {
  const inputRef = useRef(null);
  const itiRef = useRef(null);

  useEffect(() => {
    if (!inputRef.current || typeof window.intlTelInput !== 'function') return;
    const iti = window.intlTelInput(inputRef.current, {
      initialCountry: 'auto',
      geoIpLookup: (success) => {
        const fallback = 'ca';
        const tryFetch = (url) =>
          fetch(url, { cache: 'no-store' })
            .then((r) => (r.ok ? r.json() : Promise.reject()))
            .then((d) => d && (d.country_code || d.country) ? (d.country_code || d.country).toLowerCase() : null);

        tryFetch('https://ipapi.co/json/')
          .catch(() => tryFetch('https://ipwho.is/'))
          .then((code) => success(code || fallback))
          .catch(() => success(fallback));
      },
      countryOrder: ['ca', 'us', 'br', 'gb', 'pt'],
      preferredCountries: ['ca', 'us', 'br', 'gb', 'pt'],
      separateDialCode: false,
      formatAsYouType: true,
      nationalMode: false,
      autoPlaceholder: 'aggressive',
    });
    itiRef.current = iti;

    const emit = () => {
      const raw = inputRef.current?.value || '';
      if (!raw.trim()) {
        onChange?.('');
        onValidityChange?.(true);
        return;
      }
      const E164 = window.intlTelInputUtils?.numberFormat?.E164;
      const e164 = E164 != null ? iti.getNumber(E164) : iti.getNumber();
      // isValidNumber uses libphonenumber (Google) under the hood - accepts
      // any country format as long as the dial code matches a known number.
      const valid = typeof iti.isValidNumber === 'function'
        ? iti.isValidNumber()
        : true;
      onChange?.(e164 || raw);
      onValidityChange?.(valid);
    };

    inputRef.current.addEventListener('input', emit);
    inputRef.current.addEventListener('countrychange', emit);
    return () => {
      inputRef.current?.removeEventListener('input', emit);
      inputRef.current?.removeEventListener('countrychange', emit);
      iti.destroy();
    };
  }, []);

  return (
    <input
      ref={inputRef}
      type="tel"
      className={invalid ? 'iti-input-invalid' : ''}
      placeholder={placeholder}
      disabled={disabled}
      aria-invalid={invalid || undefined}
    />
  );
}

function ContactForm() {
  const { t } = window.useT();
  const f = t.form;
  const [values, setValues] = useState({ name: '', email: '', phone: '', company: '', message: '' });
  const [phoneValid, setPhoneValid] = useState(true);
  const [errors, setErrors] = useState({});
  const [status, setStatus] = useState('idle'); // idle | sending | sent | error

  const update = (field) => (e) => {
    setValues((v) => ({ ...v, [field]: e.target.value }));
    if (errors[field]) setErrors((er) => ({ ...er, [field]: undefined }));
  };

  const validate = () => {
    const next = {};
    if (!values.name.trim()) next.name = f.required;
    if (!values.email.trim()) next.email = f.required;
    else if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(values.email.trim())) next.email = f.invalidEmail;
    if (!values.message.trim()) next.message = f.required;
    if (values.phone && !phoneValid) next.phone = f.invalidPhone;
    setErrors(next);
    return Object.keys(next).length === 0;
  };

  const onSubmit = async (e) => {
    e.preventDefault();
    if (status === 'sending') return;
    if (!validate()) return;
    setStatus('sending');
    try {
      const res = await fetch('https://v3.verzel.com.br/api/contact/inex', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          name: values.name.trim(),
          email: values.email.trim(),
          phone: values.phone.trim(),
          company: values.company.trim(),
          message: values.message.trim(),
        }),
      });
      if (!res.ok) throw new Error('http_' + res.status);
      setStatus('sent');
      setValues({ name: '', email: '', phone: '', company: '', message: '' });
    } catch {
      setStatus('error');
    }
  };

  if (status === 'sent') {
    return (
      <div className="contact-form-success" role="status">
        <div className="contact-form-success-icon">✓</div>
        <p>{f.success}</p>
      </div>
    );
  }

  return (
    <form className="contact-form" onSubmit={onSubmit} noValidate>
      <div className="contact-form-row">
        <label className="contact-form-field">
          <span className="contact-form-label">{f.name}</span>
          <input
            type="text"
            value={values.name}
            onChange={update('name')}
            placeholder={f.namePh}
            aria-invalid={!!errors.name}
            disabled={status === 'sending'}
          />
          {errors.name && <span className="contact-form-error">{errors.name}</span>}
        </label>
        <label className="contact-form-field">
          <span className="contact-form-label">{f.email}</span>
          <input
            type="email"
            value={values.email}
            onChange={update('email')}
            placeholder={f.emailPh}
            aria-invalid={!!errors.email}
            disabled={status === 'sending'}
          />
          {errors.email && <span className="contact-form-error">{errors.email}</span>}
        </label>
      </div>
      <div className="contact-form-row">
        <label className="contact-form-field contact-form-field-phone">
          <span className="contact-form-label">{f.phone}</span>
          <PhoneField
            disabled={status === 'sending'}
            invalid={!!errors.phone}
            placeholder={f.phonePh}
            onChange={(val) => {
              setValues((v) => ({ ...v, phone: val }));
              if (errors.phone) setErrors((er) => ({ ...er, phone: undefined }));
            }}
            onValidityChange={setPhoneValid}
          />
          {errors.phone && <span className="contact-form-error">{errors.phone}</span>}
        </label>
        <label className="contact-form-field">
          <span className="contact-form-label">{f.company}</span>
          <input
            type="text"
            value={values.company}
            onChange={update('company')}
            placeholder={f.companyPh}
            disabled={status === 'sending'}
          />
        </label>
      </div>
      <label className="contact-form-field">
        <span className="contact-form-label">{f.message}</span>
        <textarea
          value={values.message}
          onChange={update('message')}
          placeholder={f.messagePh}
          rows={5}
          aria-invalid={!!errors.message}
          disabled={status === 'sending'}
        />
        {errors.message && <span className="contact-form-error">{errors.message}</span>}
      </label>
      <div className="contact-form-actions">
        <button type="submit" className="btn btn-primary" disabled={status === 'sending'}>
          {status === 'sending' ? f.sending : f.submit}
          {status !== 'sending' && <span className="arrow">→</span>}
        </button>
        {status === 'error' && <span className="contact-form-error contact-form-error-submit">{f.error}</span>}
      </div>
    </form>
  );
}

function FinalCTA() {
  const { t } = window.useT();
  const c = t.cta;
  return (
    <section id="cta" className="section-sm">
      <div className="container">
        <div className="final-cta">
          <span className="kicker"><span className="pulse"></span>{c.kicker}</span>
          <h2>{c.h2line1}<br />{c.h2line2}</h2>
          <p className="lead" style={{ margin: '24px auto 0 auto', textAlign: 'center', maxWidth: 640 }}>{c.lead}</p>
          <ContactForm />
        </div>
      </div>
    </section>
  );
}

function Footer() {
  const { t } = window.useT();
  return (
    <footer className="footer">
      <div className="container footer-inner">
        <div style={{ display: 'flex', alignItems: 'center', gap: 16 }}>
          <Logo small />
          <span style={{ color: 'var(--fg-3)', fontFamily: 'var(--mono)', fontSize: 11, letterSpacing: '0.14em', textTransform: 'uppercase' }}>{t.footer.tag}</span>
        </div>
        <div style={{ color: 'var(--fg-3)' }}>{t.footer.copy}</div>
      </div>
    </footer>
  );
}

window.Why = Why;
window.ParentCompany = ParentCompany;
window.FinalCTA = FinalCTA;
window.Footer = Footer;
