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

/* ---------- Icons (minimal stroke set) ---------- */
const Ico = {
  chat: (p) => (
    <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round" strokeLinejoin="round" width="26" height="26" {...p}>
      <path d="M21 11.5a8.4 8.4 0 0 1-12.1 7.5L3 20.5l1.6-5A8.4 8.4 0 1 1 21 11.5Z" />
      <path d="M8.5 11.5h7M8.5 14h4.5" />
    </svg>
  ),
  pos: (p) => (
    <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round" strokeLinejoin="round" width="26" height="26" {...p}>
      <rect x="4" y="3" width="16" height="14" rx="2.2" />
      <path d="M8 7h8M8 10.5h5M3 21h18M9 17l-1 4M15 17l1 4" />
    </svg>
  ),
  code: (p) => (
    <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round" strokeLinejoin="round" width="26" height="26" {...p}>
      <path d="m8 8-4 4 4 4M16 8l4 4-4 4M14 6l-4 12" />
    </svg>
  ),
  chip: (p) => (
    <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round" strokeLinejoin="round" width="22" height="22" {...p}>
      <rect x="7" y="7" width="10" height="10" rx="2" />
      <path d="M9.5 10.5h5v3h-5z M12 3v4M9 3v4M15 3v4M12 17v4M9 17v4M15 17v4M3 12h4M3 9h4M3 15h4M17 12h4M17 9h4M17 15h4" />
    </svg>
  ),
  flex: (p) => (
    <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round" strokeLinejoin="round" width="22" height="22" {...p}>
      <path d="M3 12a9 9 0 0 1 15.5-6.2M21 12a9 9 0 0 1-15.5 6.2" />
      <path d="M18.5 3v3h-3M5.5 21v-3h3" />
    </svg>
  ),
  support: (p) => (
    <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round" strokeLinejoin="round" width="22" height="22" {...p}>
      <path d="M4 13v-1a8 8 0 0 1 16 0v1" />
      <rect x="2.5" y="13" width="4" height="6" rx="2" />
      <rect x="17.5" y="13" width="4" height="6" rx="2" />
      <path d="M20 19a4 4 0 0 1-4 3.2h-2" />
    </svg>
  ),
  pin: (p) => (
    <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round" strokeLinejoin="round" width="22" height="22" {...p}>
      <path d="M12 21s7-6.2 7-11a7 7 0 1 0-14 0c0 4.8 7 11 7 11Z" />
      <circle cx="12" cy="10" r="2.6" />
    </svg>
  ),
  arrow: (p) => (
    <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" width="17" height="17" {...p}>
      <path d="M5 12h13M13 6l6 6-6 6" />
    </svg>
  ),
  wa: (p) => (
    <svg viewBox="0 0 24 24" fill="currentColor" width="19" height="19" {...p}>
      <path d="M17.5 14.4c-.3-.15-1.7-.84-2-.93-.27-.1-.46-.15-.65.15-.2.3-.75.93-.92 1.12-.17.2-.34.22-.63.07a8.2 8.2 0 0 1-2.4-1.48 9 9 0 0 1-1.67-2.07c-.17-.3 0-.46.13-.6.13-.14.3-.34.44-.51.15-.17.2-.3.3-.5.1-.2.05-.37-.02-.52-.08-.15-.65-1.57-.9-2.15-.23-.56-.47-.48-.65-.49h-.55c-.2 0-.5.07-.77.37-.26.3-1 .98-1 2.4 0 1.4 1.03 2.76 1.17 2.95.15.2 2.03 3.1 4.92 4.35.69.3 1.22.47 1.64.6.69.22 1.32.2 1.81.12.55-.08 1.7-.7 1.94-1.36.24-.67.24-1.24.17-1.36-.07-.12-.26-.2-.55-.34Z" />
      <path d="M12 2a10 10 0 0 0-8.5 15.3L2 22l4.8-1.5A10 10 0 1 0 12 2Zm0 18.2a8.2 8.2 0 0 1-4.2-1.15l-.3-.18-3 .94.95-2.92-.2-.31A8.2 8.2 0 1 1 12 20.2Z" />
    </svg>
  ),
};

