/* global React */
const { useState, useEffect, useRef } = React;

// ---------- Cursor ----------
function Cursor() {
  const ringRef = useRef(null);
  const dotRef = useRef(null);
  const [hover, setHover] = useState(false);
  useEffect(() => {
    let tx = window.innerWidth / 2,ty = window.innerHeight / 2;
    let rx = tx,ry = ty;
    const onMove = (e) => {tx = e.clientX;ty = e.clientY;
      if (dotRef.current) dotRef.current.style.transform = `translate(${tx}px, ${ty}px) translate(-50%, -50%)`;
    };
    let raf;
    const tick = () => {
      rx += (tx - rx) * 0.12;ry += (ty - ry) * 0.12;
      if (ringRef.current) ringRef.current.style.transform = `translate(${rx}px, ${ry}px) translate(-50%, -50%)`;
      raf = requestAnimationFrame(tick);
    };
    tick();
    const onOver = (e) => setHover(!!e.target.closest('a, button, [data-hover], .svc-row, .client-cell, .fan-card, .tm-card'));
    window.addEventListener('mousemove', onMove);
    document.addEventListener('mouseover', onOver);
    return () => {cancelAnimationFrame(raf);window.removeEventListener('mousemove', onMove);document.removeEventListener('mouseover', onOver);};
  }, []);
  return <>
    <div ref={ringRef} className={`cur-ring ${hover ? 'is-hover' : ''}`}></div>
    <div ref={dotRef} className="cur-dot"></div>
  </>;
}

// ---------- Logo ----------
function LogoFZ() {
  return <img src="assets/logo.svg" alt="FromZero - Agencia de Marketing Digital en Murcia" className="brand-img" style={{ objectFit: "fill" }} />;
}

// ---------- Reveal ----------
function Reveal({ children, delay = 0, className = "" }) {
  const ref = useRef(null);
  useEffect(() => {
    const el = ref.current;if (!el) return;
    const io = new IntersectionObserver(([e]) => {if (e.isIntersecting) setTimeout(() => el.classList.add('in'), delay);}, { threshold: 0.12 });
    io.observe(el);return () => io.disconnect();
  }, [delay]);
  return <div ref={ref} className={`reveal ${className}`}>{children}</div>;
}

// ---------- Counter ----------
function Counter({ to, prefix = "", suffix = "", decimals = 0 }) {
  const [v, setV] = useState(0);
  const ref = useRef(null);
  const started = useRef(false);
  useEffect(() => {
    const el = ref.current;if (!el) return;
    const io = new IntersectionObserver(([e]) => {
      if (e.isIntersecting && !started.current) {
        started.current = true;
        const start = performance.now(),dur = 1800;
        const step = (now) => {
          const p = Math.min(1, (now - start) / dur);
          const eased = 1 - Math.pow(1 - p, 3);
          setV(eased * to);
          if (p < 1) requestAnimationFrame(step);
        };
        requestAnimationFrame(step);
      }
    }, { threshold: 0.3 });
    io.observe(el);return () => io.disconnect();
  }, [to]);
  return <span ref={ref}>{prefix}{decimals ? v.toFixed(decimals) : Math.round(v)}{suffix}</span>;
}

// ---------- TopBar ----------
function TopBar({ lang, setLang, onMenu, onCream, backToHome }) {
  const [scrolled, setScrolled] = useState(false);
  useEffect(() => {
    const on = () => setScrolled(window.scrollY > 24);
    on();window.addEventListener('scroll', on);
    return () => window.removeEventListener('scroll', on);
  }, []);
  return (
    <header className={`topbar ${scrolled ? 'scrolled' : ''} ${onCream ? 'on-cream' : ''}`}>
      <div className="tb-left">
        <button onClick={onMenu} className="burger" aria-label="Menu"><span></span><span></span><span></span></button>
        <span className="menu-label" onClick={onMenu}>Menú</span>
        {backToHome && <a href="/" className="tb-back" data-hover>← Inicio</a>}
      </div>
      <div className="tb-center"><a href="#hero" data-hover><LogoFZ /></a></div>
      <div className="tb-right">
        <a href="#contacto" className="tb-hablemos">Hablemos →</a>
        <div className="lang">
          <button onClick={() => setLang('es')} className={lang === 'es' ? 'active' : ''}>ES</button>
          <span style={{ opacity: 0.3 }}>/</span>
          <button onClick={() => setLang('en')} className={lang === 'en' ? 'active' : ''}>EN</button>
        </div>
      </div>
    </header>);

}

