/* Contacto Page */

const ContactPage = ({ goto, showToast }) => {
  useFadeIn();
  const [form, setForm] = React.useState({
    nombre: '', empresa: '', telefono: '', email: '', tipo: '', descripcion: ''
  });
  const [errors, setErrors] = React.useState({});
  const [touched, setTouched] = React.useState({});
  const [submitting, setSubmitting] = React.useState(false);

  const validate = (data) => {
    const e = {};
    if (!data.nombre.trim()) e.nombre = 'Ingresa tu nombre';
    if (!data.email.trim()) e.email = 'Ingresa tu email';
    else if (!/^[^@\s]+@[^@\s]+\.[^@\s]+$/.test(data.email)) e.email = 'Email inválido';
    if (!data.telefono.trim()) e.telefono = 'Ingresa un teléfono';
    if (!data.tipo) e.tipo = 'Selecciona un servicio';
    if (!data.descripcion.trim() || data.descripcion.trim().length < 10)
      e.descripcion = 'Cuéntanos un poco más (mín. 10 caracteres)';
    return e;
  };

  const update = (key, value) => {
    const next = { ...form, [key]: value };
    setForm(next);
    if (touched[key] || errors[key]) {
      setErrors(validate(next));
    }
  };

  const blur = (key) => {
    setTouched(t => ({ ...t, [key]: true }));
    setErrors(validate(form));
  };

  const submit = (e) => {
    e.preventDefault();
    const all = { nombre: true, empresa: true, telefono: true, email: true, tipo: true, descripcion: true };
    setTouched(all);
    const errs = validate(form);
    setErrors(errs);
    if (Object.keys(errs).length === 0) {
      setSubmitting(true);
      setTimeout(() => {
        setSubmitting(false);
        showToast('Consulta enviada. Te contactamos en menos de 24 horas.');
        setForm({ nombre: '', empresa: '', telefono: '', email: '', tipo: '', descripcion: '' });
        setTouched({});
      }, 900);
    }
  };

  const fieldClass = (key) => {
    if (errors[key] && touched[key]) return 'field error';
    if (touched[key] && !errors[key] && form[key]) return 'field valid';
    return 'field';
  };

  return (
    <div data-screen-label="Contacto">
      <PageHeader
        current="Contacto"
        title="Hablemos de tu proyecto"
        subtitle="Cuéntanos qué necesitas fabricar o montar. Nuestro equipo técnico evalúa, cotiza y agenda una visita a faena si corresponde."
        goto={goto}
      />

      <section className="section" style={{ paddingTop: 72 }}>
        <div className="container">
          <div className="contact-grid">

            {/* Form */}
            <form className="contact-form fade-in" onSubmit={submit} noValidate>
              <h2>Formulario de cotización</h2>
              <div className="form-sub">Respondemos a todas las consultas en menos de 24 horas hábiles.</div>

              <div className="form-row">
                <div className={fieldClass('nombre')}>
                  <label>Nombre <span className="req">*</span></label>
                  <input type="text" value={form.nombre}
                         onChange={e => update('nombre', e.target.value)}
                         onBlur={() => blur('nombre')}
                         placeholder="Tu nombre" />
                  {errors.nombre && touched.nombre && <span className="err-msg">{errors.nombre}</span>}
                </div>
                <div className={fieldClass('empresa')}>
                  <label>Empresa</label>
                  <input type="text" value={form.empresa}
                         onChange={e => update('empresa', e.target.value)}
                         placeholder="Opcional" />
                </div>
              </div>

              <div className="form-row">
                <div className={fieldClass('telefono')}>
                  <label>Teléfono <span className="req">*</span></label>
                  <input type="tel" value={form.telefono}
                         onChange={e => update('telefono', e.target.value)}
                         onBlur={() => blur('telefono')}
                         placeholder="+56 9 1234 5678" />
                  {errors.telefono && touched.telefono && <span className="err-msg">{errors.telefono}</span>}
                </div>
                <div className={fieldClass('email')}>
                  <label>Email <span className="req">*</span></label>
                  <input type="email" value={form.email}
                         onChange={e => update('email', e.target.value)}
                         onBlur={() => blur('email')}
                         placeholder="nombre@empresa.cl" />
                  {errors.email && touched.email && <span className="err-msg">{errors.email}</span>}
                </div>
              </div>

              <div className={fieldClass('tipo')}>
                <label>Tipo de servicio <span className="req">*</span></label>
                <select value={form.tipo}
                        onChange={e => update('tipo', e.target.value)}
                        onBlur={() => blur('tipo')}>
                  <option value="">Selecciona una especialidad…</option>
                  {SERVICES.map(s => <option key={s.id} value={s.id}>{s.title}</option>)}
                  <option value="otro">Otro / Consulta general</option>
                </select>
                {errors.tipo && touched.tipo && <span className="err-msg">{errors.tipo}</span>}
              </div>

              <div className={fieldClass('descripcion')}>
                <label>Descripción del proyecto <span className="req">*</span></label>
                <textarea value={form.descripcion}
                          onChange={e => update('descripcion', e.target.value)}
                          onBlur={() => blur('descripcion')}
                          placeholder="Cuéntanos qué necesitas: tipo de obra, plazos, ubicación, planos disponibles…" />
                {errors.descripcion && touched.descripcion && <span className="err-msg">{errors.descripcion}</span>}
              </div>

              <div className="form-foot">
                <button type="submit" className="btn btn-primary" disabled={submitting}>
                  {submitting
                    ? <>Enviando… </>
                    : <>Enviar consulta <Icon name="send" size={16} /></>}
                </button>
              </div>
            </form>

            {/* Info */}
            <div className="contact-info fade-in">
              <a className="info-card" href="https://wa.me/56992278159" target="_blank" rel="noreferrer">
                <div className="info-icon wa"><Icon name="whatsapp" size={22} /></div>
                <div>
                  <div className="label">WhatsApp directo</div>
                  <div className="value">+56 9 9227 8159</div>
                  <div className="sub">Juan Carlos Mora · Gerencia</div>
                </div>
              </a>

              <a className="info-card" href="https://wa.me/56967316510" target="_blank" rel="noreferrer">
                <div className="info-icon wa"><Icon name="whatsapp" size={22} /></div>
                <div>
                  <div className="label">WhatsApp técnico</div>
                  <div className="value">+56 9 6731 6510</div>
                  <div className="sub">Claudio Mesina · Operaciones</div>
                </div>
              </a>

              <a className="info-card" href="mailto:contacto@moramontajes.cl">
                <div className="info-icon mail"><Icon name="mail" size={20} /></div>
                <div>
                  <div className="label">Correo electrónico</div>
                  <div className="value">contacto@moramontajes.cl</div>
                  <div className="sub">Para cotizaciones y consultas técnicas</div>
                </div>
              </a>

              <div className="info-card">
                <div className="info-icon loc"><Icon name="pin" size={20} /></div>
                <div>
                  <div className="label">Ubicación</div>
                  <div className="value">El Trapiche S/N Parcela N°1</div>
                  <div className="sub">Región de Valparaíso, Chile</div>
                </div>
              </div>

              <div className="map-wrap">
                <MapPlaceholder />
              </div>
            </div>

          </div>
        </div>
      </section>

      <section className="response-strip">
        <div className="container">
          <div className="inner">
            <span className="pulse"></span>
            <Icon name="clock" size={18} />
            Tiempo de respuesta habitual: <strong style={{ fontWeight: 700, marginLeft: 4 }}>menos de 24 horas</strong>
          </div>
        </div>
      </section>
    </div>
  );
};

