/* eslint-disable */

function QualitySection({ onCta }) {
  const cards = [
    { icon: 'badge-check', title: 'ISO 9001' },
    { icon: 'gauge', title: 'Control QC' },
    { icon: 'file-text', title: 'Documentación' },
    { icon: 'layers', title: 'Materiales' },
  ];
  return (
    <section className="section" id="calidad" data-screen-label="Calidad certificada">
      <div className="container">
        <Reveal className="section-head">
          <span className="eyebrow">Calidad certificada</span>
          <h2 className="h-section">Documentación preparada para compras profesionales.</h2>
          <p className="lead">
            Solicita certificados, fichas técnicas, información de materiales y referencias para
            evaluación de importación.
          </p>
        </Reveal>

        <Reveal className="quality-grid" delay={80}>
          {cards.map((c) => (
            <div key={c.title} className="quality-card">
              <span className="quality-card__icon">
                <Icon name={c.icon} size={22} strokeWidth={1.5}/>
              </span>
              <h3 className="quality-card__title">{c.title}</h3>
            </div>
          ))}
        </Reveal>

        <Reveal delay={160} style={{ marginTop: 40 }}>
          <button className="btn btn--lg btn--green" onClick={onCta}>
            Solicitar documentación y catálogo
            <span className="arrow-circ"><Icon name="arrow-right" size={14}/></span>
          </button>
        </Reveal>
      </div>
    </section>
  );
}

const PRODUCT_OPTIONS = [
  'PE Coated',
  'PVDF Coated',
  'Mirror',
  'Brushed',
  'Wooden & Marble',
  'Aluminum Coils',
];

const ACTIVITY_OPTIONS = [
  'Importador',
  'Distribuidor',
  'Mayorista',
  'Fabricante',
  'Transformador',
  'Otro comprador B2B',
];

const IMPORT_OPTIONS = [
  'Sí, regularmente',
  'Sí, ocasionalmente',
  'Aún no, estamos evaluando',
];

