// ============================================================
//  Qestylo — final CTA + contact + footer + App
// ============================================================
const { useState, useEffect, useRef, useCallback } = React;

// ---------------- 9 · CONTACTO + CTA FINAL ----------------
function Contacto({ prefillMessage }) {
  const [form, setForm] = useState({ nombre: '', telefono: '', mensaje: '' });
  const [touched, setTouched] = useState(false);
  const [sent, setSent] = useState(false);
  const [isSubmitting, setIsSubmitting] = useState(false);

  useEffect(() => {
    if (prefillMessage) {
      setForm((f) => ({ ...f, mensaje: prefillMessage }));
    }
  }, [prefillMessage]);

  const errors = {
    nombre: form.nombre.trim().length < 2,
    telefono: !/^[0-9+\s]{6,}$/.test(form.telefono.trim()),
  };
  const valid = !errors.nombre && !errors.telefono;

  const set = (k) => (e) => setForm((f) => ({ ...f, [k]: e.target.value }));

  const submit = async () => {
    setTouched(true);
    if (!valid) return;
    
    setIsSubmitting(true);
    try {
      await fetch('https://formsubmit.co/ajax/qestylo@qestylo.com', {
        method: 'POST',
        headers: { 
          'Content-Type': 'application/json',
          'Accept': 'application/json'
        },
        body: JSON.stringify({
          _subject: `Nuevo Presupuesto Web — ${form.nombre}`,
          _template: 'box',
          Nombre: form.nombre,
          Teléfono: form.telefono,
          Detalles: form.mensaje || 'No especificado'
        })
      });
    } catch (error) {
      console.error('Error enviando formulario:', error);
    } finally {
      setIsSubmitting(false);
      setSent(true);
    }
  };

  const field = (label, key, props = {}) => (
    <div>
      <label className="block text-xs font-medium uppercase tracking-[0.14em] text-muted mb-2">{label}</label>
      <input
        value={form[key]}
        onChange={set(key)}
        onBlur={() => setTouched(true)}
        className={`focus-ring w-full rounded-lg bg-ink/60 border px-4 py-3.5 text-[15px] text-cream placeholder:text-muted/60 transition-colors ${touched && errors[key] ? 'border-amber/70' : 'border-white/10'
          }`}
        {...props}
      />
      {touched && errors[key] && (
        <p className="mt-1.5 text-xs text-amber">{key === 'nombre' ? 'Dinos tu nombre.' : 'Necesitamos un teléfono válido.'}</p>
      )}
    </div>
  );

  return (
    <section id="contacto" className="relative z-10 bg-ink px-6 md:px-12 lg:px-16 py-20 md:py-32 lg:py-40" data-screen-label="Contacto">
      <div className="max-w-6xl mx-auto grid lg:grid-cols-2 gap-12 lg:gap-20 items-center">
        {/* left — pitch */}
        <Reveal>
          <Eyebrow>Tu presupuesto</Eyebrow>
          <h2 className="font-serif font-light leading-[1.05] tracking-[-0.02em] text-4xl md:text-5xl lg:text-6xl text-cream">
            Tu presupuesto, gratis y a tu medida
          </h2>
          <p className="mt-6 max-w-md text-[15px] font-light leading-relaxed text-muted">
            Cuéntanos qué quieres cambiar y te respondemos sin compromiso. ¿Prefieres ver toda
            nuestra obra primero? Te llevamos a{' '}
            <a href="https://www.qestylo.com/" target="_blank" rel="noopener noreferrer" className="text-amber underline-offset-4 hover:underline">qestylo.com</a>.
          </p>
          {/* Contact info grid */}
          <div className="mt-8 grid sm:grid-cols-2 gap-6">
            <div className="flex items-center gap-3">
              <span className="flex h-10 w-10 shrink-0 items-center justify-center rounded-lg bg-surface text-amber border border-white/5 shadow-sm">
                <Icon name="phone" size={18} />
              </span>
              <div>
                <p className="text-[10px] font-semibold uppercase tracking-wider text-muted">Teléfono</p>
                <a href="tel:983266408" className="text-sm text-cream hover:text-amber transition-colors font-light">
                  983 266 408
                </a>
              </div>
            </div>

            <div className="flex items-center gap-3">
              <span className="flex h-10 w-10 shrink-0 items-center justify-center rounded-lg bg-surface text-amber border border-white/5 shadow-sm">
                <Icon name="mail" size={18} />
              </span>
              <div>
                <p className="text-[10px] font-semibold uppercase tracking-wider text-muted">Email / Gmail</p>
                <a href="mailto:qestylo@qestylo.com" className="text-sm text-cream hover:text-amber transition-colors font-light">
                  qestylo@qestylo.com
                </a>
              </div>
            </div>

            <div className="flex items-center gap-3 sm:col-span-2">
              <span className="flex h-10 w-10 shrink-0 items-center justify-center rounded-lg bg-surface text-amber border border-white/5 shadow-sm">
                <Icon name="map-pin" size={18} />
              </span>
              <div>
                <p className="text-[10px] font-semibold uppercase tracking-wider text-muted">Dirección</p>
                <span className="text-sm text-cream font-light">
                  C/ Puente Colgante 16, 47007 Valladolid
                </span>
              </div>
            </div>
          </div>

          {/* Social networks section */}
          <div className="mt-10 pt-8 border-t border-white/5">
            <p className="text-xs font-semibold uppercase tracking-[0.14em] text-muted mb-4">Síguenos en nuestras Redes Sociales</p>
            <div className="flex flex-wrap gap-3">
              {/* Instagram */}
              <a
                href="https://www.instagram.com/qe_stylo/"
                target="_blank"
                rel="noopener noreferrer"
                className="liquid-glass flex items-center justify-center h-11 w-11 rounded-lg border border-white/10 text-muted hover:text-white hover:bg-gradient-to-tr hover:from-[#f9ce34] hover:via-[#ee2a7b] hover:to-[#6228d7] hover:border-transparent transition-all duration-300"
                title="Instagram"
              >
                <svg className="w-5 h-5 fill-current" viewBox="0 0 24 24">
                  <path d="M12 2.163c3.204 0 3.584.012 4.85.07 3.252.148 4.771 1.691 4.919 4.919.058 1.265.069 1.645.069 4.849 0 3.205-.012 3.584-.069 4.849-.149 3.225-1.664 4.771-4.919 4.919-1.266.058-1.644.07-4.85.07-3.204 0-3.584-.012-4.849-.07-3.26-.149-4.771-1.699-4.919-4.92-.058-1.265-.07-1.644-.07-4.849 0-3.204.013-3.583.07-4.849.149-3.227 1.664-4.771 4.919-4.919 1.266-.057 1.645-.069 4.849-.069zM12 0C8.741 0 8.333.014 7.053.072 2.695.272.273 2.69.073 7.051.014 8.333 0 8.741 0 12c0 3.259.014 3.668.072 4.948.2 4.358 2.618 6.78 6.98 6.98 1.281.058 1.689.072 4.948.072 3.259 0 3.668-.014 4.948-.072 4.354-.2 6.782-2.618 6.979-6.98.059-1.28.073-1.689.073-4.948 0-3.259-.014-3.667-.072-4.947-.196-4.354-2.617-6.78-6.979-6.98C15.668.014 15.259 0 12 0zm0 5.838a6.162 6.162 0 100 12.324 6.162 6.162 0 000-12.324zM12 16a4 4 0 110-8 4 4 0 010 8zm6.406-11.845a1.44 1.44 0 100 2.881 1.44 1.44 0 000-2.881z"/>
                </svg>
              </a>

              {/* Facebook */}
              <a
                href="https://www.facebook.com/people/Grupo-Qe-Stylo/100059304493319/?locale=es_ES"
                target="_blank"
                rel="noopener noreferrer"
                className="liquid-glass flex items-center justify-center h-11 w-11 rounded-lg border border-white/10 text-muted hover:text-white hover:bg-[#1877F2] hover:border-transparent transition-all duration-300"
                title="Facebook"
              >
                <svg className="w-5 h-5 fill-current" viewBox="0 0 24 24">
                  <path d="M24 12.073c0-6.627-5.373-12-12-12s-12 5.373-12 12c0 5.99 4.388 10.954 10.125 11.854v-8.385H7.078v-3.47h3.047V9.43c0-3.007 1.792-4.669 4.533-4.669 1.312 0 2.686.235 2.686.235v2.953H15.83c-1.491 0-1.956.925-1.956 1.874v2.25h3.328l-.532 3.47h-2.796v8.385C19.612 23.027 24 18.062 24 12.073z"/>
                </svg>
              </a>

              {/* TikTok */}
              <a
                href="#"
                className="liquid-glass flex items-center justify-center h-11 w-11 rounded-lg border border-white/10 text-muted hover:text-white hover:bg-black hover:border-transparent transition-all duration-300"
                title="TikTok"
              >
                <svg className="w-5 h-5 fill-current" viewBox="0 0 24 24">
                  <path d="M12.525.02c1.31-.02 2.61-.01 3.91-.02.08 1.53.63 3.02 1.59 4.23.94 1.15 2.25 1.95 3.66 2.3v3.91c-.99-.07-1.96-.36-2.85-.82-.93-.49-1.74-1.18-2.38-2.02v6.62c.01 1.76-.52 3.47-1.52 4.88-.99 1.39-2.4 2.37-4.01 2.79-1.6.43-3.3.31-4.83-.34-1.53-.65-2.79-1.84-3.56-3.37-.8-1.58-1.02-3.4-.63-5.11.39-1.72 1.36-3.25 2.74-4.3 1.38-1.04 3.1-1.56 4.84-1.46v3.97c-.89-.04-1.78.22-2.51.74-.71.51-1.22 1.28-1.43 2.15-.22.88-.08 1.81.39 2.59.47.78 1.25 1.32 2.15 1.52.9.21 1.85.04 2.63-.46.78-.51 1.31-1.34 1.48-2.27.05-.28.07-.57.07-.85V.02z"/>
                </svg>
              </a>
            </div>
          </div>

          <p className="mt-8 text-xs font-light leading-relaxed text-muted/50 max-w-sm">
            Presupuesto sin compromiso · Respuesta en menos de 24 h · Instalación con la cobertura
            de la Red Oficial Kömmerling (CAES).
          </p>
        </Reveal>

        {/* right — contact (no <form> tag, onClick only) */}
        <Reveal delay={120}>
          <div className="liquid-glass rounded-2xl p-7 md:p-9">
            {!sent ? (
              <div className="space-y-5">
                {field('Nombre', 'nombre', { placeholder: 'Tu nombre', type: 'text' })}
                {field('Teléfono', 'telefono', { placeholder: '983 000 000', type: 'tel' })}
                <div>
                  <label className="block text-xs font-medium uppercase tracking-[0.14em] text-muted mb-2">¿Qué necesitas? (opcional)</label>
                  <textarea
                    value={form.mensaje}
                    onChange={set('mensaje')}
                    rows={3}
                    placeholder="Ej. cambiar las 4 ventanas del salón y dos dormitorios"
                    className="focus-ring w-full rounded-lg bg-ink/60 border border-white/10 px-4 py-3.5 text-[15px] text-cream placeholder:text-muted/60 resize-none"
                  ></textarea>
                </div>
                <PrimaryCTA href="#" onClick={(e) => { e.preventDefault(); submit(); }} className={`w-full ${isSubmitting ? 'opacity-75 pointer-events-none' : ''}`}>
                  {isSubmitting ? 'Enviando...' : 'Pide presupuesto'}
                  {!isSubmitting && <Icon name="arrow-right" size={18} />}
                </PrimaryCTA>
                <p className="text-[11px] font-light text-muted/60 text-center">
                  Al enviar aceptas que te contactemos sobre tu solicitud.
                </p>
              </div>
            ) : (
              <div className="text-center py-10">
                <span className="inline-flex text-amber mb-4"><Icon name="circle-check" size={40} /></span>
                <h3 className="font-serif text-2xl font-normal text-cream">¡Gracias, {form.nombre.split(' ')[0]}!</h3>
                <p className="mt-3 text-sm font-light text-muted max-w-xs mx-auto">
                  Hemos abierto tu solicitud. Si lo prefieres, llámanos al 983 266 408 y lo cerramos por teléfono.
                </p>
              </div>
            )}
          </div>
        </Reveal>
      </div>
    </section>
  );
}