// ---------- Menu ----------
function MenuOverlay({ open, onClose, lang }) {
  const items = lang === 'es' ?
  [['hero', 'Inicio'], ['servicios', 'Servicios'], ['clientes', 'Clientes'], ['proceso', 'Proceso'], ['equipo', 'Equipo'], ['contacto', 'Contacto']] :
  [['hero', 'Home'], ['servicios', 'Services'], ['clientes', 'Clients'], ['proceso', 'Process'], ['equipo', 'Team'], ['contacto', 'Contact']];
  const go = (id) => (e) => {
    e.preventDefault();onClose();
    setTimeout(() => {
      const el = document.getElementById(id);
      if (el) el.scrollIntoView({ behavior: 'smooth', block: 'start' });
      else window.location.href = `/#${id}`;
    }, 300);
  };
  return (
    <div className={`menu-overlay ${open ? 'open' : ''}`} aria-hidden={!open}>
      <button className="menu-close" onClick={onClose} data-hover>CERRAR ✕</button>
      <div className="menu-list">
        {items.map(([id, label], i) =>
        <a key={id} href={`#${id}`} className="menu-link" onClick={go(id)} data-hover>
            <span className="ml-num">0{i + 1}</span><span>{label}</span>
          </a>
        )}
      </div>
      <div className="menu-foot">
        <div>
          <h6>{lang === 'es' ? 'Contacto' : 'Contact'}</h6>
          <a href="mailto:hola@fromzero.es" data-hover>hola@fromzero.es</a>
          <a href="tel:+34600000000" data-hover>+34 600 00 00 00</a>
        </div>
        <div>
          <h6>{lang === 'es' ? 'Redes' : 'Social'}</h6>
          <a href="#" data-hover>Instagram ↗</a>
          <a href="#" data-hover>TikTok ↗</a>
          <a href="#" data-hover>LinkedIn ↗</a>
        </div>
        <div>
          <h6>{lang === 'es' ? 'Estudio' : 'Studio'}</h6>
          <div style={{ color: 'rgba(255,255,255,0.7)', fontSize: 13, textTransform: 'none', letterSpacing: 0.04 }}>Murcia, España</div>
          <div style={{ color: 'rgba(255,255,255,0.4)', fontSize: 13, textTransform: 'none', marginTop: 4 }}>{lang === 'es' ? 'Desde 2024' : 'Since 2024'}</div>
        </div>
      </div>
    </div>);

}

// ---------- Hero word rotator ----------
function WordRotator({ words }) {
  const [idx, setIdx] = useState(0);
  const [phase, setPhase] = useState('current');
  useEffect(() => {
    const i = setInterval(() => {
      setPhase('exit');
      setTimeout(() => {
        setIdx((x) => (x + 1) % words.length);
        setPhase('enter');
        requestAnimationFrame(() => requestAnimationFrame(() => setPhase('current')));
      }, 550);
    }, 2200);
    return () => clearInterval(i);
  }, [words.length]);
  return (
    <span className="hero-rotator">
      <span className={`hero-rotator-word ${phase}`}>{words[idx]}</span>
    </span>);

}

// ---------- Hero client logo rotator (inside rect) ----------
function HeroLogoRotator({ logos }) {
  const [idx, setIdx] = useState(0);
  const [out, setOut] = useState(false);
  useEffect(() => {
    const i = setInterval(() => {
      setOut(true);
      setTimeout(() => {setIdx((x) => (x + 1) % logos.length);setOut(false);}, 400);
    }, 1800);
    return () => clearInterval(i);
  }, [logos.length]);
  return (
    <span className="hero-rect" aria-hidden="true">
      <span className={`hero-rect-logo ${out ? 'out' : ''}`}>
        <img src={logos[idx]} alt="" />
      </span>
    </span>);

}