const WA_ADVISOR = "https://wa.me/51993260417?text=Hola%2C%20quiero%20saber%20m%C3%A1s%20sobre%20sus%20soluciones";
const WA_AI = "https://wa.me/51993260417?text=Hola%2C%20me%20interesa%20saber%20m%C3%A1s%20sobre%20sus%20servicios";

/* Scroll-reveal — content is visible by default; the entrance animation only
   arms when the tab is actually visible (animations run) and motion is allowed.
   This guarantees content is NEVER stuck hidden (frozen tab, reduced-motion, etc). */
function Reveal({ as: Tag = "div", d, className = "", children, ...rest }) {
  const ref = useRef(null);
  const [st, setSt] = useState({ armed: false, shown: false });
  useLayoutEffect(() => {
    const el = ref.current;
    let done = false;
    const inView = () => {
      const r = el.getBoundingClientRect();
      return r.top < window.innerHeight * 0.92 && r.bottom > -40;
    };
    if (inView()) { setSt({ armed: true, shown: true }); return; }
    setSt({ armed: true, shown: false });
    const onScroll = () => {
      if (!done && inView()) { done = true; setSt({ armed: true, shown: true }); window.removeEventListener("scroll", onScroll); }
    };
    window.addEventListener("scroll", onScroll, { passive: true });
    return () => window.removeEventListener("scroll", onScroll);
  }, []);
  const cls = `reveal ${st.armed ? "anim" : ""} ${st.shown ? "in" : ""} ${className}`.replace(/\s+/g, " ").trim();
  return <Tag ref={ref} data-d={d} className={cls} {...rest}>{children}</Tag>;
}

/* ---------- Nav ---------- */
function Nav() {
  const [scrolled, setScrolled] = useState(false);
  const [open, setOpen] = useState(false);
  useEffect(() => {
    const onScroll = () => setScrolled(window.scrollY > 12);
    onScroll(); window.addEventListener("scroll", onScroll, { passive: true });
    return () => window.removeEventListener("scroll", onScroll);
  }, []);
  const links = [["Soluciones", "#soluciones"], ["Nosotros", "#nosotros"], ["Contacto", "#contacto"]];
  return (
    <nav className={`nav ${scrolled ? "scrolled" : ""}`}>
      <div className="wrap nav-inner">
        <a className="brand" href="#top">
          <img className="badge" src="assets/wdp-badge.png" alt="WorkDataPlace" />
          <span><b>WorkData</b><span className="dim">Place</span></span>
        </a>
        <div className={`nav-links ${open ? "open" : ""}`}>
          {links.map(([l, h]) => (
            <a key={h} className="navlink" href={h} onClick={() => setOpen(false)}>{l}</a>
          ))}
          <a className="btn btn-primary btn-sm nav-cta" href={WA_ADVISOR} target="_blank" rel="noopener" onClick={() => setOpen(false)}>Empezar</a>
        </div>
        <button className="nav-burger" aria-label="Menú" onClick={() => setOpen((o) => !o)}>
          <svg viewBox="0 0 24 24" width="22" height="22" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round">
            {open ? <path d="M6 6l12 12M18 6 6 18" /> : <path d="M3 7h18M3 12h18M3 17h18" />}
          </svg>
        </button>
      </div>
    </nav>
  );
}