// ---------------- FOOTER ----------------
function Footer({ onOpenLegal }) {
  const links = [
    ['Ventanas', '#solucion'],
    ['Puertas', '#puertas'],
    ['Persianas', '#persianas'],
    ['Cómo funciona', '#como'],
    ['qestylo.com', 'https://www.qestylo.com/'],
    ['Aviso legal', 'legal'],
    ['Privacidad', 'privacidad'],
    ['Política de Cookies', 'cookies'],
  ];
  return (
    <footer className="relative z-10 bg-ink border-t border-surface/40 px-6 md:px-12 lg:px-16 py-12">
      <div className="max-w-6xl mx-auto flex flex-col md:flex-row md:items-end justify-between gap-8">
        <div>
          <div className="flex items-center gap-3">
            <img src="assets/logo.png" alt="Qestylo" className="h-7 md:h-8 w-auto object-contain" />
            <span className="text-[11px] font-light uppercase tracking-[0.18em] text-muted">Distribuidor oficial Kömmerling</span>
          </div>
          <div className="mt-4 text-sm font-light text-muted leading-relaxed">
            C/ Puente Colgante 16, 47007 Valladolid<br />
            <a href="tel:983266408" className="hover:text-amber transition-colors">983 266 408</a>
            {' · '}
            <a href="mailto:qestylo@qestylo.com" className="hover:text-amber transition-colors">qestylo@qestylo.com</a>
          </div>
          {/* Elegant small footer social links */}
          <div className="mt-5 flex gap-4 text-muted/60">
            <a href="https://www.instagram.com/qe_stylo/" target="_blank" rel="noopener noreferrer" className="hover:text-[#E1306C] transition-colors" title="Instagram">
              <svg className="w-4 h-4 fill-current" viewBox="0 0 24 24">
                <path d="M12 2.163c3.204 0 3.584.012 4.85.07 3.252.148 4.771 1.691 4.919 4.919.058 1.265.069 1.645.069 4.849 0 3.205-.012 3.584-.069 4.849-.149 3.225-1.664 4.771-4.919 4.919-1.266.058-1.644.07-4.85.07-3.204 0-3.584-.012-4.849-.07-3.26-.149-4.771-1.699-4.919-4.92-.058-1.265-.07-1.644-.07-4.849 0-3.204.013-3.583.07-4.849.149-3.227 1.664-4.771 4.919-4.919 1.266-.057 1.645-.069 4.849-.069zM12 0C8.741 0 8.333.014 7.053.072 2.695.272.273 2.69.073 7.051.014 8.333 0 8.741 0 12c0 3.259.014 3.668.072 4.948.2 4.358 2.618 6.78 6.98 6.98 1.281.058 1.689.072 4.948.072 3.259 0 3.668-.014 4.948-.072 4.354-.2 6.782-2.618 6.979-6.98.059-1.28.073-1.689.073-4.948 0-3.259-.014-3.667-.072-4.947-.196-4.354-2.617-6.78-6.979-6.98C15.668.014 15.259 0 12 0zm0 5.838a6.162 6.162 0 100 12.324 6.162 6.162 0 000-12.324zM12 16a4 4 0 110-8 4 4 0 010 8zm6.406-11.845a1.44 1.44 0 100 2.881 1.44 1.44 0 000-2.881z"/>
              </svg>
            </a>
            <a href="https://www.facebook.com/people/Grupo-Qe-Stylo/100059304493319/?locale=es_ES" target="_blank" rel="noopener noreferrer" className="hover:text-[#1877F2] transition-colors" title="Facebook">
              <svg className="w-4 h-4 fill-current" viewBox="0 0 24 24">
                <path d="M24 12.073c0-6.627-5.373-12-12-12s-12 5.373-12 12c0 5.99 4.388 10.954 10.125 11.854v-8.385H7.078v-3.47h3.047V9.43c0-3.007 1.792-4.669 4.533-4.669 1.312 0 2.686.235 2.686.235v2.953H15.83c-1.491 0-1.956.925-1.956 1.874v2.25h3.328l-.532 3.47h-2.796v8.385C19.612 23.027 24 18.062 24 12.073z"/>
              </svg>
            </a>
            <a href="#" className="hover:text-white transition-colors" title="TikTok">
              <svg className="w-4 h-4 fill-current" viewBox="0 0 24 24">
                <path d="M12.525.02c1.31-.02 2.61-.01 3.91-.02.08 1.53.63 3.02 1.59 4.23.94 1.15 2.25 1.95 3.66 2.3v3.91c-.99-.07-1.96-.36-2.85-.82-.93-.49-1.74-1.18-2.38-2.02v6.62c.01 1.76-.52 3.47-1.52 4.88-.99 1.39-2.4 2.37-4.01 2.79-1.6.43-3.3.31-4.83-.34-1.53-.65-2.79-1.84-3.56-3.37-.8-1.58-1.02-3.4-.63-5.11.39-1.72 1.36-3.25 2.74-4.3 1.38-1.04 3.1-1.56 4.84-1.46v3.97c-.89-.04-1.78.22-2.51.74-.71.51-1.22 1.28-1.43 2.15-.22.88-.08 1.81.39 2.59.47.78 1.25 1.32 2.15 1.52.9.21 1.85.04 2.63-.46.78-.51 1.31-1.34 1.48-2.27.05-.28.07-.57.07-.85V.02z"/>
              </svg>
            </a>
          </div>
        </div>
        <nav className="flex flex-wrap gap-x-6 gap-y-2">
          {links.map(([label, hrefOrTab]) => {
            const isTab = ['legal', 'privacidad', 'cookies'].includes(hrefOrTab);
            return (
              <a
                key={label}
                href={isTab ? '#' : hrefOrTab}
                onClick={isTab ? (e) => { e.preventDefault(); onOpenLegal(hrefOrTab); } : undefined}
                target={hrefOrTab.startsWith('http') ? '_blank' : undefined}
                rel={hrefOrTab.startsWith('http') ? 'noopener noreferrer' : undefined}
                className="focus-ring rounded text-sm font-light text-muted hover:text-amber transition-colors"
              >
                {label}
              </a>
            );
          })}
        </nav>
      </div>
      <div className="max-w-6xl mx-auto mt-10 pt-6 border-t border-surface/30 text-xs font-light text-muted/60">
        © {new Date().getFullYear()} Qestylo · Distribuidor oficial Kömmerling en Valladolid.
      </div>
    </footer>
  );
}