// ---------- HERO ----------
function Hero({ lang }) {
  const t = lang === 'es' ? {
    l1: "LA AGENCIA", l2: "QUE GENERA",
    words: ["VENTAS", "CLIENTES", "VISIBILIDAD", "RESULTADOS"],
    sub: "Ayudamos a negocios y marcas a crecer desde cero. Resultados reales, no métricas de vanidad.",
    cta1: "Hablemos", cta2: "Ver resultados →",
    date: "Desde 2024",
    s: [["+20", "Clientes"], ["+100M", "Visitas"], ["+300K", "Seguidores"]]
  } : {
    l1: "THE AGENCY", l2: "THAT DRIVES",
    words: ["SALES", "CLIENTS", "VISIBILITY", "RESULTS"],
    sub: "We help businesses and brands grow from zero. Real results, not vanity metrics.",
    cta1: "Let's talk", cta2: "See results →",
    date: "Since 2024",
    s: [["+20", "Clients"], ["+100M", "Views"], ["+300K", "Followers"]]
  };
  const logos = [
  "assets/clients/cliente1.svg", "assets/clients/cliente2.svg", "assets/clients/cliente3.svg",
  "assets/clients/cliente4.svg", "assets/clients/cliente5.svg", "assets/clients/cliente6.svg",
  "assets/clients/cliente7.svg", "assets/clients/cliente8.svg", "assets/clients/cliente9.svg"];

  return (
    <section id="hero" className="hero bg-navy" style={{ backgroundColor: "rgb(6, 13, 30)" }}>
      <div className="hero-bg" aria-hidden="true">
        <img src="assets/hero-bg.png" alt="" />
      </div>
      <div className="hero-glow"></div>
      <div className="hero-date">{t.date}</div>
      <h1 className="hero-title">
        <div className="hero-line">{t.l1}</div>
        <div className="hero-line">{t.l2} <HeroLogoRotator logos={logos} /></div>
        <div className="hero-rotator-wrap"><WordRotator words={t.words} /></div>
      </h1>
      <p className="hero-sub">{t.sub}</p>
      <div className="hero-ctas">
        <a href="#contacto" className="btn-lime">{t.cta1} <span>→</span></a>
        <a href="#clientes" className="btn-text">{t.cta2}</a>
      </div>
      <div className="hero-scroll"><span className="hero-scroll-dot"></span><span className="hero-scroll-line"></span></div>
      <div className="hero-stats">
        {t.s.map(([v, l], i) => <div key={i} className="hs"><span className="hs-v">{v}</span><span className="hs-l">{l}</span></div>)}
      </div>
    </section>);

}

// ---------- SERVICIOS ----------
function Servicios({ lang }) {
  const data = lang === 'es' ? {
    tag: "02 — Lo que hacemos", title: "SERVICIOS",
    list: [
    ["01", "Redes Sociales", "Contenido estratégico para Instagram y TikTok.", "/redes-sociales"],
    ["02", "Publicidad Digital", "Google Ads, Meta Ads y TikTok Ads orientados a ventas.", "/publicidad-digital"],
    ["03", "Diseño Web & SEO", "Webs que convierten y posicionamiento en Google para que te encuentren primero.", "/diseno-web-seo"],
    ["04", "Automatización & IA", "Chatbots y flujos que trabajan 24 horas.", "/automatizacion-ia"]]

  } : {
    tag: "02 — What we do", title: "SERVICES",
    list: [
    ["01", "Social Media", "Strategic content for Instagram and TikTok.", "/redes-sociales"],
    ["02", "Digital Advertising", "Google, Meta and TikTok Ads built for sales.", "/publicidad-digital"],
    ["03", "Web Design & SEO", "Websites that convert and Google rankings so they find you first.", "/diseno-web-seo"],
    ["04", "Automation & AI", "Chatbots and flows that work 24/7.", "/automatizacion-ia"]]

  };
  return (
    <section id="servicios" className="bg-cream">
      <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="services-head">
            <div className="tag">{data.tag}</div>
            <h2 className="services-title">{data.title}</h2>
          </div>
        </Reveal>
        <div className="svc-list">
          {data.list.map(([n, name, desc, href], i) =>
          <Reveal key={i} delay={i * 60}>
              <a className="svc-row" href={href} data-hover aria-label={`${name} — ver landing`}>
                <div className="svc-num">{n}</div>
                <div>
                  <h3 className="svc-name">{name}</h3>
                  <div className="svc-desc">{desc}</div>
                </div>
                <div className="svc-arrow">→</div>
              </a>
            </Reveal>
          )}
        </div>
      </div>
    </section>);

}