/* ---------- Hero ---------- */
function Hero() {
  const stageRef = useRef(null);
  useEffect(() => {
    const onScroll = () => {
      const y = window.scrollY;
      const s = stageRef.current; if (!s) return;
      s.style.setProperty("--py", `${y * 0.04}px`);
    };
    window.addEventListener("scroll", onScroll, { passive: true });
    return () => window.removeEventListener("scroll", onScroll);
  }, []);
  const stars = Array.from({ length: 26 }, (_, i) => ({
    left: `${(i * 37) % 100}%`, top: `${(i * 53) % 100}%`,
    delay: `${(i % 7) * 0.5}s`, size: i % 5 === 0 ? 3 : 2,
  }));
  return (
    <header className="hero dark" id="top">
      <div className="stars">
        {stars.map((s, i) => (
          <i key={i} style={{ left: s.left, top: s.top, animationDelay: s.delay, width: s.size, height: s.size }} />
        ))}
      </div>
      <div className="wrap hero-grid">
        <div>
          <Reveal as="p" className="eyebrow">Soluciones tecnológicas · Lima, Perú</Reveal>
          <Reveal as="h1" className="display" d="1">
            Transformamos tu negocio con <span className="grad-text">inteligencia artificial</span>
          </Reveal>
          <Reveal as="p" className="lead" d="2">
            Chatbots, sistemas de punto de venta y desarrollo web diseñados para empresas que quieren crecer de forma inteligente.
          </Reveal>
          <Reveal className="hero-cta" d="2">
            <a className="btn btn-primary" href={WA_ADVISOR} target="_blank" rel="noopener">{Ico.wa()} Hablar con un asesor</a>
            <a className="btn btn-ghost on-dark" href="#soluciones">Ver soluciones</a>
          </Reveal>
          <Reveal className="hero-meta" d="3">
            <div className="stat"><div className="n grad-text">24/7</div><div className="l">Atención automatizada</div></div>
            <div className="stat"><div className="n grad-text">SUNAT</div><div className="l">Facturación electrónica</div></div>
            <div className="stat"><div className="n grad-text">100%</div><div className="l">Hecho en Perú</div></div>
          </Reveal>
        </div>
        <div className="orb-stage" ref={stageRef} style={{ transform: "translateY(var(--py,0))" }}>
          <div className="aurora"><div className="blob b1" /><div className="blob b2" /><div className="blob b3" /></div>
          <div className="ring r2"><span className="dot" /></div>
          <div className="ring r1" />
          <img className="badge-hero" src="assets/wdp-badge.png" alt="WorkDataPlace — astronauta" />
        </div>
      </div>
    </header>
  );
}

/* ---------- Solutions ---------- */
const SOLUTIONS = [
  { tag: "IA conversacional", icon: "chat", title: "Chatbot WhatsApp IA",
    body: "Atiende a tus clientes 24/7 con IA que conoce tu negocio. Toma pedidos, agenda reservas, imprime comandas en cocina y transfiere a un humano cuando hace falta. Compatible con tu número actual.",
    cta: "Conocer más", href: "https://api.workdataplace.com" },
  { tag: "Punto de venta", icon: "pos", title: "POS Inteligente",
    body: "Sistema completo con facturación electrónica SUNAT, inventario, control de caja, delivery (Rappi, PedidosYa), recetas y reportes en tiempo real. Multi-sucursal, hecho para negocios peruanos.",
    cta: "Solicitar demo", href: "https://software-pos.wdpsolutions.com" },
  { tag: "Web a medida", icon: "code", title: "Desarrollo Web",
    body: "Páginas modernas con diseño profesional, optimizadas para SEO y conversión. Landing pages, tiendas online, portales y sistemas web a medida con deploy rápido y dominio propio.",
    cta: "Ver proyectos", href: "https://desarrollo-web.wdpsolutions.com" },
];

function Solutions() {
  return (
    <section className="section-pad" id="soluciones">
      <div className="wrap">
        <Reveal className="sec-head">
          <p className="eyebrow">Soluciones</p>
          <h2 className="h2" style={{ marginTop: 14 }}>Todo lo que tu empresa necesita</h2>
          <p className="lead">Herramientas inteligentes que se adaptan a tu negocio y trabajan por ti las 24 horas.</p>
        </Reveal>
        <div className="cards">
          {SOLUTIONS.map((s, i) => (
            <Reveal key={s.title} className="card" d={String(i + 1)}>
              <span className="tag">{s.tag}</span>
              <div className="ico">{Ico[s.icon]()}</div>
              <h3>{s.title}</h3>
              <p>{s.body}</p>
              <div className="foot">
                <a className="link-arrow" href={s.href} target="_blank" rel="noopener">{s.cta} {Ico.arrow()}</a>
              </div>
            </Reveal>
          ))}
        </div>
      </div>
    </section>
  );
}

