/* global React, Icon */

const AGENCY_METRICS = [
  { value: 3, label: "etapas de trabajo", detail: "Descubrimiento, implantación y evolución." },
  { value: 4, label: "soluciones iniciales", detail: "Software, web y apps, automatización e integraciones." },
  { value: 1, label: "equipo directo", detail: "Hablas con quienes entienden, diseñan y construyen." },
];

const AGENCY_SERVICES = [
  {
    icon: "code",
    number: "01",
    title: "Software a medida",
    text: "Centralizamos procesos, roles y datos en plataformas propias que eliminan hojas paralelas y se adaptan a tu operación.",
    href: "/service/software-a-medida/",
    outcomes: ["Procesos centralizados", "Roles y trazabilidad"],
  },
  {
    icon: "mobile",
    number: "02",
    title: "Experiencias web y aplicaciones",
    text: "Creamos sitios, portales y aplicaciones rápidos que comunican confianza, convierten visitas y facilitan servicios digitales.",
    href: "/service/desarrollo-webs/",
    outcomes: ["Conversión y confianza", "Responsive y rendimiento"],
  },
  {
    icon: "sparkle2",
    number: "03",
    title: "Automatización e IA aplicada",
    text: "Conectamos tareas, documentos y decisiones para reducir trabajo repetitivo, conservando control y supervisión humana.",
    href: "/service/automatizaciones/",
    outcomes: ["Menos tareas manuales", "Flujos medibles"],
  },
  {
    icon: "api",
    number: "04",
    title: "WhatsApp oficial e integraciones",
    text: "Integramos atención, notificaciones y procesos guiados mediante APIs oficiales, trazabilidad y derivación al equipo.",
    href: "/service/whatsapp-oficial/",
    outcomes: ["Canal oficial", "Bot y equipo humano"],
  },
  {
    icon: "chat",
    number: "05",
    title: "STAM Connect",
    text: "Producto propio para organizar atención, catálogo, proformas, agenda y automatizaciones conversacionales desde un solo panel.",
    href: "https://stamconnect.staminex.net/",
    outcomes: ["Catálogo y proformas", "Agenda y ventas"],
  },
];

const AGENCY_PROCESS = [
  {
    step: "01",
    title: "Descubrimiento",
    text: "Entendemos el negocio, detectamos el cuello de botella y delimitamos una primera versión útil.",
    image: "assets/projects/consultorio-medico.webp",
    alt: "Interfaz digital para la gestión de un consultorio médico",
  },
  {
    step: "02",
    title: "Desarrollo e implantación",
    text: "Diseñamos, construimos, probamos e integramos la solución en el trabajo diario de tu equipo.",
    image: "assets/projects/empresa-paqueteria.webp",
    alt: "Sistema digital para la operación de una empresa de paquetería",
  },
  {
    step: "03",
    title: "Soporte y evolución",
    text: "Acompañamos el uso real, resolvemos incidencias y priorizamos mejoras a partir de evidencia.",
    image: "assets/projects/laboratorio-clinico.webp",
    alt: "Plataforma digital para la gestión de un laboratorio clínico",
  },
];

const AUTOMATION_TOOLS = [
  [
    { slug: "whatsapp", name: "WhatsApp", short: "WA", color: "25D366" },
    { slug: "googlesheets", name: "Google Sheets", short: "GS", color: "34A853" },
    { slug: "googlecalendar", name: "Google Calendar", short: "GC", color: "4285F4" },
    { slug: "gmail", name: "Gmail", short: "GM", color: "EA4335" },
    { slug: "slack", name: "Slack", short: "SL", color: "E01E5A", fallback: true },
    { slug: "telegram", name: "Telegram", short: "TG", color: "26A5E4" },
    { slug: "microsoftteams", name: "Microsoft Teams", short: "MT", color: "6264A7", fallback: true },
  ],
  [
    { slug: "n8n", name: "n8n", short: "n8", color: "EA4B71" },
    { slug: "hubspot", name: "HubSpot", short: "HS", color: "FF7A59" },
    { slug: "notion", name: "Notion", short: "NO", color: "FFFFFF" },
    { slug: "stripe", name: "Stripe", short: "ST", color: "635BFF" },
    { slug: "shopify", name: "Shopify", short: "SH", color: "7AB55C" },
    { slug: "meta", name: "Meta", short: "ME", color: "0866FF" },
    { slug: "openai", name: "OpenAI", short: "AI", color: "FFFFFF", fallback: true },
  ],
];