// ---------- CLIENTES ----------
const CLIENT_DATA = [
{ src: "assets/clients/cliente1.svg", name: "Sushi Cero", meta: "Restaurante · Alicante", results: "3.500 seg. orgánicos · Sold out · +500 reseñas Google" },
{ src: "assets/clients/cliente2.svg", name: "Natalia's Secret", meta: "Salón de belleza · Murcia", results: "1,9M visualizaciones · De 3K a 5.6K seguidores" },
{ src: "assets/clients/cliente3.svg", name: "MontePadel", meta: "Club de pádel", results: "315K reproducciones · +514 nuevos seguidores" },
{ src: "assets/clients/cliente4.svg", name: "El Código del Amor", meta: "Relaciones conscientes", results: "+50K orgánicos · 14 ventas de 6.000€ sin publicidad" },
{ src: "assets/clients/cliente5.svg", name: "Joyería Muñoz 1943", meta: "Joyería · Murcia", results: "+20M visitas · +40K Instagram · +90K TikTok" },
{ src: "assets/clients/cliente6.svg", name: "Vi Sushi", meta: "Restaurante · Villajoyosa", results: "40K visualizaciones · Sold out 2ª semana" },
{ src: "assets/clients/cliente7.svg", name: "Qing Tian Ramen", meta: "Restaurante", results: "+400K visualizaciones · Flujo constante" },
{ src: "assets/clients/cliente8.svg", name: "CMC Fitness", meta: "Gimnasio", results: "+100 nuevos suscriptores en 3 meses" },
{ src: "assets/clients/cliente9.svg", name: "Arroz y Arte", meta: "Restaurante", results: "Videos +100K visualizaciones primer mes" }];


function Clientes({ lang }) {
  const t = lang === 'es' ? { tag: "03 — Confían en nosotros", title: "RESULTADOS REALES.", title2: "", s: [["+20", "Clientes"], ["+100M", "Visitas"], ["+300K", "Seguidores"]] } :
  { tag: "03 — Trusted by", title: "REAL RESULTS.", title2: "", s: [["+20", "Clients"], ["+100M", "Views"], ["+300K", "Followers"]] };
  return (
    <section id="clientes" className="bg-navy">
      <div className="wrap">
        <Reveal>
          <div className="clientes-head">
            <div className="tag">{t.tag}</div>
            <h2 className="clientes-title">{t.title}<br /><span style={{ color: 'var(--lime)' }}>{t.title2}</span></h2>
          </div>
        </Reveal>
        <div className="clientes-grid">
          {CLIENT_DATA.map((c, i) =>
          <div key={i} className="client-cell" data-hover>
              <img src={c.src} alt={`${c.name} - Cliente de FromZero Agencia de Marketing en Murcia`} loading="lazy" onError={(e) => {e.currentTarget.style.display = 'none';}} />
              <div className="client-card">
                <div className="cc-name">{c.name}</div>
                <div className="cc-meta">{c.meta}</div>
                <div className="cc-results">{c.results}</div>
              </div>
            </div>
          )}
        </div>
      </div>
    </section>);

}