/* ---------- Why us ---------- */
const FEATURES = [
  { icon: "chip", title: "Tecnología de punta", body: "IA avanzada, infraestructura cloud y las mejores prácticas de la industria." },
  { icon: "flex", title: "Sin contratos largos", body: "Planes flexibles, sin letra chica. Cancela cuando quieras, sin penalidades." },
  { icon: "support", title: "Soporte 24/7", body: "Equipo disponible en cualquier momento, con respuesta rápida garantizada." },
  { icon: "pin", title: "Hecho en Perú", body: "Entendemos el mercado local. Soluciones pensadas para la realidad peruana." },
];

function WhyUs() {
  return (
    <section className="section-pad dark" id="nosotros">
      <div className="stars">
        {Array.from({ length: 18 }, (_, i) => (
          <i key={i} style={{ left: `${(i * 61) % 100}%`, top: `${(i * 29) % 100}%`, animationDelay: `${(i % 6) * 0.6}s` }} />
        ))}
      </div>
      <div className="wrap" style={{ position: "relative", zIndex: 1 }}>
        <Reveal className="sec-head">
          <p className="eyebrow">Por qué elegirnos</p>
          <h2 className="h2" style={{ marginTop: 14 }}>Tecnología que entiende tu negocio</h2>
          <p className="lead">No somos una agencia más. Construimos herramientas reales que generan resultados desde el día uno.</p>
        </Reveal>
        <div className="feat-grid">
          {FEATURES.map((f, i) => (
            <Reveal key={f.title} className="feat" d={String((i % 3) + 1)}>
              <div className="ico">{Ico[f.icon]()}</div>
              <h3>{f.title}</h3>
              <p>{f.body}</p>
            </Reveal>
          ))}
        </div>
      </div>
    </section>
  );
}

/* ---------- CTA ---------- */
function CTA() {
  return (
    <section className="section-pad" id="contacto">
      <div className="wrap">
        <Reveal className="cta-band dark">
          <div className="aurora"><div className="blob b1" /><div className="blob b2" /><div className="blob b3" /></div>
          <p className="eyebrow" style={{ position: "relative", zIndex: 2 }}>Conversemos</p>
          <h2 className="h2" style={{ marginTop: 16 }}>¿Listo para automatizar tu negocio?</h2>
          <p className="lead" style={{ maxWidth: "44ch", margin: "18px auto 34px" }}>
            Hablemos sobre cómo la tecnología puede hacer crecer tu empresa. Sin compromiso.
          </p>
          <a className="btn btn-primary" href={WA_AI} target="_blank" rel="noopener" style={{ fontSize: "1.08rem" }}>
            {Ico.wa()} Chatear con nuestro asesor IA
          </a>
        </Reveal>
      </div>
    </section>
  );
}

/* ---------- Footer ---------- */
function Footer() {
  return (
    <footer className="footer dark">
      <div className="wrap">
        <div className="foot-grid">
          <div className="foot-brand">
            <a className="brand" href="#top"><img className="badge" src="assets/wdp-badge.png" alt="" /><span><b>WorkData</b><span className="dim">Place</span></span></a>
            <p className="lead">Soluciones tecnológicas para empresas que quieren crecer con inteligencia artificial y automatización.</p>
          </div>
          <div className="foot-col">
            <h4>Soluciones</h4>
            <a href="https://api.workdataplace.com" target="_blank" rel="noopener">Chatbot WhatsApp</a>
            <a href="https://software-pos.wdpsolutions.com" target="_blank" rel="noopener">POS Inteligente</a>
            <a href="https://desarrollo-web.wdpsolutions.com" target="_blank" rel="noopener">Desarrollo Web</a>
          </div>
          <div className="foot-col">
            <h4>Empresa</h4>
            <a href="#nosotros">Nosotros</a>
            <a href="#contacto">Contacto</a>
            <a href="privacidad.html">Privacidad</a>
            <a href="terminos.html">Términos</a>
          </div>
        </div>
        <div className="foot-bottom">
          <span>© 2026 WorkDataPlace · Lima, Perú</span>
          <span>Tecnología hecha en Perú</span>
        </div>
      </div>
    </footer>
  );
}

Object.assign(window, { Nav, Hero, Solutions, WhyUs, CTA, Footer });
