const { PillButton, Input, ContactCard, SectionHeading, IconBadge, HexagonPattern } = window.CerrajerosLaSaforDesignSystem_88370e;

const RL_WINDOW_MS = 15 * 60 * 1000; // 15 minutes
const RL_MAX       = 3;               // max submissions per window
const RL_COOLDOWN  = 5 * 1000;       // 5 seconds between submits

function getRateLimitState() {
  try {
    const raw = localStorage.getItem('form_rl');
    return raw ? JSON.parse(raw) : { count: 0, firstAt: null, lastAt: null };
  } catch { return { count: 0, firstAt: null, lastAt: null }; }
}
function saveRateLimitState(s) {
  try { localStorage.setItem('form_rl', JSON.stringify(s)); } catch {}
}

function checkRateLimit() {
  const s = getRateLimitState();
  const now = Date.now();

  // Reset window if expired
  if (s.firstAt && (now - s.firstAt) > RL_WINDOW_MS) {
    const fresh = { count: 0, firstAt: null, lastAt: null };
    saveRateLimitState(fresh);
    return { allowed: true };
  }

  // Cooldown check
  if (s.lastAt && (now - s.lastAt) < RL_COOLDOWN) {
    const remaining = Math.ceil((RL_COOLDOWN - (now - s.lastAt)) / 1000);
    return { allowed: false, reason: `Espera ${remaining}s antes de enviar otro mensaje.` };
  }

  // Window count check
  if (s.count >= RL_MAX) {
    const resetAt = s.firstAt + RL_WINDOW_MS;
    const mins = Math.ceil((resetAt - now) / 60000);
    return { allowed: false, reason: `Has enviado demasiados mensajes. Inténtalo en ${mins} min.` };
  }

  return { allowed: true };
}

function recordRateLimit() {
  const s = getRateLimitState();
  const now = Date.now();
  s.count = (s.firstAt && (now - s.firstAt) <= RL_WINDOW_MS) ? s.count + 1 : 1;
  if (!s.firstAt || (now - s.firstAt) > RL_WINDOW_MS) s.firstAt = now;
  s.lastAt = now;
  saveRateLimitState(s);
}