// ---------- PROCESO (fan) ----------
function Proceso({ lang }) {
  const data = lang === 'es' ? {
    tag: "04 — Cómo trabajamos", title: "EL PROCESO",
    steps: [
    ["01", "Brand Unpacking", "Analizamos tu marca, competencia y audiencia objetivo para construir desde una base sólida."],
    ["02", "Asignación del equipo", "Seleccionamos el equipo perfecto según las necesidades específicas de tu proyecto."],
    ["03", "Estrategia", "Diseñamos un plan de acción con objetivos claros, KPIs medibles y calendario de ejecución."],
    ["04", "Ejecución", "Producimos y publicamos contenido optimizado, gestionamos campañas y ajustamos en tiempo real."],
    ["05", "Seguimiento", "Análisis continuo de resultados, reporting mensual y optimización para seguir creciendo."]]

  } : {
    tag: "04 — How we work", title: "THE PROCESS",
    steps: [
    ["01", "Brand Unpacking", "We analyze your brand, competition and target audience to build from a solid base."],
    ["02", "Team Assignment", "We pick the right team for your project's specific needs."],
    ["03", "Strategy", "We design an action plan with clear goals, KPIs and a delivery calendar."],
    ["04", "Execution", "We produce optimized content, run campaigns and adjust in real time."],
    ["05", "Tracking", "Continuous reporting and optimization to keep growing."]]

  };
  const [active, setActive] = useState(0);
  const ref = useRef(null);
  useEffect(() => {
    const el = ref.current;if (!el) return;
    const io = new IntersectionObserver(([e]) => {if (e.isIntersecting) setTimeout(() => setActive(0), 500);}, { threshold: 0.3 });
    io.observe(el);return () => io.disconnect();
  }, []);
  const n = data.steps.length;
  const procesoImgs = ["assets/proceso/paso1.jpg", "assets/proceso/paso2.png", "assets/proceso/paso3.webp", "assets/proceso/paso4.webp", "assets/proceso/paso5.webp"];
  return (
    <section id="proceso" className="bg-cream">
      <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="proceso-head">
            <div className="tag">{data.tag}</div>
            <h2 className="proceso-title">{data.title}</h2>
          </div>
        </Reveal>
        <div className="fan" ref={ref}>
          {data.steps.map(([num, title, desc], i) => {
            const isActive = i === active;
            // compute left offset: when one is active it takes 60% of container; others compressed
            const containerW = 100; // percent
            const activeW = 56;
            const compactW = (containerW - activeW) / (n - 1);
            let left = 0;
            for (let k = 0; k < i; k++) left += k === active ? activeW : compactW;
            const width = isActive ? activeW : compactW;
            return (
              <div key={i} className={`fan-card ${isActive ? 'active' : ''}`}
              style={{ left: `${left}%`, width: `${width}%`, zIndex: isActive ? 10 : n - Math.abs(active - i), transform: `rotate(${isActive ? 0 : (i - active) * 1.2}deg)` }}
              onMouseEnter={() => setActive(i)} onClick={() => setActive(i)} data-hover>
                <div className="fan-img" data-img-slot={`proceso-${num}`}><img src={procesoImgs[i]} alt={`Paso ${num} — ${title}`} loading="lazy" /></div>
                <span className="fan-num-bg">{num}</span>
                <div className="fan-step-label">PASO / {num}</div>
                <h3 className="fan-title">{title}</h3>
                <div className="fan-line"></div>
                <div className="fan-desc">{desc}</div>
                <div className="fan-step-vert">{num} · {title}</div>
              </div>);

          })}
        </div>
      </div>
    </section>);

}