const AUTOMATION_HEADING = "Software que avanza";

function AnimatedLetters({ text }) {
  return Array.from(text).map((character, index) => (
    <span className="ag-automation__letter-mask" aria-hidden="true" key={character + index}>
      <span className="ag-automation__char">{character}</span>
    </span>
  ));
}

function OrbitGlyph() {
  return (
    <span className="ag-automation-glyph ag-automation-glyph--orbit" aria-hidden="true">
      <svg viewBox="0 0 120 120">
        <defs>
          <linearGradient id="ag-glyph-gradient" x1="0" y1="0" x2="1" y2="1">
            <stop offset="0" stopColor="#d19aee" /><stop offset=".55" stopColor="#7626e8" /><stop offset="1" stopColor="#67e8f9" />
          </linearGradient>
        </defs>
        <g className="ag-automation-glyph__spinner">
          <circle className="ag-automation-glyph__draw" cx="60" cy="60" r="49" />
          <circle className="ag-automation-glyph__draw ag-automation-glyph__ring" cx="60" cy="60" r="35" />
          <circle className="ag-automation-glyph__node" cx="60" cy="11" r="5" />
        </g>
        <path className="ag-automation-glyph__mark" d="M35 43 60 29l25 14-25 14-25-14Zm0 28 25-14 25 14-25 14-25-14Z" />
      </svg>
    </span>
  );
}

function VectorSpark() {
  return (
    <span className="ag-automation-glyph ag-automation-glyph--spark" aria-hidden="true">
      <svg viewBox="0 0 120 120">
        <path className="ag-automation-glyph__draw" d="M60 5c0 30-25 55-55 55 30 0 55 25 55 55 0-30 25-55 55-55-30 0-55-25-55-55Z" />
        <g className="ag-automation-glyph__pieces">
          <path d="M60 8c0 28-23 50-51 52 28 1 51 24 51 52V8Z" />
          <path d="M60 8c0 28 23 50 51 52-28 1-51 24-51 52V8Z" />
        </g>
        <circle className="ag-automation-glyph__center" cx="60" cy="60" r="6" />
      </svg>
    </span>
  );
}

function AutomationHeading() {
  return (
    <h1 className="ag-automation__title" id="ag-automation-title" aria-label={AUTOMATION_HEADING}>
      <span className="ag-automation__line ag-automation__line--one">
        <span className="ag-automation__word">
          <AnimatedLetters text="S" />
          <OrbitGlyph />
          <AnimatedLetters text="FTWARE" />
        </span>
      </span>
      <span className="ag-automation__line ag-automation__line--two">
        <span className="ag-automation__word"><AnimatedLetters text="QUE" /></span>
        <VectorSpark />
        <span className="ag-automation__word"><AnimatedLetters text="AVANZA" /></span>
      </span>
    </h1>
  );
}

function AutomationVector() {
  return (
    <div className="ag-automation-vector" aria-hidden="true">
      <svg viewBox="0 0 1440 900" preserveAspectRatio="xMidYMid slice">
        <defs>
          <linearGradient id="ag-vector-gradient" x1="0" y1="0" x2="1" y2="1">
            <stop offset="0" stopColor="#d19aee" />
            <stop offset=".5" stopColor="#7626e8" />
            <stop offset="1" stopColor="#67e8f9" />
          </linearGradient>
          <radialGradient id="ag-runner-gradient">
            <stop offset="0" stopColor="#fff" />
            <stop offset=".45" stopColor="#d19aee" />
            <stop offset="1" stopColor="#7626e8" />
          </radialGradient>
        </defs>
        <g className="ag-automation-vector__grid">
          <path d="M90 0v900M330 0v900M570 0v900M810 0v900M1050 0v900M1290 0v900" />
          <path d="M0 150h1440M0 390h1440M0 630h1440M0 870h1440" />
        </g>
        <path className="ag-automation-vector__path ag-automation-vector__draw" d="M-80 236C190 76 390 370 650 214S1118 35 1520 250" />
        <path className="ag-automation-vector__path ag-automation-vector__draw" d="M-110 700C160 482 388 790 668 606S1120 424 1530 650" />
        <path className="ag-automation-vector__path ag-automation-vector__path--flow ag-automation-vector__draw ag-automation-vector__route" d="M-90 474C226 316 404 566 705 432S1165 254 1528 444" />
        <g className="ag-automation-vector__runner">
          <circle r="18" fill="rgba(118,38,232,.12)" />
          <circle r="7" fill="url(#ag-runner-gradient)" />
        </g>
        <g className="ag-automation-vector__nodes">
          <circle cx="177" cy="171" r="6" /><circle cx="399" cy="319" r="4" />
          <circle cx="1048" cy="122" r="5" /><circle cx="1252" cy="536" r="7" />
          <circle cx="276" cy="653" r="5" /><circle cx="816" cy="702" r="4" />
        </g>
      </svg>
    </div>
  );
}

