/* global React, ReactDOM, Cursor, TopBar, MenuOverlay, Footer, Reveal */
const { useState, useEffect, useRef } = React;

// ============ Tiny SVG glyphs (no decorative illustration — just structural shapes) ============
const GlyphChat = () =>
<svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.6" strokeLinecap="square">
    <path d="M3 5h18v11H8l-5 4V5z" />
    <path d="M8 10h8M8 13h5" />
  </svg>;

const GlyphFlow = () =>
<svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.6" strokeLinecap="square">
    <rect x="2" y="3" width="6" height="6" />
    <rect x="16" y="3" width="6" height="6" />
    <rect x="9" y="15" width="6" height="6" />
    <path d="M5 9v3h14V9M12 12v3" />
  </svg>;

const GlyphSpark = () =>
<svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.6" strokeLinecap="square">
    <path d="M12 3l2 5 5 2-5 2-2 5-2-5-5-2 5-2 2-5z" />
  </svg>;

const GlyphGear = () =>
<svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.6" strokeLinecap="square">
    <circle cx="12" cy="12" r="3.4" />
    <path d="M12 3v3M12 18v3M3 12h3M18 12h3M5.5 5.5l2 2M16.5 16.5l2 2M5.5 18.5l2-2M16.5 7.5l2-2" />
  </svg>;

const GlyphPhone = () =>
<svg width="22" height="22" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5" strokeLinecap="square">
    <rect x="6" y="2.5" width="12" height="19" rx="2" />
    <path d="M10 18.5h4" />
  </svg>;

const GlyphFilter = () =>
<svg width="22" height="22" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5" strokeLinecap="square">
    <path d="M3 5h18l-7 8v6l-4 2v-8L3 5z" />
  </svg>;

const GlyphDoc = () =>
<svg width="22" height="22" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5" strokeLinecap="square">
    <path d="M6 3h9l4 4v14H6z" />
    <path d="M15 3v4h4M9 12h7M9 15h7M9 18h4" />
  </svg>;

const GlyphShare = () =>
<svg width="22" height="22" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5" strokeLinecap="square">
    <circle cx="6" cy="12" r="2.4" />
    <circle cx="18" cy="5.5" r="2.4" />
    <circle cx="18" cy="18.5" r="2.4" />
    <path d="M8.2 10.8l7.6-4.3M8.2 13.2l7.6 4.3" />
  </svg>;

const GlyphCal = () =>
<svg width="22" height="22" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5" strokeLinecap="square">
    <rect x="3" y="5" width="18" height="16" />
    <path d="M3 9h18M8 3v4M16 3v4M8 13h2M14 13h2M8 17h2M14 17h2" />
  </svg>;

const GlyphChart = () =>
<svg width="22" height="22" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5" strokeLinecap="square">
    <path d="M3 21h18" />
    <rect x="6" y="13" width="3" height="6" />
    <rect x="11" y="9" width="3" height="10" />
    <rect x="16" y="5" width="3" height="14" />
  </svg>;


// ============ HERO ============
function HeroAIA() {
  const geo = ["Murcia", "Alicante", "Almería", "Madrid", "Valencia", "Barcelona", "Málaga", "Toda España"];
  return (
    <section id="hero" className="rs-hero bg-navy">
      <div className="rs-hero-grid" aria-hidden="true"></div>
      <div className="rs-hero-glow" aria-hidden="true"></div>

      <div className="rs-hero-tag">Servicio · Automatización &amp; IA</div>

      <h2 className="rs-hero-title">
        TRABAJA<br />MENOS.<br /><span className="rs-accent">CRECE MÁS.</span>
      </h2>

      <p className="rs-hero-sub">
        Automatizamos tus procesos y aplicamos inteligencia artificial para que tu negocio funcione solo mientras tú te centras en crecer.
      </p>

      <div className="rs-hero-cta-row">
        <a href="#contacto" className="btn-lime">Hablemos <span>→</span></a>
        <div className="rs-hero-cta-meta">Primeros resultados en <b>menos de 2 semanas</b></div>
      </div>

      <div className="rs-hero-geo">
        <div className="rs-hero-geo-label">↳ Trabajamos en</div>
        <div className="rs-hero-geo-list">
          {geo.map((g, i) => <span key={i}>{g}</span>)}
        </div>
      </div>

      <div className="rs-hero-scroll-cue" aria-hidden="true">
        <span>Scroll</span>
        <span className="dot"></span>
      </div>
    </section>);
}