// ---------- POR QUE ----------
function PorQue({ lang }) {
  const data = lang === 'es' ? {
    tag: "05 — Por qué FromZero", title: "POR QUÉ", title2: "NOSOTROS",
    list: [
    ["", "Equipo joven", "3 años de experiencia real en contenido viral."],
    ["📈", "+100M reproducciones", "Generadas orgánicamente para clientes."],
    ["🎯", "Nuestro propio caso", "60K seguidores propios, sin atajos."],
    ["🔧", "Soluciones a medida", "Sin paquetes cerrados ni plantillas."],
    ["✅", "Sin permanencia", "Resultados desde el primer mes."]],

    fan2: [
    ["01", "EQUIPO JOVEN", "3 años creando contenido viral"],
    ["02", "+100M", "Reproducciones orgánicas generadas"],
    ["03", "SOMOS EL CASO", "Somos influencers con 60K seguidores propios"],
    ["04", "SIN PERMANENCIA", "Resultados desde el primer mes"],
    ["05", "PERSONALIZADO", "Sin paquetes cerrados, estrategia a medida"]]

  } : {
    tag: "05 — Why FromZero", title: "WHY", title2: "US",
    list: [
    ["", "Young team", "3 years of real experience with viral content."],
    ["📈", "+100M plays", "Organically generated for our clients."],
    ["🎯", "Our own case", "60K followers earned without shortcuts."],
    ["🔧", "Tailored solutions", "No fixed packages, no templates."],
    ["✅", "No lock-in", "Results from month one."]],

    fan2: [
    ["01", "YOUNG TEAM", "3 years creating viral content"],
    ["02", "+100M", "Organic plays generated"],
    ["03", "SOMOS EL CASO", "We're influencers with 60K of our own"],
    ["04", "NO LOCK-IN", "Results from month one"],
    ["05", "TAILORED", "No fixed packages, custom strategy"]]

  };
  const fan2Ref = useRef(null);
  const [fan2In, setFan2In] = useState(false);
  useEffect(() => {
    const el = fan2Ref.current;if (!el) return;
    const io = new IntersectionObserver(([e]) => {if (e.isIntersecting) setFan2In(true);}, { threshold: 0.2 });
    io.observe(el);return () => io.disconnect();
  }, []);
  const porqueImgs = ["assets/porque/equipo-joven.jpg", "assets/porque/reproducciones.jpg", "assets/porque/caso-exito.jpg", "assets/porque/sin-permanencia.jpg", "assets/porque/personalizado.webp"];
  return (
    <section id="porque" className="bg-black">
      <div className="porque-bg" aria-hidden="true"><img src="assets/porque-bg.webp" alt="" loading="lazy" /></div>
      <div className="wrap">
        <Reveal>
          <div className="pq-head">
            <div className="tag">{data.tag}</div>
            <h2 className="pq-title">{data.title} <span style={{ color: 'var(--lime)' }}>{data.title2}</span>.</h2>
          </div>
        </Reveal>
        <div ref={fan2Ref} className={`pq-fan2 ${fan2In ? 'in-view' : ''}`}>
          {data.fan2.map(([idx, title, sub], i) =>
          <div key={i} className="pq2-card" data-hover>
              <div className="pq2-bg" data-img-slot={`porque-${idx}`}><img src={porqueImgs[i]} alt={title} loading="lazy" /></div>
              <div className="pq2-overlay"></div>
              <div className="pq2-content">
                <div className="pq2-index">{idx} / 05</div>
                <h3 className="pq2-title">{title}</h3>
                <div className="pq2-sub">{sub}</div>
              </div>
            </div>
          )}
        </div>
      </div>
    </section>);

}

// ---------- EQUIPO ----------
function Equipo({ lang }) {
  const data = lang === 'es' ? {
    tag: "06 — El equipo", title: "LAS PERSONAS DETRÁS DE LOS RESULTADOS.",
    list: [
    ["Diana Kushnerova", "Co-Founder & CEO", "Estrategia, marca y dirección creativa.", "assets/equipo/diana.webp"],
    ["Miguel Garcia", "Co-Founder & CMO", "Performance, paid media y growth. Especialista en escalado.", "assets/equipo/miguel.webp"],
    ["Jaime Gómez", "CTO", "Web, automatizaciones e IA. Stack moderno.", "assets/equipo/jaime.webp"],
    ["Silvia López", "Project Manager & Filmmaker", "Producción audiovisual y coordinación de proyectos.", "assets/equipo/silvia.jpg"]]

  } : {
    tag: "06 — The team", title: "THE PEOPLE BEHIND THE RESULTS.",
    list: [
    ["Diana Kushnerova", "Co-Founder & CEO", "Strategy, brand and creative direction. Ex-agency Madrid & Barcelona.", "assets/equipo/diana.webp"],
    ["Miguel Garcia", "Co-Founder & CMO", "Performance, paid media and growth. E-commerce scaling specialist.", "assets/equipo/miguel.webp"],
    ["Jaime Gómez", "CTO", "Web, automation and AI. Modern stack, no empty promises.", "assets/equipo/jaime.webp"],
    ["Silvia López", "Project Manager & Filmmaker", "Audiovisual production and project coordination.", "assets/equipo/silvia.jpg"]]

  };
  return (
    <section id="equipo" className="bg-navy">
      <div className="wrap">
        <Reveal>
          <div className="equipo-head">
            <div className="tag">{data.tag}</div>
            <h2 className="equipo-title">{data.title}</h2>
          </div>
        </Reveal>
        <div className="team-grid">
          {data.list.map(([n, r, bio, photo], i) => {
            const initials = n.split(' ').map((w) => w[0]).join('').slice(0, 2);
            return (
              <Reveal key={i} delay={i * 80}>
                <div className="tm-card" data-hover>
                  <div className="tm-photo">
                    {photo ? <img src={photo} alt={n} className="tm-img" /> : <div className="tm-initials">{initials}</div>}
                    {!photo && <div className="tm-tag">PHOTO</div>}
                    <div className="tm-curtain" style={{ opacity: "0.7" }}><div className="tm-curtain-bio">{bio}</div></div>
                  </div>
                  <h3 className="tm-name">{n}</h3>
                  <div className="tm-role">{r}</div>
                </div>
              </Reveal>);

          })}
        </div>
      </div>
    </section>);

}