const AGENCY_FAQS = [
  {
    question: "¿Trabajan con una solución estándar o a medida?",
    answer: "Partimos del problema y del contexto de cada empresa. Podemos construir una solución desde cero o integrar herramientas existentes cuando eso sea más eficiente.",
  },
  {
    question: "¿Cómo se define el alcance del proyecto?",
    answer: "En descubrimiento ordenamos objetivos, usuarios, procesos e integraciones. Con esa información delimitamos entregables, prioridades y una primera etapa verificable.",
  },
  {
    question: "¿Pueden conectar un sistema que ya utilizamos?",
    answer: "Sí, siempre que el sistema disponga de una API o un mecanismo de integración viable. Antes de comprometer el alcance revisamos su documentación y restricciones técnicas.",
  },
  {
    question: "¿STAM Connect es el servicio de agencia?",
    answer: "No. STAM Connect es un producto creado por STAMINEX para automatización y atención empresarial. La agencia desarrolla proyectos e integraciones a medida.",
  },
  {
    question: "¿Qué ocurre después de publicar la solución?",
    answer: "Podemos continuar con soporte y evolución: observamos el uso, atendemos incidencias y acordamos mejoras según el impacto que tengan en la operación.",
  },
];

function AgencyCount({ value }) {
  const ref = React.useRef(null);
  const frame = React.useRef(0);
  const [current, setCurrent] = React.useState(0);

  React.useEffect(() => {
    const node = ref.current;
    if (!node) return undefined;

    const reduceMotion = window.matchMedia && window.matchMedia("(prefers-reduced-motion: reduce)").matches;
    if (reduceMotion || !("IntersectionObserver" in window)) {
      setCurrent(value);
      return undefined;
    }

    const observer = new IntersectionObserver((entries) => {
      if (!entries[0].isIntersecting) return;
      observer.disconnect();
      const startedAt = performance.now();
      const animate = (now) => {
        const progress = Math.min((now - startedAt) / 900, 1);
        setCurrent(Math.round(value * (1 - Math.pow(1 - progress, 3))));
        if (progress < 1) frame.current = requestAnimationFrame(animate);
      };
      frame.current = requestAnimationFrame(animate);
    }, { threshold: 0.55 });

    observer.observe(node);
    return () => {
      observer.disconnect();
      cancelAnimationFrame(frame.current);
    };
  }, [value]);

  return <strong className="ag-metric__value" ref={ref}>{current}</strong>;
}

function AgencyAbout() {
  return (
    <section className="ag-section ag-about" id="agencia" aria-labelledby="ag-about-title">
      <div className="ag-container ag-about__grid">
        <div className="ag-about__visual reveal">
          <img src="assets/projects/staminex-equipo.webp" alt="Equipo de STAMINEX colaborando en un proyecto digital" />
          <span className="ag-about__stamp" aria-hidden="true">STAMINEX<br />ESTUDIO DIGITAL</span>
        </div>
        <div className="ag-about__copy reveal d2">
          <span className="ag-kicker">Sobre STAMINEX</span>
          <h2 className="ag-title" id="ag-about-title">Tecnología que se adapta al negocio, no al revés.</h2>
          <p className="ag-lead">STAMINEX es un equipo de soluciones digitales que diseña y desarrolla software, sitios, aplicaciones y automatizaciones para empresas.</p>
          <p>Trabajamos de forma directa: primero entendemos cómo opera tu negocio y después construimos la tecnología necesaria para simplificar procesos, conectar herramientas y crear mejores experiencias.</p>
          <div className="ag-about__note">
            <Icon name="spark" size={20} />
            <span>Diseño, desarrollo e implantación con un mismo equipo.</span>
          </div>
        </div>
      </div>
    </section>
  );
}