// ============ SERVICIOS — 4 cards ============
function QueAutomatizamos() {
  const items = [
  {
    n: "01",
    glyph: <GlyphChat />,
    name: "Chatbots inteligentes",
    body: "Atención al cliente 24 horas sin intervención humana. Responden, cualifican leads y cierran ventas automáticamente."
  },
  {
    n: "02",
    glyph: <GlyphFlow />,
    name: "Flujos de automatización",
    body: "Conectamos tus herramientas para que trabajen solas. CRM, email, WhatsApp, redes sociales — todo sincronizado."
  },
  {
    n: "03",
    glyph: <GlyphSpark />,
    name: "IA aplicada al contenido",
    body: "Generación y optimización de contenido con inteligencia artificial adaptada a tu marca y tono de voz."
  },
  {
    n: "04",
    glyph: <GlyphGear />,
    name: "Soluciones tecnológicas a medida",
    body: "Evaluamos tu negocio e implementamos la tecnología exacta que necesitas para escalar."
  }];

  return (
    <section id="servicios" className="bg-cream rs-section">
      <div className="wipe wipe-top"><svg viewBox="0 0 1440 80" preserveAspectRatio="none"><path d="M0,80 L1440,80 L1440,40 Q720,-30 0,40 Z" fill="#F5F4EF" /></svg></div>
      <div className="wrap">
        <Reveal>
          <div className="rs-para-head">
            <h2 className="rs-para-title">¿QUÉ<br />AUTOMATIZAMOS?</h2>
            <p className="rs-para-sub">Cuatro frentes que liberan tiempo, reducen errores humanos y multiplican lo que un equipo puede entregar. No vendemos magia — vendemos sistemas que funcionan a las 3 de la madrugada igual que a las 3 de la tarde.</p>
          </div>
        </Reveal>
        <div className="aia-services">
          {items.map((it, i) =>
          <Reveal key={i} delay={i * 80}>
              <div className="aia-service-card" data-hover>
                <div className="aia-service-top">
                  <span className="aia-service-num">{it.n} / 04</span>
                  <span className="aia-service-glyph">{it.glyph}</span>
                </div>
                <h3 className="aia-service-name">{it.name}</h3>
                <p className="aia-service-body">{it.body}</p>
              </div>
            </Reveal>
          )}
        </div>
      </div>
    </section>);
}

// ============ MÉTODO ============
function MetodoStep({ num, name, body, idx }) {
  const ref = useRef(null);
  const [vis, setVis] = useState(false);
  useEffect(() => {
    const el = ref.current;if (!el) return;
    const io = new IntersectionObserver(([e]) => {if (e.isIntersecting) setVis(true);}, { threshold: 0.25 });
    io.observe(el);return () => io.disconnect();
  }, []);
  return (
    <div ref={ref} className={`rs-metodo-step ${vis ? 'in' : ''}`} style={{ transitionDelay: `${idx * 80}ms` }}>
      <div className="rs-metodo-num">{num}</div>
      <h3 className="rs-metodo-name">{name}</h3>
      <p className="rs-metodo-body">{body}</p>
    </div>);
}

function MetodoAIA() {
  const steps = [
  ["01", "Análisis del negocio", "Evaluamos tus procesos, metas y dónde la IA puede generar mayor impacto. Detectamos qué tareas repetitivas están drenando tiempo de tu equipo."],
  ["02", "Identificación de soluciones", "Seleccionamos las herramientas más adecuadas para tu caso concreto. Sin enamorarnos del software — la tecnología se elige por encaje, no por moda."],
  ["03", "Personalización e integración", "Adaptamos e integramos la solución en tus sistemas existentes. Conectamos lo que ya tienes con lo nuevo, sin romper procesos que funcionan."],
  ["04", "Seguimiento y optimización", "Monitorizamos y mejoramos continuamente para maximizar resultados. Lo que se mide, se afina — y lo que se afina, escala."]];

  return (
    <section id="metodo" className="bg-black rs-section">
      <div className="wrap">
        <Reveal>
          <div className="rs-metodo-head">
            <h2 className="rs-metodo-title">CÓMO LO<br />HACEMOS</h2>
            <div className="rs-metodo-kicker">Cuatro fases. Cero improvisación. Implementamos sin romper lo que ya tienes — y sin tecnicismos que nadie te pidió.</div>
          </div>
        </Reveal>
        <div className="rs-metodo">
          {steps.map(([n, t, b], i) => <MetodoStep key={i} num={n} name={t} body={b} idx={i} />)}
        </div>
      </div>
    </section>);
}

// ============ FRASE IMPACTO ============
function FraseImpacto() {
  return (
    <section className="aia-impact" aria-label="Mensaje destacado">
      <Reveal>
        <div className="aia-impact-eyebrow">From Zero · Manifesto</div>
        <h2 className="aia-impact-quote">
          NO HAY LÍMITES <em>SI LO PUEDES IMAGINAR.</em>
        </h2>
        <div className="aia-impact-foot">
          <span>↳ Murcia · Toda España</span>
          <span>Sin permanencia · Mes a mes</span>
        </div>
      </Reveal>
    </section>);
}