// ---------- CONTACTO ----------
function Contacto({ lang }) {
  const t = lang === 'es' ? {
    title: "¿HABLAMOS?", sub: "Cuéntanos tu proyecto. Te respondemos en menos de 24 horas.",
    f: { name: "Nombre", email: "Email", phone: "Teléfono", company: "Empresa", message: "Mensaje", send: "Enviar" },
    err: { req: "Requerido", email: "Email no válido" },
    s: { t: "Mensaje recibido.", b: "Te respondemos antes de 24h.", a: "Enviar otro" },
    links: [["EMAIL", "hola@fromzero.es", "mailto:hola@fromzero.es"], ["TELÉFONO", "+34 650 720 278", "tel:+34650720278"], ["LINKEDIN", "FromZero", "#"]]
  } : {
    title: "LET'S TALK?", sub: "Tell us about your project. We reply within 24 hours.",
    f: { name: "Name", email: "Email", phone: "Phone", company: "Company", message: "Message", send: "Send" },
    err: { req: "Required", email: "Invalid email" },
    s: { t: "Got it.", b: "We'll reply within 24h.", a: "Send another" },
    links: [["EMAIL", "hola@fromzero.es", "mailto:hola@fromzero.es"], ["PHONE", "+34 650 720 278", "tel:+34650720278"], ["LINKEDIN", "FromZero", "#"]]
  };
  const [form, setForm] = useState({ name: '', email: '', phone: '', company: '', message: '' });
  const [errs, setErrs] = useState({});
  const [status, setStatus] = useState('idle'); // 'idle' | 'sending' | 'success' | 'error'
  const u = (k) => (e) => setForm((f) => ({ ...f, [k]: e.target.value }));
  const submit = async (e) => {
    e.preventDefault();
    const er = {};
    if (!form.name.trim()) er.name = t.err.req;
    if (!form.email.trim()) er.email = t.err.req;else
    if (!/^[^@]+@[^@]+\.[^@]+$/.test(form.email)) er.email = t.err.email;
    if (!form.message.trim()) er.message = t.err.req;
    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({ name: '', email: '', phone: '', company: '', message: '' });
      } else {
        setStatus('error');
      }
    } catch (_err) {
      setStatus('error');
    }
  };
  return (
    <section id="contacto" className="bg-cream">
      <div className="wipe wipe-top"><svg viewBox="0 0 1440 80" preserveAspectRatio="none"><path d="M0,80 L1440,80 L1440,45 Q720,-20 0,45 Z" fill="#F5F4EF" /></svg></div>
      <div className="wrap">
        <div className="contact-grid">
          <Reveal>
            <div>
              <h2 className="contact-title">{t.title}</h2>
              <p className="contact-sub">{t.sub}</p>
              <div className="contact-links">
                {t.links.map(([tag, label, href], i) =>
                <a key={i} href={href} data-hover>
                    <span className="cl-tag">{tag}</span><span>{label}</span>
                  </a>
                )}
              </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 FromZero.es" />
              <div className="field"><label htmlFor="fz-nombre">{t.f.name}</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-email">{t.f.email}</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-telefono">{t.f.phone}</label><input id="fz-telefono" name="telefono" type="tel" value={form.phone} onChange={u('phone')} /><div className="err"></div></div>
              <div className="field"><label htmlFor="fz-empresa">{t.f.company}</label><input id="fz-empresa" name="empresa" value={form.company} onChange={u('company')} /><div className="err"></div></div>
              <div className="field"><label htmlFor="fz-mensaje">{t.f.message}</label><textarea id="fz-mensaje" name="mensaje" value={form.message} onChange={u('message')} rows={3}></textarea><div className="err">{errs.message || ''}</div></div>
              <button type="submit" className="btn-send" disabled={status === 'sending'}>
                {status === 'sending' ? (lang === 'es' ? 'Enviando…' : 'Sending…') : `${t.f.send} →`}
              </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, letterSpacing: '-0.005em' }}>
                  ¡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 directamente a <a href="mailto:hola@fromzero.es" style={{ color: '#ff4d4d', textDecoration: 'underline' }}>hola@fromzero.es</a>
                </div>
              )}
            </form>
          </Reveal>
        </div>
      </div>
    </section>);

}