function AgencyMetrics() {
  return (
    <section className="ag-section ag-metrics" aria-label="Cómo trabaja STAMINEX">
      <div className="ag-container">
        <div className="ag-metrics__panel reveal">
          <div className="ag-metrics__intro">
            <span className="ag-kicker ag-kicker--light">Una estructura clara</span>
            <h2>Lo concreto antes que las cifras de escaparate.</h2>
            <p>Estos números describen nuestro modelo de trabajo y nuestra oferta inicial, no resultados inventados.</p>
          </div>
          <div className="ag-metrics__list">
            {AGENCY_METRICS.map((metric, index) => (
              <article className={"ag-metric reveal d" + (index + 1)} key={metric.label}>
                <AgencyCount value={metric.value} />
                <h3>{metric.label}</h3>
                <p>{metric.detail}</p>
              </article>
            ))}
          </div>
        </div>
      </div>
    </section>
  );
}

function AgencyServices() {
  return (
    <section className="ag-section ag-services" id="servicios-agencia" aria-labelledby="ag-services-title">
      <div className="ag-container">
        <header className="ag-heading reveal">
          <span className="ag-kicker">Soluciones STAMINEX Tech</span>
          <h2 className="ag-title" id="ag-services-title">Tecnología diseñada para resolver, conectar y crecer.</h2>
          <p>Partimos del resultado que necesita tu empresa y combinamos producto, automatización e integración sin forzar procesos dentro de una plantilla.</p>
        </header>
        <div className="ag-services__grid">
          {AGENCY_SERVICES.map((service, index) => (
            <article className={"ag-service reveal d" + ((index % 3) + 1)} key={service.title}>
              <div className="ag-service__top">
                <span className="ag-service__icon"><Icon name={service.icon} size={24} /></span>
                <span className="ag-service__number">{service.number}</span>
              </div>
              <span className="ag-service__signal" aria-hidden="true"><i /><i /><i /><i /></span>
              <h3>{service.title}</h3>
              <p>{service.text}</p>
              <ul className="ag-service__outcomes" aria-label={"Resultados de " + service.title}>
                {service.outcomes.map((outcome) => <li key={outcome}><Icon name="check" size={12} /> {outcome}</li>)}
              </ul>
              {service.href && <a className="ag-service__link" href={service.href}>{service.number === "05" ? "Conocer el producto" : "Ver servicio"} <Icon name="arrow" size={16} /></a>}
            </article>
          ))}
        </div>
      </div>
    </section>
  );
}

function AgencyProcess() {
  return (
    <section className="ag-section ag-process" id="proceso-agencia" aria-labelledby="ag-process-title">
      <div className="ag-container">
        <header className="ag-heading ag-heading--split reveal">
          <div>
            <span className="ag-kicker">Proceso</span>
            <h2 className="ag-title" id="ag-process-title">De la conversación a una herramienta en uso.</h2>
          </div>
          <p>Avanzamos por etapas comprensibles, con decisiones visibles y una solución que puede seguir evolucionando.</p>
        </header>
        <div className="ag-process__grid">
          {AGENCY_PROCESS.map((item, index) => (
            <article className={"ag-process-card ag-process-card--" + (index + 1) + " reveal d" + (index + 1)} key={item.step}>
              <img src={item.image} alt={item.alt} />
              <div className="ag-process-card__shade" />
              <div className="ag-process-card__content">
                <span>{item.step} / 03</span>
                <h3>{item.title}</h3>
                <p>{item.text}</p>
              </div>
            </article>
          ))}
        </div>
      </div>
    </section>
  );
}