// ---------------- APP ----------------
function App() {
  const [prefillMsg, setPrefillMsg] = useState('');
  const [activeLegalTab, setActiveLegalTab] = useState(null);

  useEffect(() => {
    window.onLegalTabChange = (tab) => {
      setActiveLegalTab(tab);
    };
    return () => {
      window.onLegalTabChange = null;
    };
  }, []);

  return (
    <React.Fragment>
      <PingPongVideo />
      <Navbar />
      <main>
        <Hero />
        <Problema />
        <Solucion onSelectSystemForQuote={(sysName) => {
          setPrefillMsg(`Hola, me interesa recibir presupuesto sin compromiso e información para el sistema de ventanas Kömmerling ${sysName}.`);
        }} />
        <Puertas onSelectSystemForQuote={(sysName) => {
          setPrefillMsg(`Hola, me interesa recibir presupuesto sin compromiso e información para el sistema de puertas Kömmerling ${sysName}.`);
        }} />
        <Persianas onSelectSystemForQuote={(sysName) => {
          setPrefillMsg(`Hola, me interesa recibir presupuesto sin compromiso e información para el sistema de persianas/contraventanas Kömmerling ${sysName}.`);
        }} />
        <ComoFunciona />
        <Credenciales />
        <Opiniones />
        <Contacto prefillMessage={prefillMsg} />
      </main>
      <Footer onOpenLegal={(tab) => setActiveLegalTab(tab)} />
      <WhatsAppWidget />
      <CookieBanner onOpenCookies={() => setActiveLegalTab('cookies')} />
      <LegalModal activeTab={activeLegalTab} onClose={() => setActiveLegalTab(null)} />
    </React.Fragment>
  );
}

ReactDOM.createRoot(document.getElementById('root')).render(<App />);