/* Stylized map placeholder — grid + street lines + pin */
const MapPlaceholder = () => (
  <div style={{
    position: 'absolute', inset: 0,
    background: 'linear-gradient(180deg, #e8eef5 0%, #dbe5f0 100%)',
    overflow: 'hidden'
  }}>
    <svg width="100%" height="100%" viewBox="0 0 400 280" preserveAspectRatio="xMidYMid slice"
         style={{ position: 'absolute', inset: 0 }}>
      <defs>
        <pattern id="grid" width="32" height="32" patternUnits="userSpaceOnUse">
          <path d="M32 0H0V32" fill="none" stroke="rgba(30,58,95,0.07)" strokeWidth="1"/>
        </pattern>
      </defs>
      <rect width="100%" height="100%" fill="url(#grid)" />
      {/* roads */}
      <path d="M-20 180 Q120 140 220 170 T 420 130" fill="none" stroke="#fff" strokeWidth="14" />
      <path d="M-20 180 Q120 140 220 170 T 420 130" fill="none" stroke="#cfd8e3" strokeWidth="1" />
      <path d="M80 -20 Q90 100 140 160 T 200 300" fill="none" stroke="#fff" strokeWidth="10" />
      <path d="M80 -20 Q90 100 140 160 T 200 300" fill="none" stroke="#cfd8e3" strokeWidth="1" />
      <path d="M300 -20 L 310 300" stroke="#fff" strokeWidth="6" />
      <path d="M300 -20 L 310 300" stroke="#cfd8e3" strokeWidth="1" strokeDasharray="4 4" />
      {/* blocks */}
      <rect x="20" y="40" width="50" height="40" fill="rgba(30,58,95,0.06)" rx="3" />
      <rect x="210" y="30" width="70" height="60" fill="rgba(30,58,95,0.06)" rx="3" />
      <rect x="220" y="200" width="60" height="50" fill="rgba(30,58,95,0.06)" rx="3" />
      <rect x="340" y="160" width="50" height="60" fill="rgba(30,58,95,0.06)" rx="3" />
    </svg>

    {/* Pin */}
    <div style={{
      position: 'absolute', top: '50%', left: '50%',
      transform: 'translate(-50%, -100%)',
    }}>
      <div style={{
        background: '#2563EB', color: '#fff',
        width: 44, height: 44, borderRadius: '50% 50% 50% 4px',
        transform: 'rotate(-45deg)',
        display: 'grid', placeItems: 'center',
        boxShadow: '0 8px 20px rgba(37,99,235,0.45)'
      }}>
        <div style={{ transform: 'rotate(45deg)' }}>
          <Icon name="pin" size={20} stroke={2.2} />
        </div>
      </div>
      <div style={{
        position: 'absolute', top: 44, left: '50%',
        transform: 'translateX(-50%)',
        width: 16, height: 6, borderRadius: '50%',
        background: 'rgba(0,0,0,0.18)', filter: 'blur(2px)'
      }}></div>
    </div>

    <div style={{
      position: 'absolute', bottom: 12, left: 12,
      background: '#fff', padding: '8px 14px', borderRadius: 6,
      fontSize: 12.5, fontWeight: 600, color: 'var(--navy)',
      boxShadow: '0 2px 8px rgba(0,0,0,0.1)',
      display: 'flex', alignItems: 'center', gap: 8
    }}>
      <Icon name="pin" size={14} />
      El Trapiche S/N · Valparaíso
    </div>

    <div style={{
      position: 'absolute', top: 12, right: 12,
      fontFamily: "'JetBrains Mono', monospace",
      fontSize: 10, color: 'rgba(30,58,95,0.5)',
      textTransform: 'uppercase', letterSpacing: '0.15em'
    }}>
      [ google maps embed ]
    </div>
  </div>
);

Object.assign(window, { ContactPage });