function AgencyAutomation() {
  const sectionRef = React.useRef(null);

  React.useLayoutEffect(() => {
    const section = sectionRef.current;
    const gsap = window.gsap;
    const drawSVG = window.DrawSVGPlugin;
    const motionPath = window.MotionPathPlugin;
    const reduceMotion = window.matchMedia && window.matchMedia("(prefers-reduced-motion: reduce)").matches;
    if (!section || !gsap || reduceMotion) return undefined;

    const plugins = [drawSVG, motionPath].filter(Boolean);
    if (plugins.length) gsap.registerPlugin(...plugins);

    let moveHandler;

    const context = gsap.context(() => {
      const timeline = gsap.timeline({ defaults: { ease: "power3.out" } });
      timeline
        .from(".ag-automation-vector__draw", drawSVG ? { drawSVG: "0%", duration: 1.9, stagger: .12, ease: "power2.inOut" } : { strokeDashoffset: 1, duration: 1.9, stagger: .12 })
        .from(".ag-automation-vector__nodes circle", { scale: 0, transformOrigin: "center", duration: .55, stagger: .09 }, .25)
        .from(".ag-automation__head .ag-kicker", { y: -14, opacity: 0, duration: .55 }, .15)
        .from(".ag-automation__char", { yPercent: 120, rotateX: -92, opacity: 0, transformOrigin: "50% 100%", duration: .9, stagger: .025, ease: "power4.out" }, .3)
        .from(".ag-automation-glyph", { scale: 0, rotation: -100, opacity: 0, duration: 1, stagger: .14, ease: "back.out(1.5)" }, .48)
        .from(".ag-automation-glyph__pieces path", { scale: 0, transformOrigin: "center", duration: .55, stagger: .08, ease: "back.out(2)" }, .8)
        .from(".ag-automation__head > p", { y: 24, opacity: 0, duration: .7 }, 1.05)
        .from(".ag-automation-stage", { y: 52, scale: .97, opacity: 0, duration: 1 }, 1.15);

      gsap.to(".ag-automation-glyph__spinner", { rotation: 360, transformOrigin: "center", duration: 14, repeat: -1, ease: "none" });
      gsap.to(".ag-automation-glyph--spark", { yPercent: -9, rotation: 8, duration: 2.8, repeat: -1, yoyo: true, ease: "sine.inOut" });
      gsap.to(".ag-automation-vector__nodes circle", { opacity: .25, scale: .55, duration: 1.6, stagger: { each: .22, repeat: -1, yoyo: true }, transformOrigin: "center" });

      if (motionPath) gsap.to(".ag-automation-vector__runner", {
        motionPath: { path: ".ag-automation-vector__route", align: ".ag-automation-vector__route", alignOrigin: [.5, .5] },
        duration: 10,
        repeat: -1,
        ease: "none",
      });

      if (window.matchMedia("(pointer: fine)").matches) {
        const vectorX = gsap.quickTo(".ag-automation-vector svg", "x", { duration: 1.2, ease: "power3.out" });
        const vectorY = gsap.quickTo(".ag-automation-vector svg", "y", { duration: 1.2, ease: "power3.out" });
        moveHandler = (event) => {
          vectorX((event.clientX / window.innerWidth - .5) * 22);
          vectorY((event.clientY / window.innerHeight - .5) * 14);
        };
        section.addEventListener("pointermove", moveHandler, { passive: true });
      }
    }, section);

    return () => {
      if (moveHandler) section.removeEventListener("pointermove", moveHandler);
      context.revert();
    };
  }, []);

  return (
    <section className="ag-section ag-automation ag-automation--intro" id="inicio" aria-labelledby="ag-automation-title" ref={sectionRef}>
      <AutomationVector />
      <div className="ag-container ag-automation__head">
        <span className="ag-kicker">STAMINEX / Software Studio</span>
        <AutomationHeading />
        <p>Diseñamos sistemas, experiencias digitales y automatizaciones que convierten procesos complejos en operaciones más simples, conectadas y escalables.</p>
      </div>
      <div className="ag-automation-stage" aria-label="Herramientas que STAMINEX puede conectar">
        <div className="ag-tool-streams">
          {AUTOMATION_TOOLS.map((row, rowIndex) => {
          const repeated = row.concat(row);
          return (
            <div className={"ag-tool-stream ag-tool-stream--" + (rowIndex === 0 ? "forward" : "reverse")} key={rowIndex}>
              <div className="ag-tool-stream__track">
                {repeated.map((tool, index) => (
                  <span className={"ag-tool" + (tool.fallback ? " is-fallback" : "")} aria-hidden={index >= row.length ? "true" : undefined} key={tool.slug + index} title={tool.name}>
                    {!tool.fallback && <img
                        src={`https://cdn.simpleicons.org/${tool.slug}/${tool.color}`}
                        alt=""
                        loading="lazy"
                        onError={(event) => event.currentTarget.parentElement.classList.add("is-fallback")}
                      />}
                    <span className="ag-tool__fallback" aria-hidden="true">{tool.short}</span>
                    <small>{tool.name}</small>
                  </span>
                ))}
              </div>
            </div>
          );
        })}
        </div>
        <div className="ag-automation-core" aria-label="STAMINEX centraliza tus automatizaciones">
          <span className="ag-automation-core__ring ag-automation-core__ring--outer" />
          <span className="ag-automation-core__ring ag-automation-core__ring--inner" />
          <span className="ag-automation-core__orbit"><i /><i /><i /></span>
          <span className="ag-automation-core__logo"><img src="assets/staminex-mark.png" alt="STAMINEX Tech" /></span>
          <strong>STAMINEX</strong>
          <small>Automatizaciones</small>
        </div>
      </div>
    </section>
  );
}

