
const SERVICES_LIST = ['Construcción y Remodelación','Mantenimiento Integral','Albercas','Jardinería','Electricidad','Plomería','Limpieza Profesional','Aires Acondicionados','Paneles Solares','Tarjeteros RFID','Automatización','Pintura','Impermeabilizado','Otro'];

const EJS_SERVICE  = 'service_taw4gtd';
const EJS_TEMPLATE = 'template_a0prqfo';

const TLQuote = () => {
  const [form, setForm] = React.useState({ nombre:'', empresa:'', tel:'', email:'', servicio:'', ubicacion:'', desc:'', presupuesto:'', fecha:'' });
  const [sent, setSent] = React.useState(false);
  const [loading, setLoading] = React.useState(false);
  const [error, setError] = React.useState('');
  const set = (k) => (e) => setForm(f => ({ ...f, [k]: e.target.value }));

  const inputStyle = {
    width: '100%', boxSizing: 'border-box',
    fontFamily: 'Inter, sans-serif', fontSize: 14, color: '#1D1D1F',
    background: '#F5F5F7', border: '1.5px solid #E5E5EA', borderRadius: 12,
    padding: '14px 16px', outline: 'none', transition: 'all 0.2s',
  };
  const focus = (e) => { e.target.style.borderColor = '#1D1D1F'; e.target.style.background = '#fff'; };
  const blur = (e) => { e.target.style.borderColor = '#E5E5EA'; e.target.style.background = '#F5F5F7'; };
  const labelStyle = { fontFamily: 'Inter, sans-serif', fontWeight: 600, fontSize: 12, color: '#3D3D3F', letterSpacing: 0.3, display: 'block', marginBottom: 7 };

  const handleSubmit = async (e) => {
    e.preventDefault();
    setLoading(true);
    setError('');
    try {
      await window.emailjs.send(EJS_SERVICE, EJS_TEMPLATE, {
        name: form.nombre,
        from_name: form.nombre,
        from_email: form.email,
        phone: form.tel,
        service: form.servicio,
        message: `Empresa: ${form.empresa}\nUbicación: ${form.ubicacion}\nPresupuesto: ${form.presupuesto}\nFecha deseada: ${form.fecha}\n\n${form.desc}`,
      }, { publicKey: '4qmrVdouMua1Zsquq' });
      setSent(true);
    } catch (err) {
      console.error('EmailJS error:', err);
      setError('No se pudo enviar. Por favor intenta de nuevo o contáctanos por WhatsApp.');
    }
    setLoading(false);
  };

  return (
    <section id="cotizar" style={{ background: '#fff', padding: '100px 40px' }}>
      <div style={{ maxWidth: 1200, margin: '0 auto', display: 'grid', gridTemplateColumns: '1fr 1.6fr', gap: 80, alignItems: 'start' }}>
        {/* Left */}
        <div style={{ position: 'sticky', top: 100 }}>
          <div style={{ fontFamily: 'Inter, sans-serif', fontWeight: 600, fontSize: 12, color: '#1D1D1F', letterSpacing: 3, textTransform: 'uppercase', marginBottom: 20 }}>Presupuesto</div>
          <h2 style={{ fontFamily: 'Inter, sans-serif', fontWeight: 800, fontSize: 'clamp(28px, 3.5vw, 44px)', color: '#1D1D1F', letterSpacing: -1.5, margin: '0 0 20px', lineHeight: 1.1 }}>Solicita tu cotización profesional</h2>
          <p style={{ fontFamily: 'Inter, sans-serif', fontSize: 16, color: '#9E9EA3', lineHeight: 1.7, margin: '0 0 40px' }}>Cuéntanos tu proyecto y te respondemos con una propuesta clara y detallada en menos de 24 horas.</p>
          {[
            { icon: 'M13 10V3L4 14h7v7l9-11h-7z', t: 'Respuesta en menos de 24h', s: 'Revisamos tu solicitud con atención inmediata.' },
            { icon: 'M9 12l2 2 4-4m6 2a9 9 0 11-18 0 9 9 0 0118 0z', t: 'Cotización detallada y transparente', s: 'Sin sorpresas ni costos ocultos. Todo por escrito.' },
            { icon: 'M17 20h5v-2a3 3 0 00-5.356-1.857M17 20H7m10 0v-2c0-.656-.126-1.283-.356-1.857M7 20H2v-2a3 3 0 015.356-1.857M7 20v-2c0-.656.126-1.283.356-1.857m0 0a5.002 5.002 0 019.288 0M15 7a3 3 0 11-6 0 3 3 0 016 0z', t: 'Asesor asignado personalmente', s: 'Un especialista dedicado a tu proyecto.' },
          ].map(item => (
            <div key={item.t} style={{ display: 'flex', gap: 16, marginBottom: 24 }}>
              <div style={{ width: 40, height: 40, borderRadius: 12, background: '#F5F5F7', display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0 }}>
                <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="#1D1D1F" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round"><path d={item.icon}/></svg>
              </div>
              <div><div style={{ fontFamily: 'Inter, sans-serif', fontWeight: 700, fontSize: 14, color: '#1D1D1F', marginBottom: 4 }}>{item.t}</div><div style={{ fontFamily: 'Inter, sans-serif', fontSize: 13, color: '#9E9EA3', lineHeight: 1.6 }}>{item.s}</div></div>
            </div>
          ))}
          <div style={{ background: '#F5F5F7', border: '1px solid #E5E5EA', borderRadius: 16, padding: 20, marginTop: 8 }}>
            <div style={{ fontFamily: 'Inter, sans-serif', fontWeight: 700, fontSize: 13, color: '#1D1D1F', marginBottom: 4 }}>¿Necesitas hablar ahora?</div>
            <a href="https://wa.me/5529086846" target="_blank" rel="noopener noreferrer" style={{ fontFamily: 'Inter, sans-serif', fontSize: 14, color: '#1D1D1F', fontWeight: 600, textDecoration: 'none', display: 'flex', alignItems: 'center', gap: 6 }}>
              <svg width="16" height="16" viewBox="0 0 24 24" fill="#25D366"><path d="M17.472 14.382c-.297-.149-1.758-.867-2.03-.967-.273-.099-.471-.148-.67.15-.197.297-.767.966-.94 1.164-.173.199-.347.223-.644.075-.297-.15-1.255-.463-2.39-1.475-.883-.788-1.48-1.761-1.653-2.059-.173-.297-.018-.458.13-.606.134-.133.298-.347.446-.52.149-.174.198-.298.298-.497.099-.198.05-.371-.025-.52-.075-.149-.669-1.612-.916-2.207-.242-.579-.487-.5-.669-.51-.173-.008-.371-.01-.57-.01-.198 0-.52.074-.792.372-.272.297-1.04 1.016-1.04 2.479 0 1.462 1.065 2.875 1.213 3.074.149.198 2.096 3.2 5.077 4.487.709.306 1.262.489 1.694.625.712.227 1.36.195 1.871.118.571-.085 1.758-.719 2.006-1.413.248-.694.248-1.289.173-1.413-.074-.124-.272-.198-.57-.347m-5.421 7.403h-.004a9.87 9.87 0 01-5.031-1.378l-.361-.214-3.741.982.998-3.648-.235-.374a9.86 9.86 0 01-1.51-5.26c.001-5.45 4.436-9.884 9.888-9.884 2.64 0 5.122 1.03 6.988 2.898a9.825 9.825 0 012.893 6.994c-.003 5.45-4.437 9.884-9.885 9.884m8.413-18.297A11.815 11.815 0 0012.05 0C5.495 0 .16 5.335.157 11.892c0 2.096.547 4.142 1.588 5.945L.057 24l6.305-1.654a11.882 11.882 0 005.683 1.448h.005c6.554 0 11.89-5.335 11.893-11.893a11.821 11.821 0 00-3.48-8.413z"/></svg>
              WhatsApp: (55) 2908 6846
            </a>
          </div>
        </div>

        {/* Form */}
        <div>
          {sent ? (
            <div style={{ textAlign: 'center', padding: '60px 40px', background: '#F0FDF4', borderRadius: 24, border: '1px solid #BBF7D0' }}>
              <div style={{ fontSize: 48, marginBottom: 16 }}>✓</div>
              <h3 style={{ fontFamily: 'Inter, sans-serif', fontWeight: 800, fontSize: 24, color: '#166534', margin: '0 0 12px' }}>¡Solicitud recibida!</h3>
              <p style={{ fontFamily: 'Inter, sans-serif', fontSize: 16, color: '#15803D', margin: 0 }}>Te contactaremos en menos de 24 horas con tu cotización profesional.</p>
              <button onClick={() => setSent(false)} style={{ marginTop: 24, background: '#166534', color: '#fff', border: 'none', cursor: 'pointer', fontFamily: 'Inter, sans-serif', fontWeight: 600, fontSize: 14, padding: '12px 28px', borderRadius: 10 }}>Nueva solicitud</button>
            </div>
          ) : (
            <form onSubmit={handleSubmit} style={{ display: 'flex', flexDirection: 'column', gap: 20 }}>
              <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 16 }}>
                <div><label style={labelStyle}>Nombre completo *</label><input required style={inputStyle} placeholder="Ej. Carlos Hernández" value={form.nombre} onChange={set('nombre')} onFocus={focus} onBlur={blur}/></div>
                <div><label style={labelStyle}>Empresa / Condominio / Hotel</label><input style={inputStyle} placeholder="Nombre del proyecto o empresa" value={form.empresa} onChange={set('empresa')} onFocus={focus} onBlur={blur}/></div>
              </div>
              <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 16 }}>
                <div><label style={labelStyle}>Teléfono *</label><input required style={inputStyle} placeholder="+52 55 0000 0000" value={form.tel} onChange={set('tel')} onFocus={focus} onBlur={blur}/></div>
                <div><label style={labelStyle}>Correo electrónico *</label><input required type="email" style={inputStyle} placeholder="tu@correo.com" value={form.email} onChange={set('email')} onFocus={focus} onBlur={blur}/></div>
              </div>
              <div><label style={labelStyle}>Tipo de servicio *</label>
                <select required style={inputStyle} value={form.servicio} onChange={set('servicio')} onFocus={focus} onBlur={blur}>
                  <option value="">Selecciona un servicio</option>
                  {SERVICES_LIST.map(s => <option key={s} value={s}>{s}</option>)}
                </select>
              </div>
              <div><label style={labelStyle}>Ubicación del proyecto *</label><input required style={inputStyle} placeholder="Ciudad, colonia o dirección general" value={form.ubicacion} onChange={set('ubicacion')} onFocus={focus} onBlur={blur}/></div>
              <div><label style={labelStyle}>Descripción del proyecto</label><textarea style={{ ...inputStyle, minHeight: 110, resize: 'vertical' }} placeholder="Cuéntanos qué necesitas, el alcance, materiales específicos o cualquier detalle relevante..." value={form.desc} onChange={set('desc')} onFocus={focus} onBlur={blur}/></div>
              <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 16 }}>
                <div><label style={labelStyle}>Presupuesto estimado</label>
                  <select style={inputStyle} value={form.presupuesto} onChange={set('presupuesto')} onFocus={focus} onBlur={blur}>
                    <option value="">Sin definir</option>
                    <option>Menos de $10,000</option>
                    <option>$10,000 – $50,000</option>
                    <option>$50,000 – $150,000</option>
                    <option>$150,000 – $500,000</option>
                    <option>Más de $500,000</option>
                  </select>
                </div>
                <div><label style={labelStyle}>Fecha deseada</label><input type="date" style={inputStyle} value={form.fecha} onChange={set('fecha')} onFocus={focus} onBlur={blur}/></div>
              </div>
              <div>
                <label style={labelStyle}>Fotografías o archivos</label>
                <div style={{ background: '#F5F5F7', border: '2px dashed #D1D1D6', borderRadius: 12, padding: '24px', textAlign: 'center', cursor: 'pointer' }}
                  onMouseEnter={e => { e.currentTarget.style.borderColor = '#1D1D1F'; e.currentTarget.style.background = '#F5F5F7'; }}
                  onMouseLeave={e => { e.currentTarget.style.borderColor = '#D1D1D6'; e.currentTarget.style.background = '#F5F5F7'; }}
                >
                  <svg width="28" height="28" viewBox="0 0 24 24" fill="none" stroke="#9E9EA3" strokeWidth="1.5" strokeLinecap="round" style={{ marginBottom: 8 }}><path d="M21 15v4a2 2 0 01-2 2H5a2 2 0 01-2-2v-4M17 8l-5-5-5 5M12 3v12"/></svg>
                  <div style={{ fontFamily: 'Inter, sans-serif', fontSize: 13, color: '#9E9EA3' }}>Arrastra archivos o <span style={{ color: '#1D1D1F', fontWeight: 600 }}>haz clic para subir</span></div>
                  <div style={{ fontFamily: 'Inter, sans-serif', fontSize: 11, color: '#D1D1D6', marginTop: 4 }}>JPG, PNG, PDF hasta 20MB</div>
                </div>
              </div>
              {error && (
                <div style={{ background: '#FFF1F2', border: '1px solid #FECDD3', borderRadius: 12, padding: '14px 18px', fontFamily: 'Inter, sans-serif', fontSize: 13, color: '#BE123C' }}>
                  {error}
                </div>
              )}
              <button type="submit" disabled={loading} style={{
                background: loading ? '#6E6E73' : '#1D1D1F', color: '#fff', border: 'none',
                cursor: loading ? 'not-allowed' : 'pointer',
                fontFamily: 'Inter, sans-serif', fontWeight: 700, fontSize: 16,
                padding: '18px 0', borderRadius: 14, width: '100%',
                boxShadow: '0 8px 32px rgba(10,22,40,0.25)', transition: 'all 0.25s',
                letterSpacing: -0.2,
              }}
              onMouseEnter={e => { if (!loading) { e.target.style.transform = 'translateY(-2px)'; e.target.style.boxShadow = '0 16px 48px rgba(10,22,40,0.35)'; }}}
              onMouseLeave={e => { e.target.style.transform = 'none'; e.target.style.boxShadow = '0 8px 32px rgba(10,22,40,0.25)'; }}
              >
                {loading ? 'Enviando...' : 'Solicitar presupuesto →'}
              </button>
            </form>
          )}
        </div>
      </div>
    </section>
  );
};

Object.assign(window, { TLQuote });