// ============ CASOS DE USO ============
function CasosUso() {
  const uses = [
  { glyph: <GlyphPhone />, body: "Responder consultas automáticamente por WhatsApp" },
  { glyph: <GlyphFilter />, body: "Cualificar leads sin intervención humana" },
  { glyph: <GlyphDoc />, body: "Enviar presupuestos automáticos tras un formulario" },
  { glyph: <GlyphShare />, body: "Publicar contenido en redes de forma automatizada" },
  { glyph: <GlyphCal />, body: "Sincronizar reservas con el calendario en tiempo real" },
  { glyph: <GlyphChart />, body: "Generar informes semanales sin tocar una hoja de cálculo" }];

  return (
    <section id="casos" className="bg-navy rs-section">
      <div className="wrap">
        <Reveal>
          <div className="aia-uses-head">
            <h2 className="aia-uses-title">¿PARA QUÉ LO USAN<br />NUESTROS CLIENTES?</h2>
            <p className="aia-uses-kicker">Seis ejemplos reales que ya tenemos rodando hoy. No son demos ni proyecciones — son tareas que antes ocupaban horas y ahora se resuelven solas.</p>
          </div>
        </Reveal>
        <div className="aia-uses-grid">
          {uses.map((u, i) =>
          <Reveal key={i} delay={i * 70}>
              <div className="aia-use-cell" data-hover>
                <div className="aia-use-top">
                  <span className="aia-use-glyph">{u.glyph}</span>
                  <span className="aia-use-idx">0{i + 1} / 06</span>
                </div>
                <p className="aia-use-body">{u.body}</p>
              </div>
            </Reveal>
          )}
        </div>
      </div>
    </section>);
}

// ============ POR QUÉ ============
function PorQueAIA() {
  const reasons = [
  { n: "01", name: "Sin permanencia", body: "Mes a mes. Sin ataduras. Si no funcionamos para ti, no hay contrato que te obligue a quedarte." },
  { n: "02", name: "Implementación rápida", body: "Primeros resultados en menos de 2 semanas. Empezamos por lo que más impacto tiene — no por lo que más factura." },
  { n: "03", name: "Sin tecnicismos", body: "Te explicamos todo en cristiano, sin jerga tecnológica. Si no se entiende, lo reescribimos." },
  { n: "04", name: "Soporte continuo", body: "Estamos contigo después de la implementación. Las automatizaciones no se construyen y se abandonan — se mantienen vivas." }];

  return (
    <section id="porque" className="bg-cream rs-section">
      <div className="wipe wipe-top"><svg viewBox="0 0 1440 80" preserveAspectRatio="none"><path d="M0,80 L1440,80 L1440,30 Q720,90 0,30 Z" fill="#F5F4EF" /></svg></div>
      <div className="wrap">
        <Reveal>
          <div className="rs-para-head">
            <h2 className="rs-para-title">¿POR QUÉ<br />NOSOTROS?</h2>
            <p className="rs-para-sub">Cuatro razones para automatizar con FromZero — y no con una consultora que te cobra por hora ni con una herramienta enlatada que no se adapta a tu negocio.</p>
          </div>
        </Reveal>
        <div className="dws-why-grid">
          {reasons.map((r, i) =>
          <Reveal key={i} delay={i * 90}>
              <div className="dws-why-card" data-hover>
                <div className="dws-why-num">{r.n}</div>
                <h3 className="dws-why-name">{r.name}</h3>
                <p className="dws-why-body">{r.body}</p>
              </div>
            </Reveal>
          )}
        </div>
      </div>
    </section>);
}