function StamConnectProduct() {
  return (
    <section className="ag-section ag-product" aria-labelledby="ag-product-title">
      <div className="ag-container">
        <div className="ag-product__card reveal">
          <div className="ag-product__copy">
            <span className="ag-product__label"><Icon name="sparkle2" size={16} /> Producto STAMINEX</span>
            <h2 id="ag-product-title">STAM <span>Connect</span></h2>
            <p>Una plataforma creada por STAMINEX para automatizar atención y procesos conversacionales. Es un producto propio, distinto de nuestro servicio de agencia y desarrollo a medida.</p>
            <a className="ag-product__cta" href="https://stamconnect.staminex.net/">Conocer STAM Connect <Icon name="arrow" size={18} /></a>
          </div>
          <div className="ag-product__visual" aria-hidden="true">
            <div className="ag-product__orb"><Icon name="chat" size={48} /></div>
            <span className="ag-product__chip ag-product__chip--one"><Icon name="bot" size={18} /> Atención</span>
            <span className="ag-product__chip ag-product__chip--two"><Icon name="bolt" size={18} /> Automatización</span>
            <span className="ag-product__chip ag-product__chip--three"><Icon name="bars" size={18} /> Seguimiento</span>
          </div>
        </div>
      </div>
    </section>
  );
}

function AgencyFAQ() {
  const [openIndex, setOpenIndex] = React.useState(0);
  const baseId = React.useId().replace(/:/g, "");

  return (
    <section className="ag-section ag-faq" id="preguntas-agencia" aria-labelledby={baseId + "-title"}>
      <div className="ag-container ag-faq__layout">
        <header className="ag-faq__head reveal">
          <span className="ag-kicker">Preguntas frecuentes</span>
          <h2 className="ag-title" id={baseId + "-title"}>Antes de empezar, hablemos claro.</h2>
          <p>Algunas respuestas sobre el alcance, la integración y la relación entre la agencia y STAM Connect.</p>
        </header>
        <div className="ag-faq__list reveal d2">
          {AGENCY_FAQS.map((item, index) => {
            const isOpen = openIndex === index;
            const buttonId = baseId + "-question-" + index;
            const panelId = baseId + "-answer-" + index;
            return (
              <div className={"ag-faq__item" + (isOpen ? " is-open" : "")} key={item.question}>
                <h3>
                  <button
                    type="button"
                    id={buttonId}
                    aria-expanded={isOpen}
                    aria-controls={panelId}
                    onClick={() => setOpenIndex(isOpen ? -1 : index)}
                  >
                    <span>{item.question}</span>
                    <span className="ag-faq__plus" aria-hidden="true" />
                  </button>
                </h3>
                <div className="ag-faq__answer" id={panelId} role="region" aria-labelledby={buttonId} hidden={!isOpen}>
                  <p>{item.answer}</p>
                </div>
              </div>
            );
          })}
        </div>
      </div>
    </section>
  );
}

Object.assign(window, {
  AgencyAbout,
  AgencyMetrics,
  AgencyServices,
  AgencyProcess,
  AgencyAutomation,
  StamConnectProduct,
  AgencyFAQ,
});
