// FormularioPresupuesto — NEX Higiene & Seguridad
const { useState } = React;

const PROVINCIAS_AR = [
  'Buenos Aires',
  'Catamarca',
  'Chaco',
  'Chubut',
  'Ciudad Autónoma de Buenos Aires',
  'Córdoba',
  'Corrientes',
  'Entre Ríos',
  'Formosa',
  'Jujuy',
  'La Pampa',
  'La Rioja',
  'Mendoza',
  'Misiones',
  'Neuquén',
  'Río Negro',
  'Salta',
  'San Juan',
  'San Luis',
  'Santa Cruz',
  'Santa Fe',
  'Santiago del Estero',
  'Tierra del Fuego',
  'Tucumán',
];

const SERVICIOS_LISTA = [
  'Auditoría de Higiene y Seguridad',
  'Capacitaciones',
  'Plan de evacuación',
  'Programa de seguridad',
  'Mediciones ambientales',
  'Puesta a tierra',
  'Informe ambiental',
  'Asesoramiento normativo',
  'Otro',
];

const WA_NUMBER = '5493547594144';

function FormularioPresupuesto() {
  const [form, setForm] = useState({
    empresa: '',
    empleados: '',
    provincia: '',
    localidad: '',
    servicios: [],
    otroDetalle: '',
  });
  const [errors, setErrors] = useState({});
  const [toast, setToast] = useState(false);

  const set = (k, v) => {
    setForm(f => ({ ...f, [k]: v }));
    if (errors[k]) setErrors(e => { const n = { ...e }; delete n[k]; return n; });
  };

  const toggleServicio = (s) => {
    setForm(f => ({
      ...f,
      servicios: f.servicios.includes(s)
        ? f.servicios.filter(x => x !== s)
        : [...f.servicios, s],
    }));
    if (errors.servicios) setErrors(e => { const n = { ...e }; delete n.servicios; return n; });
  };

  const validate = () => {
    const e = {};
    if (!form.empresa.trim())   e.empresa   = 'Requerido';
    if (!form.empleados)        e.empleados = 'Requerido';
    if (!form.provincia)        e.provincia = 'Requerido';
    if (!form.localidad.trim()) e.localidad = 'Requerido';
    if (form.servicios.length === 0) e.servicios = 'Seleccioná al menos un servicio';
    return e;
  };

  const handleSubmit = () => {
    const e = validate();
    if (Object.keys(e).length > 0) {
      setErrors(e);
      const section = document.getElementById('presupuesto');
      if (section) section.scrollIntoView({ behavior: 'smooth', block: 'start' });
      return;
    }
    setErrors({});

    const serviciosList = form.servicios
      .map(s => s === 'Otro' ? `Otro: ${form.otroDetalle.trim() || '(sin especificar)'}` : s)
      .map(s => `✅ ${s}`)
      .join('\n');

    const msg = [
      '🆕 PRESUPUESTO NEX',
      '',
      '📋 CLIENTE',
      `Nombre: ${form.empresa}`,
      `Empleados: ${form.empleados}`,
      '',
      '📍 UBICACIÓN',
      `${form.provincia}, ${form.localidad}`,
      '',
      '🛠️ SERVICIOS',
      serviciosList,
    ].join('\n');

    setToast(true);
    setTimeout(() => {
      setToast(false);
      window.open(
        `https://wa.me/${WA_NUMBER}?text=${encodeURIComponent(msg)}`,
        '_blank',
        'noopener,noreferrer'
      );
    }, 1400);
  };

  // Style helpers
  const inputBase = (hasError) => ({
    width: '100%',
    padding: '13px 16px',
    fontSize: 15,
    fontFamily: "'Rubik', sans-serif",
    color: '#1A1A1A',
    background: '#FFFFFF',
    border: `1.5px solid ${hasError ? '#E31E24' : '#E6E6E6'}`,
    borderRadius: 8,
    outline: 'none',
    boxSizing: 'border-box',
    appearance: 'none',
    WebkitAppearance: 'none',
    transition: 'border-color .2s',
  });

  const WA_ICON = (
    <svg width="22" height="22" viewBox="0 0 32 32" fill="currentColor">
      <path d="M16 0C7.16 0 0 7.16 0 16c0 2.82.74 5.47 2.04 7.78L0 32l8.45-2.21A15.93 15.93 0 0016 32c8.84 0 16-7.16 16-16S24.84 0 16 0zm0 29.2c-2.5 0-4.84-.69-6.85-1.88l-.49-.29-5.02 1.31 1.34-4.89-.32-.5A13.16 13.16 0 012.8 16c0-7.29 5.91-13.2 13.2-13.2S29.2 8.71 29.2 16 23.29 29.2 16 29.2zm7.24-9.88c-.4-.2-2.35-1.16-2.71-1.29-.36-.13-.62-.2-.89.2-.27.4-1.02 1.29-1.25 1.55-.23.27-.46.3-.86.1-.4-.2-1.69-.62-3.22-1.99-1.19-1.06-1.99-2.37-2.22-2.77-.23-.4-.02-.62.18-.82.18-.18.4-.46.6-.7.2-.23.27-.4.4-.66.13-.27.07-.5-.03-.7-.1-.2-.89-2.15-1.22-2.94-.32-.77-.65-.66-.89-.67h-.76c-.27 0-.7.1-1.07.5-.36.4-1.4 1.37-1.4 3.34s1.43 3.87 1.63 4.13c.2.27 2.83 4.32 6.85 6.06.96.41 1.7.66 2.28.84.96.31 1.83.27 2.51.16.77-.11 2.35-.96 2.68-1.89.33-.93.33-1.72.23-1.89-.1-.16-.36-.27-.76-.46z"/>
    </svg>
  );

  return (
    <section id="presupuesto" style={{ background: '#F5F5F5', padding: '80px 20px', fontFamily: "'Rubik', sans-serif" }}>

      {/* Toast */}
      <div style={{
        position: 'fixed',
        top: 28,
        left: '50%',
        transform: `translateX(-50%) translateY(${toast ? '0' : '-90px'})`,
        background: '#1A1A1A',
        color: '#FFFFFF',
        padding: '14px 28px',
        borderRadius: 8,
        fontSize: 14,
        fontWeight: 500,
        zIndex: 9999,
        boxShadow: '0 8px 24px rgba(0,0,0,0.22)',
        fontFamily: "'Rubik', sans-serif",
        transition: 'transform .35s cubic-bezier(.4,0,.2,1)',
        whiteSpace: 'nowrap',
        pointerEvents: 'none',
      }}>
        ✅ Abriendo WhatsApp…
      </div>

      <div style={{ maxWidth: 800, margin: '0 auto' }}>

        {/* Header */}
        <div style={{ marginBottom: 52, textAlign: 'center' }}>
          <h2 style={{
            fontFamily: "'Rubik', sans-serif",
            fontSize: 'clamp(28px, 4vw, 40px)',
            fontWeight: 700,
            color: '#1A1A1A',
            margin: '0 0 14px',
            lineHeight: 1.15,
          }}>
            ¿Necesitás un presupuesto?
          </h2>
          <p style={{ color: '#666666', fontSize: 16, margin: 0, fontFamily: "'Rubik', sans-serif" }}>
            Completá el formulario y te contactamos en menos de 24hs
          </p>
        </div>

        {/* Card */}
        <div style={{
          background: '#FFFFFF',
          borderRadius: 16,
          padding: 'clamp(28px, 5vw, 60px)',
          boxShadow: '0 4px 32px rgba(0,0,0,0.06)',
        }}>

          {/* 01 · CLIENTE */}
          <Section label="01 · CLIENTE">
            <Field label="Nombre" error={errors.empresa}>
              <input
                type="text"
                value={form.empresa}
                onChange={e => set('empresa', e.target.value)}
                style={inputBase(errors.empresa)}
                placeholder="Ej: Martín González de Empresa Volt"
                onFocus={e => { e.target.style.borderColor = '#E31E24'; }}
                onBlur={e => { e.target.style.borderColor = errors.empresa ? '#E31E24' : '#E6E6E6'; }}
              />
            </Field>
            <Field label="Cantidad de empleados" error={errors.empleados}>
              <select
                value={form.empleados}
                onChange={e => set('empleados', e.target.value)}
                style={inputBase(errors.empleados)}
              >
                <option value="">Seleccioná una opción</option>
                <option value="1-10">1 – 10</option>
                <option value="11-30">11 – 30</option>
                <option value="31-50">31 – 50</option>
                <option value="51-100">51 – 100</option>
                <option value="100+">Más de 100</option>
              </select>
            </Field>
          </Section>

          {/* 02 · UBICACIÓN */}
          <Section label="02 · UBICACIÓN">
            <Field label="Provincia" error={errors.provincia}>
              <select
                value={form.provincia}
                onChange={e => set('provincia', e.target.value)}
                style={inputBase(errors.provincia)}
              >
                <option value="">Seleccioná una provincia</option>
                {PROVINCIAS_AR.map(p => <option key={p} value={p}>{p}</option>)}
              </select>
            </Field>
            <Field label="Localidad" error={errors.localidad}>
              <input
                type="text"
                value={form.localidad}
                onChange={e => set('localidad', e.target.value)}
                style={inputBase(errors.localidad)}
                placeholder="Ej: San Francisco, Río Cuarto, Mendoza..."
                onFocus={e => { e.target.style.borderColor = '#E31E24'; }}
                onBlur={e => { e.target.style.borderColor = errors.localidad ? '#E31E24' : '#E6E6E6'; }}
              />
            </Field>
          </Section>

          {/* 03 · SERVICIOS */}
          <Section label="03 · SERVICIOS" last>
            {errors.servicios && (
              <div style={{ fontSize: 12, color: '#E31E24', marginBottom: 16, fontFamily: "'Rubik', sans-serif" }}>
                {errors.servicios}
              </div>
            )}
            <div style={{
              display: 'grid',
              gridTemplateColumns: 'repeat(auto-fill, minmax(230px, 1fr))',
              gap: '10px 20px',
              marginBottom: 0,
            }}>
              {SERVICIOS_LISTA.map(s => {
                const checked = form.servicios.includes(s);
                return (
                  <div
                    key={s}
                    onClick={() => toggleServicio(s)}
                    style={{
                      display: 'flex',
                      alignItems: 'flex-start',
                      gap: 12,
                      cursor: 'pointer',
                      padding: '12px 14px',
                      borderRadius: 8,
                      border: `1.5px solid ${checked ? '#E31E24' : '#E6E6E6'}`,
                      background: checked ? 'rgba(227,30,36,0.04)' : '#FFFFFF',
                      transition: 'border-color .18s, background .18s',
                      userSelect: 'none',
                    }}
                  >
                    <div style={{
                      width: 18,
                      height: 18,
                      borderRadius: 4,
                      border: `2px solid ${checked ? '#E31E24' : '#CCCCCC'}`,
                      background: checked ? '#E31E24' : 'transparent',
                      display: 'flex',
                      alignItems: 'center',
                      justifyContent: 'center',
                      flexShrink: 0,
                      marginTop: 1,
                      transition: 'background .18s, border-color .18s',
                    }}>
                      {checked && (
                        <svg width="10" height="8" viewBox="0 0 10 8" fill="none">
                          <path d="M1 4l3 3 5-6" stroke="white" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round" />
                        </svg>
                      )}
                    </div>
                    <span style={{
                      fontSize: 14,
                      color: checked ? '#1A1A1A' : '#666666',
                      fontFamily: "'Rubik', sans-serif",
                      fontWeight: checked ? 500 : 400,
                      lineHeight: 1.4,
                    }}>
                      {s}
                    </span>
                  </div>
                );
              })}
            </div>

            {/* Otro — conditional input */}
            {form.servicios.includes('Otro') && (
              <div style={{ marginTop: 16 }}>
                <input
                  type="text"
                  value={form.otroDetalle}
                  onChange={e => set('otroDetalle', e.target.value)}
                  style={{ ...inputBase(false), maxWidth: 420 }}
                  placeholder="Especificá el servicio..."
                  onFocus={e => { e.target.style.borderColor = '#E31E24'; }}
                  onBlur={e => { e.target.style.borderColor = '#E6E6E6'; }}
                />
              </div>
            )}
          </Section>

          {/* Submit */}
          <div style={{ marginTop: 40, display: 'flex', justifyContent: 'center' }}>
            <button
              onClick={handleSubmit}
              style={{
                background: '#E31E24',
                color: '#FFFFFF',
                border: 'none',
                borderRadius: 8,
                padding: '15px 44px',
                fontSize: 14,
                fontWeight: 600,
                letterSpacing: '0.08em',
                textTransform: 'uppercase',
                fontFamily: "'Rubik', sans-serif",
                cursor: 'pointer',
                transition: 'background .2s, transform .2s, box-shadow .2s',
                display: 'inline-flex',
                alignItems: 'center',
                gap: 10,
                boxShadow: '0 6px 20px rgba(227,30,36,0.3)',
              }}
              onMouseEnter={e => {
                e.currentTarget.style.background = '#C41A1F';
                e.currentTarget.style.transform = 'translateY(-1px)';
                e.currentTarget.style.boxShadow = '0 8px 24px rgba(227,30,36,0.4)';
              }}
              onMouseLeave={e => {
                e.currentTarget.style.background = '#E31E24';
                e.currentTarget.style.transform = 'translateY(0)';
                e.currentTarget.style.boxShadow = '0 6px 20px rgba(227,30,36,0.3)';
              }}
            >
              {WA_ICON}
              Enviar por WhatsApp
            </button>
          </div>
        </div>
      </div>

      {/* WhatsApp FAB — fixed bottom-right */}
      <button
        onClick={handleSubmit}
        aria-label="Enviar presupuesto por WhatsApp"
        title="Enviar presupuesto"
        style={{
          position: 'fixed',
          right: 22,
          bottom: 22,
          width: 64,
          height: 64,
          borderRadius: '50%',
          background: '#25D366',
          color: '#FFFFFF',
          border: 'none',
          cursor: 'pointer',
          display: 'grid',
          placeItems: 'center',
          boxShadow: '0 4px 12px rgba(37,211,102,0.4)',
          transition: 'transform .2s ease, box-shadow .2s ease, background .2s ease',
          zIndex: 60,
        }}
        onMouseEnter={e => {
          e.currentTarget.style.transform = 'scale(1.1)';
          e.currentTarget.style.background = '#128C7E';
          e.currentTarget.style.boxShadow = '0 6px 22px rgba(37,211,102,0.55)';
        }}
        onMouseLeave={e => {
          e.currentTarget.style.transform = 'scale(1)';
          e.currentTarget.style.background = '#25D366';
          e.currentTarget.style.boxShadow = '0 4px 12px rgba(37,211,102,0.4)';
        }}
      >
        {WA_ICON}
      </button>
    </section>
  );
}

/* Sub-components */
function Section({ label, children, last }) {
  return (
    <div style={{ marginBottom: last ? 0 : 40 }}>
      <span style={{
        display: 'block',
        fontSize: 11,
        fontWeight: 600,
        letterSpacing: '0.2em',
        color: '#E31E24',
        textTransform: 'uppercase',
        fontFamily: "'Rubik', sans-serif",
        marginBottom: 20,
        paddingBottom: 12,
        borderBottom: '1px solid #E6E6E6',
      }}>
        {label}
      </span>
      {children}
    </div>
  );
}

function Field({ label, error, children }) {
  return (
    <div style={{ marginBottom: 18 }}>
      <label style={{
        display: 'block',
        fontSize: 13,
        fontWeight: 500,
        color: '#1A1A1A',
        marginBottom: 7,
        fontFamily: "'Rubik', sans-serif",
      }}>
        {label} <span style={{ color: '#E31E24' }}>*</span>
      </label>
      {children}
      {error && (
        <div style={{
          fontSize: 12,
          color: '#E31E24',
          marginTop: 5,
          fontFamily: "'Rubik', sans-serif",
        }}>
          {error}
        </div>
      )}
    </div>
  );
}

window.FormularioPresupuesto = FormularioPresupuesto;