function SiteContact() {
  const [form, setForm] = React.useState({ nombre: '', telefono: '', problema: '' });
  const [errors, setErrors] = React.useState({});
  const [sent, setSent] = React.useState(false);
  const [rlError, setRlError] = React.useState(null);

  const submit = (e) => {
    e.preventDefault();
    setRlError(null);
    const er = {};
    if (!form.nombre.trim())   er.nombre   = 'Indica tu nombre.';
    if (!form.telefono.trim()) er.telefono = 'Indica tu teléfono.';
    if (!form.problema.trim()) er.problema = 'Describe el problema.';
    setErrors(er);
    if (Object.keys(er).length !== 0) return;

    const rl = checkRateLimit();
    if (!rl.allowed) { setRlError(rl.reason); return; }

    recordRateLimit();
    setSent(true);
  };

  const Ic = (n) => <i data-lucide={n} style={{ width:'100%', height:'100%' }} />;

  return (
    <section id="contacto" style={{ background: 'var(--stone)', padding: 'var(--space-10) 0 var(--section-y)' }}>
      <div style={{ maxWidth: 'var(--content-wide)', margin: '0 auto', padding: '0 var(--gutter)' }}>
        <div className="contact-wrapper" style={{ position: 'relative', paddingTop: 56 }}>
          {/* Floating contact cards — absolutely positioned, half over the dark band */}
          <div style={{
            position: 'absolute', top: 0, left: 'var(--space-5)', right: 'var(--space-5)',
            display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: 'var(--space-4)', zIndex: 2,
          }} className="contact-cards">
            <ContactCard icon={Ic('phone')}          label="Teléfono"  value="+34 600 982 986" />
            <ContactCard icon={Ic('message-circle')} label="WhatsApp"  value="+34 600 982 986" />
            <ContactCard icon={Ic('map-pin')}        label="Dirección" value="Regne de Valencia 36, Beniflá" />
          </div>

          {/* Dark band */}
          <div className="contact-band" style={{
            position: 'relative', overflow: 'hidden',
            background: 'var(--warm)', borderRadius: 'var(--radius-xl)',
            paddingTop: 'calc(var(--space-10) + 40px)',
            paddingBottom: 'var(--space-10)',
            paddingLeft: 'var(--space-8)', paddingRight: 'var(--space-8)',
          }}>
            <HexagonPattern opacity={0.05} />

            <div style={{ position: 'relative', display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 'var(--space-10)', alignItems: 'center' }} className="contact-grid">
              <div>
                <SectionHeading eyebrow="Contacto" title={<span>¿Necesitas ayuda<br/><span style={{ color: 'var(--verde-bright)' }}>ahora mismo?</span></span>} size="lg" tone="dark" />
                <p style={{ fontFamily: 'var(--font-body)', fontSize: 16, color: 'var(--ink)', lineHeight: 1.6, maxWidth: '42ch', margin: 'var(--space-5) 0 var(--space-6)' }}>
                  Llámanos o escríbenos por WhatsApp — respondemos de inmediato, las 24 horas del día.
                </p>
                <div className="contact-cta-btns" style={{ display: 'flex', gap: 'var(--space-3)' }}>
                  <PillButton variant="bright" size="lg" href="tel:+34600982986">Llamar ahora</PillButton>
                  <PillButton variant="dark-outline" size="lg" href="https://wa.me/34600982986">WhatsApp</PillButton>
                </div>

                <div style={{ marginTop: 'var(--space-8)', display: 'flex', alignItems: 'center', gap: 'var(--space-4)' }}>
                  <IconBadge icon={Ic('clock')} tone="dark" size="sm" />
                  <div>
                    <div style={{ fontFamily: 'var(--font-display)', fontWeight: 700, color: 'var(--stone)', textTransform: 'uppercase', fontSize: 14, letterSpacing: '0.05em' }}>Tiempo medio de llegada</div>
                    <div style={{ fontFamily: 'var(--font-display)', fontWeight: 900, color: 'var(--verde-bright)', fontSize: 28, lineHeight: 1, marginTop: 4 }}>30 minutos</div>
                  </div>
                </div>
              </div>

              {/* Form card */}
              <div className="contact-form-card" style={{ background: 'var(--white)', borderRadius: 'var(--radius-xl)', padding: 'var(--space-6)', boxShadow: 'var(--shadow-lg)' }}>
                {sent ? (
                  <div style={{ textAlign: 'center', padding: 'var(--space-8) 0' }}>
                    <div style={{ display: 'inline-flex' }}><IconBadge icon={Ic('key-round')} size="lg" /></div>
                    <h3 style={{ fontFamily: 'var(--font-display)', fontWeight: 800, textTransform: 'uppercase', fontSize: 24, color: 'var(--ink)', margin: 'var(--space-4) 0 8px' }}>¡Mensaje listo!</h3>
                    <p style={{ fontFamily: 'var(--font-body)', fontSize: 14, color: 'var(--ink-2)', margin: 0 }}>Te abrimos WhatsApp para enviarlo. Respondemos enseguida.</p>
                  </div>
                ) : (
                  <form onSubmit={submit} noValidate style={{ display: 'flex', flexDirection: 'column', gap: 'var(--space-3)' }}>
                    <h3 style={{ fontFamily: 'var(--font-display)', fontWeight: 800, textTransform: 'uppercase', fontSize: 22, color: 'var(--ink)', margin: '0 0 var(--space-1)' }}>
                      Cuéntanos tu caso
                    </h3>
                    <Input label="Tu nombre" required name="nombre" placeholder="Nombre y apellidos"
                      value={form.nombre} error={errors.nombre} onChange={(e)=>setForm(f=>({...f,nombre:e.target.value}))} />
                    <Input label="Tu teléfono" required name="telefono" placeholder="+34 600 982 986"
                      value={form.telefono} error={errors.telefono} onChange={(e)=>setForm(f=>({...f,telefono:e.target.value}))} />
                    <Input label="Describe el problema" required name="problema" multiline rows={3}
                      placeholder="Ej: Se me ha cerrado la puerta y no tengo llave..."
                      value={form.problema} error={errors.problema} onChange={(e)=>setForm(f=>({...f,problema:e.target.value}))} />
                    {rlError && (
                      <div style={{
                        fontFamily: 'var(--font-body)', fontSize: 13, color: '#c0392b',
                        background: '#fdf2f2', border: '1px solid #f5c6cb',
                        borderRadius: 'var(--radius-sm)', padding: 'var(--space-3)',
                        lineHeight: 1.5,
                      }}>{rlError}</div>
                    )}
                    <button type="submit" style={{
                      marginTop: 'var(--space-2)',
                      display: 'inline-flex', alignItems: 'center', justifyContent: 'center', gap: 12,
                      width: '100%', padding: '14px 24px',
                      fontFamily: 'var(--font-body)', fontWeight: 'var(--weight-semibold)', fontSize: 16,
                      color: 'var(--white)', background: 'var(--verde-bright)', border: 'none',
                      borderRadius: 'var(--radius-sm)', cursor: 'pointer',
                      transition: 'background var(--dur-base)',
                    }}
                      onMouseEnter={(e) => { e.currentTarget.style.background = 'var(--verde-glow)'; }}
                      onMouseLeave={(e) => { e.currentTarget.style.background = 'var(--verde-bright)'; }}
                    >
                      <i data-lucide="message-circle" style={{ width: 18, height: 18 }} />
                      Enviar
                    </button>
                  </form>
                )}
              </div>
            </div>
          </div>
        </div>

        {/* Google Maps */}
        <div style={{ marginTop: 'var(--space-6)' }}>
          <div className="contact-map" style={{ borderRadius: 'var(--radius-xl)', overflow: 'hidden', boxShadow: 'var(--shadow-lg)', height: 400 }}>
            <iframe
              title="Cerrajeros La Safor — Ubicación"
              src="https://maps.google.com/maps?q=Regne+de+Valencia+36,+46722+Benifl%C3%A1,+Valencia&output=embed&z=15"
              width="100%" height="400" style={{ border: 0, display: 'block' }}
              allowFullScreen="" loading="lazy" referrerPolicy="no-referrer-when-downgrade"
            />
          </div>
          <p style={{ fontFamily: 'var(--font-body)', fontSize: 13, color: 'var(--ink-2)', textAlign: 'center', margin: 'var(--space-3) 0 0' }}>
            Regne de Valencia 36-2-C, Beniflá, 46722 · Valencia
          </p>
        </div>
      </div>
    </section>
  );
}

Object.assign(window, { SiteContact });