// ============ CONTACTO ============
function ContactoAIA() {
  const [form, setForm] = useState({ email: '', name: '', phone: '', message: '' });
  const [errs, setErrs] = useState({});
  const [status, setStatus] = useState('idle');
  const u = (k) => (e) => setForm((f) => ({ ...f, [k]: e.target.value }));
  const submit = async (e) => {
    e.preventDefault();
    const er = {};
    if (!form.email.trim()) er.email = "Requerido";else
    if (!/^[^@]+@[^@]+\.[^@]+$/.test(form.email)) er.email = "Email no válido";
    if (!form.name.trim()) er.name = "Requerido";
    if (!form.message.trim()) er.message = "Requerido";
    setErrs(er);
    if (Object.keys(er).length > 0) return;
    setStatus('sending');
    try {
      const fd = new FormData(e.target);
      const res = await fetch('https://formspree.io/f/xrejvgea', { method: 'POST', body: fd, headers: { 'Accept': 'application/json' } });
      if (res.ok) {setStatus('success');setForm({ email: '', name: '', phone: '', message: '' });} else
      setStatus('error');
    } catch (_) {setStatus('error');}
  };
  return (
    <section id="contacto" className="bg-navy rs-section aia-contact">
      <div className="wrap">
        <div className="rs-contact-grid">
          <Reveal>
            <div>
              <h2 className="rs-contact-title aia-contact-title">¿HABLAMOS<br />DE TU PROYECTO?</h2>
              <p className="rs-contact-sub aia-contact-sub">Cuéntanos qué quieres automatizar: atención al cliente, ventas, reporting, contenido… Te respondemos en menos de 24h con una propuesta concreta.</p>
              <div className="rs-contact-extras aia-contact-extras">
                <a href="mailto:hola@fromzero.es" data-hover>hola@fromzero.es</a>
                <a href="tel:+34650720278" data-hover>+34 650 720 278</a>
                <div style={{ opacity: 0.5 }}>Murcia · España</div>
              </div>
            </div>
          </Reveal>
          <Reveal delay={140}>
            <form className="contact-form" action="https://formspree.io/f/xrejvgea" method="POST" onSubmit={submit} noValidate>
              <input type="hidden" name="_subject" value="Nuevo contacto desde automatizacion-ia · FromZero.es" />
              <input type="hidden" name="_origen" value="automatizacion-ia" />
              <div className="field"><label htmlFor="fz-email">Correo electrónico</label><input id="fz-email" name="email" type="email" value={form.email} onChange={u('email')} /><div className="err">{errs.email || ''}</div></div>
              <div className="field"><label htmlFor="fz-nombre">Nombre</label><input id="fz-nombre" name="nombre" value={form.name} onChange={u('name')} /><div className="err">{errs.name || ''}</div></div>
              <div className="field"><label htmlFor="fz-tel">Número de teléfono</label><input id="fz-tel" name="telefono" type="tel" value={form.phone} onChange={u('phone')} /><div className="err"></div></div>
              <div className="field"><label htmlFor="fz-msg">Mensaje</label><textarea id="fz-msg" name="mensaje" rows={3} value={form.message} onChange={u('message')}></textarea><div className="err">{errs.message || ''}</div></div>
              <button type="submit" className="btn-send" disabled={status === 'sending'}>
                {status === 'sending' ? 'Enviando…' : 'Enviar →'}
              </button>
              {status === 'success' &&
              <div role="status" style={{ marginTop: 16, padding: '14px 18px', border: '1px solid #BFFF00', background: 'rgba(191,255,0,0.10)', color: '#BFFF00', fontWeight: 500, fontSize: 15 }}>
                  ¡Mensaje enviado! Te contactamos en menos de 24 horas.
                </div>
              }
              {status === 'error' &&
              <div role="alert" style={{ marginTop: 16, padding: '14px 18px', border: '1px solid #ff4d4d', background: 'rgba(255,77,77,0.08)', color: '#ff4d4d', fontWeight: 500, fontSize: 15 }}>
                  Algo salió mal. Escríbenos a <a href="mailto:hola@fromzero.es" style={{ color: '#ff4d4d', textDecoration: 'underline' }}>hola@fromzero.es</a>
                </div>
              }
            </form>
          </Reveal>
        </div>
      </div>
    </section>);
}

// ============ APP ============
function App() {
  const [lang, setLang] = useState('es');
  const [menuOpen, setMenuOpen] = useState(false);
  const [onCream, setOnCream] = useState(false);
  useEffect(() => {
    const handle = () => {
      const y = 50,x = window.innerWidth / 2;
      const el = document.elementFromPoint(x, y);if (!el) return;
      const section = el.closest('section, footer');
      // Treat the lime impact band as a "cream-like" light background for the topbar contrast.
      setOnCream(section && (section.classList.contains('bg-cream') || section.classList.contains('aia-impact')));
    };
    handle();
    window.addEventListener('scroll', handle, { passive: true });
    window.addEventListener('resize', handle);
    return () => {window.removeEventListener('scroll', handle);window.removeEventListener('resize', handle);};
  }, []);
  useEffect(() => {document.documentElement.lang = lang;}, [lang]);
  useEffect(() => {document.body.style.overflow = menuOpen ? 'hidden' : '';}, [menuOpen]);
  return (
    <>
      <Cursor />
      <TopBar lang={lang} setLang={setLang} onMenu={() => setMenuOpen(true)} onCream={onCream && !menuOpen} backToHome />
      <MenuOverlay open={menuOpen} onClose={() => setMenuOpen(false)} lang={lang} />
      <h1 className="sr-only">Automatización e Inteligencia Artificial para empresas en Murcia - FromZero</h1>
      <main>
        <HeroAIA />
        <QueAutomatizamos />
        <MetodoAIA />
        <FraseImpacto />
        <CasosUso />
        <PorQueAIA />
        <ContactoAIA />
      </main>
      <Footer lang={lang} />
    </>);

}

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