function ContactForm() {
  const [data, setData] = React.useState({
    name: '', company: '', email: '', phone: '',
    country: '', website: '',
    activity: '', importsAcm: '',
    products: [], message: '',
  });
  const [errors, setErrors] = React.useState({});
  const [submitting, setSubmitting] = React.useState(false);
  const [submitted, setSubmitted] = React.useState(false);

  const set = (k, v) => {
    setData(d => ({ ...d, [k]: v }));
    if (errors[k]) setErrors(e => ({ ...e, [k]: null }));
  };

  const toggleProduct = (p) => {
    setData(d => ({
      ...d,
      products: d.products.includes(p) ? d.products.filter(x => x !== p) : [...d.products, p],
    }));
  };

  const validate = () => {
    const e = {};
    if (!data.name.trim()) e.name = 'Campo obligatorio';
    if (!data.company.trim()) e.company = 'Campo obligatorio';
    if (!data.email.trim()) e.email = 'Campo obligatorio';
    else if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(data.email)) e.email = 'E-mail inválido';
    if (!data.phone.trim()) e.phone = 'Campo obligatorio';
    if (!data.country.trim()) e.country = 'Campo obligatorio';
    if (!data.activity) e.activity = 'Selecciona una opción';
    if (!data.importsAcm) e.importsAcm = 'Selecciona una opción';
    setErrors(e);
    return Object.keys(e).length === 0;
  };

  const onSubmit = (ev) => {
    ev.preventDefault();
    if (!validate()) {
      const firstKey = Object.keys(errors)[0];
      if (firstKey) {
        const el = document.querySelector(`[data-field="${firstKey}"]`);
        if (el) el.focus();
      }
      return;
    }
    setSubmitting(true);

    const payload = {
      name: data.name,
      email: data.email,
      phone: data.phone,
      source: 'Landing Page JIEYAO',
      data: {
        empresa: data.company,
        pais: data.country,
        sitio_web: data.website,
        actividad: data.activity,
        importa_acm: data.importsAcm,
        productos: data.products.join(', '),
      },
    };

    fetch('https://kukudbukuzdrgiueiwnz.supabase.co/functions/v1/webhook-leads', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        'Authorization': 'Bearer vox_bba647a349ea001cb9a12dc608596f18e6ebbb4e08304ef6a59148c132a798fe',
      },
      body: JSON.stringify(payload),
    })
      .then(() => {
        if (window.fbq) window.fbq('track', 'Lead');
        setSubmitting(false);
        setSubmitted(true);
      })
      .catch(() => {
        if (window.fbq) window.fbq('track', 'Lead');
        setSubmitting(false);
        setSubmitted(true);
      });
  };

  if (submitted) {
    return (
      <div className="form-success" role="status">
        <span className="form-success__icon">
          <Icon name="check" size={26} strokeWidth={2.4}/>
        </span>
        <h3 className="form-success__title">Solicitud registrada.</h3>
        <p className="form-success__body">
          El equipo de JIEYAO responderá en hasta 48 horas hábiles.
        </p>
      </div>
    );
  }

  return (
    <form className="form-card" onSubmit={onSubmit} noValidate>
      <div className="field--row">
        <Field label="Nombre completo" required error={errors.name}>
          <input
            data-field="name"
            className="field__input"
            value={data.name}
            onChange={(e) => set('name', e.target.value)}
            autoComplete="name"
          />
        </Field>
        <Field label="Empresa" required error={errors.company}>
          <input
            data-field="company"
            className="field__input"
            value={data.company}
            onChange={(e) => set('company', e.target.value)}
            autoComplete="organization"
          />
        </Field>
      </div>

      <div className="field--row">
        <Field label="E-mail corporativo" required error={errors.email}>
          <input
            data-field="email"
            type="email"
            className="field__input"
            value={data.email}
            onChange={(e) => set('email', e.target.value)}
            autoComplete="email"
          />
        </Field>
        <Field label="WhatsApp / Teléfono" required error={errors.phone}>
          <input
            data-field="phone"
            type="tel"
            className="field__input"
            value={data.phone}
            onChange={(e) => set('phone', e.target.value)}
            autoComplete="tel"
          />
        </Field>
      </div>

      <div className="field--row">
        <Field label="País" required error={errors.country}>
          <input
            data-field="country"
            className="field__input"
            value={data.country}
            onChange={(e) => set('country', e.target.value)}
            autoComplete="country-name"
          />
        </Field>
        <Field label="Sitio web">
          <input
            className="field__input"
            value={data.website}
            onChange={(e) => set('website', e.target.value)}
            placeholder="https://"
            autoComplete="url"
          />
        </Field>
      </div>

      <Field label="Actividad principal" required error={errors.activity}>
        <select
          data-field="activity"
          className="field__select"
          value={data.activity}
          onChange={(e) => set('activity', e.target.value)}
        >
          <option value="">Selecciona una opción</option>
          {ACTIVITY_OPTIONS.map((o) => (
            <option key={o} value={o}>{o}</option>
          ))}
        </select>
      </Field>

      <Field label="¿Tu empresa ya importa ACM?" required error={errors.importsAcm}>
        <div className="chip-group" data-field="importsAcm">
          {IMPORT_OPTIONS.map((o) => (
            <button
              type="button"
              key={o}
              className={`chip ${data.importsAcm === o ? 'chip--active' : ''}`}
              onClick={() => set('importsAcm', o)}
            >
              {data.importsAcm === o && (
                <span className="chip-check"><Icon name="check" size={12} strokeWidth={2.4}/></span>
              )}
              {o}
            </button>
          ))}
        </div>
      </Field>

      <Field label="Productos de interés">
        <div className="chip-group">
          {PRODUCT_OPTIONS.map((o) => (
            <button
              type="button"
              key={o}
              className={`chip ${data.products.includes(o) ? 'chip--active' : ''}`}
              onClick={() => toggleProduct(o)}
            >
              {data.products.includes(o) && (
                <span className="chip-check"><Icon name="check" size={12} strokeWidth={2.4}/></span>
              )}
              {o}
            </button>
          ))}
        </div>
      </Field>

      <button type="submit" className="btn btn--lg btn--green btn--full" disabled={submitting} style={{ marginTop: 8 }}>
        {submitting ? 'Enviando solicitud...' : 'Enviar solicitud B2B'}
        {!submitting && (
          <span className="arrow-circ"><Icon name="arrow-right" size={14}/></span>
        )}
      </button>
    </form>
  );
}

function Field({ label, required, error, children }) {
  return (
    <div className={`field ${error ? 'field--error' : ''}`}>
      <label className="field__label">
        {label}
        {required && <span className="req">*</span>}
      </label>
      {children}
      {error && <span className="field__error">{error}</span>}
    </div>
  );
}

function ContactSection() {
  return (
    <section className="section section--alt" id="contacto" data-screen-label="Contacto B2B">
      <div className="container">
        <div className="form-wrap">
          <div className="form-side">
            <Reveal className="section-head" style={{ marginBottom: 0 }}>
              <span className="eyebrow">Contacto B2B</span>
              <h2 className="h-section">Solicita catálogo técnico y cotización.</h2>
              <p className="lead">
                Completa el formulario para que el equipo comercial evalúe tu empresa, productos
                de interés y condiciones de compra.
              </p>
            </Reveal>

            <Reveal delay={160} className="form-side__notice">
              Registro orientado exclusivamente a empresas distribuidoras, importadoras o
              compradoras mayoristas. No atendemos usuarios finales.
            </Reveal>

          </div>

          <Reveal delay={80}>
            <ContactForm/>
          </Reveal>
        </div>
      </div>
    </section>
  );
}

function SiteFooter() {
  return (
    <footer className="site-footer" data-screen-label="Footer">
      <div className="container">
        <div className="site-footer__rule" style={{ marginTop: 0 }}/>
        <div className="site-footer__inner">
          <div className="site-footer__brand-block">
            <span className="site-footer__brand-name">Taizhou Jieyao Technology Co., Ltd.</span>
            <span className="site-footer__brand-line">Taizhou, Zhejiang, China</span>
          </div>
          <div className="site-footer__meta">
            Exportación B2B América Latina · © 2026
          </div>
        </div>
      </div>
    </footer>
  );
}

window.QualitySection = QualitySection;
window.ContactSection = ContactSection;
window.SiteFooter = SiteFooter;