// ---------- FOOTER ----------
function Footer({ lang }) {
  const items = lang === 'es' ? ["MARKETING DIGITAL", "FROM ZERO", "MURCIA"] : ["DIGITAL MARKETING", "FROM ZERO", "MURCIA"];
  const seq = [...Array(8)].flatMap(() => items);
  return (
    <footer className="footer-wrap">
      <div className="footer-bg" aria-hidden="true"><img src="assets/footer-bg.webp" alt="" loading="lazy" /></div>
      <div className="footer-top wrap">
        <div>
          <LogoFZ />
          <p style={{ marginTop: 20, opacity: 0.7, fontSize: 14, lineHeight: 1.55, maxWidth: 360 }}>
            {lang === 'es' ? 'Agencia de marketing digital independiente. Construyendo marcas desde cero.' : 'Independent digital marketing agency. Building brands from zero.'}
          </p>
        </div>
        <div>
          <h5>{lang === 'es' ? 'Secciones' : 'Sections'}</h5>
          <ul>
            <li><a href="#hero">{lang === 'es' ? 'Inicio' : 'Home'}</a></li>
            <li><a href="#servicios">{lang === 'es' ? 'Servicios' : 'Services'}</a></li>
            <li><a href="#clientes">{lang === 'es' ? 'Clientes' : 'Clients'}</a></li>
            <li><a href="#proceso">{lang === 'es' ? 'Proceso' : 'Process'}</a></li>
            <li><a href="#contacto">{lang === 'es' ? 'Contacto' : 'Contact'}</a></li>
          </ul>
        </div>
        <div>
          <h5>{lang === 'es' ? 'Contacto' : 'Contact'}</h5>
          <ul>
            <li><a href="mailto:hola@fromzero.es">hola@fromzero.es</a></li>
            <li><a href="tel:+34650720278">+34 650 720 278</a></li>
            <li><a href="#">Murcia, España</a></li>
          </ul>
        </div>
      </div>
      <div className="ticker">
        <div className="ticker-inner">
          {seq.map((w, i) => <span key={i}>{w}</span>)}
        </div>
      </div>
      <div className="footer-legal wrap">
        <a href="#" data-hover>{lang === 'es' ? 'Política de Privacidad' : 'Privacy Policy'}</a>
        <a href="#" data-hover>{lang === 'es' ? 'Aviso Legal' : 'Legal Notice'}</a>
        <a href="#" data-hover>{lang === 'es' ? 'Política de Cookies' : 'Cookie Policy'}</a>
        <a href="#" data-hover>{lang === 'es' ? 'Términos y Condiciones' : 'Terms & Conditions'}</a>
      </div>
      <div className="footer-bottom wrap">
        <div>© 2024 FromZero. {lang === 'es' ? 'Todos los derechos reservados.' : 'All rights reserved.'}</div>
        <div>{lang === 'es' ? 'Hecho desde cero · Murcia' : 'Made from zero · Murcia'}</div>
      </div>
    </footer>);

}

Object.assign(window, { Cursor, LogoFZ, TopBar, MenuOverlay, Hero, Servicios, Clientes, Proceso, PorQue, Equipo, Contacto, Footer, Reveal, Counter });