/* ServicioPage — shared component rendering one service page from data. */
const { useEffect: useEffectServ, useRef: useRefServ, useState: useStateServ } = React;

/* ---------- Logo ---------- */
const LogoServ = ({ size = 32 }) => (
  <span style={{ display: 'inline-flex', alignItems: 'center', gap: 10, color: '#FAFAFA' }}>
    <svg width={size} height={size} viewBox="0 0 32 32" fill="none">
      <g stroke="currentColor" strokeWidth="1.5" fill="none" strokeLinecap="round">
        <circle cx="16" cy="16" r="4"/>
        <line x1="16" y1="12" x2="16" y2="4"/>
        <line x1="16" y1="20" x2="16" y2="28"/>
        <line x1="19.5" y1="14" x2="26" y2="10"/>
        <line x1="19.5" y1="18" x2="26" y2="22"/>
        <line x1="12.5" y1="14" x2="6" y2="10"/>
        <line x1="12.5" y1="18" x2="6" y2="22"/>
        <circle cx="16" cy="2.5" r="1.8" fill="currentColor"/>
        <circle cx="16" cy="29.5" r="1.8" fill="currentColor"/>
        <circle cx="27.5" cy="9.2" r="1.8" fill="currentColor"/>
        <circle cx="27.5" cy="22.8" r="1.8" fill="currentColor"/>
        <circle cx="4.5" cy="9.2" r="1.8" fill="currentColor"/>
        <circle cx="4.5" cy="22.8" r="1.8" fill="currentColor"/>
      </g>
    </svg>
    <window.Wordmark fontSize={17}/>
  </span>
);

/* ---------- Navbar ---------- */
/* ---------- Navbar (mega-menu, sub-page) ---------- */
const NavbarServ = ({ currentService }) => {
  const ctx = window.useMegaMenuMM();
  return (
    <nav className="nav-fixed" ref={ctx.wrapRef}>
      <a href="../index.html" aria-label="Geishia"><LogoServ size={34}/></a>
      <div className="nav-pill liquid-glass">
        <a href="../index.html">Inicio</a>
        <window.MegaTrigger
          which="servicios"
          label="Servicios"
          items={window.SERVICIOS_MENU}
          basePath="../"
          currentKey={currentService}
          isActive={true}
          ctx={ctx}
        />
        <a href="../empresa/sobre-nosotros.html">Sobre nosotros</a>
        <a href="../index.html#diagnostico">Diagnóstico</a>
        <a href="../index.html#contacto">Contacto</a>
      </div>
      <a href="../index.html#contacto" className="btn-primary btn-sm">
        Agendar reunión <Icons.ArrowUpRight size={14}/>
      </a>
    </nav>
  );
};

/* ---------- FadeUp local ---------- */
const FadeUpServ = window.FadeUp || (({ children, delay = 0, className = '' }) => {
  const ref = useRefServ(null);
  const [visible, setVisible] = useStateServ(false);
  useEffectServ(() => {
    const el = ref.current;
    if (!el) return;
    const io = new IntersectionObserver(([e]) => {
      if (e.isIntersecting) { setVisible(true); io.disconnect(); }
    }, { threshold: 0.1 });
    io.observe(el);
    return () => io.disconnect();
  }, []);
  return (
    <div ref={ref} className={`fadeup ${visible ? 'is-visible' : ''} ${className}`}
         style={{ transitionDelay: `${delay}ms` }}>
      {children}
    </div>
  );
});

/* ---------- Breadcrumb ---------- */
const BreadcrumbServ = ({ label }) => (
  <nav className="serv-breadcrumb" aria-label="Breadcrumb">
    <a href="../index.html">Inicio</a>
    <Icons.ChevronRight size={14}/>
    <span>Servicios</span>
    <Icons.ChevronRight size={14}/>
    <span className="serv-bc-current">{label}</span>
  </nav>
);

/* ---------- Hero ---------- */
const ServHero = ({ d }) => (
  <section className="serv-hero" data-screen-label="01 Hero">
    <div className="section-glow violet" data-parallax="0.2"
         style={{ top: '20%', left: '50%', transform: 'translateX(-50%)' }}/>
    <div className="container">
      <BreadcrumbServ label={d.label}/>
      <FadeUpServ delay={80}>
        <span className="eyebrow-mono eyebrow-violet">{d.eyebrow}</span>
      </FadeUpServ>
      <FadeUpServ delay={160}>
        <h1 className="h1-display">{d.h1}</h1>
      </FadeUpServ>
      <FadeUpServ delay={280}>
        <p className="body-lead serv-hero-sub">{d.sub}</p>
      </FadeUpServ>
      <FadeUpServ delay={400}>
        <div className="serv-hero-stats mono">{d.stats}</div>
      </FadeUpServ>
      <FadeUpServ delay={520}>
        <div className="serv-hero-ctas">
          <a href="../index.html#diagnostico" className="btn-primary btn-warm-shimmer">
            Hablemos de tu proyecto <Icons.ArrowRight size={15}/>
          </a>
          <a href="#proposals" className="btn-glass">
            Ver propuestas <Icons.ArrowDown size={15}/>
          </a>
        </div>
      </FadeUpServ>
    </div>
  </section>
);

/* ---------- Problems ---------- */
const ServProblems = ({ d }) => (
  <section className="section" data-screen-label="02 Problema">
    <div className="container">
      <div className="section-header">
        <FadeUpServ><span className="eyebrow-mono eyebrow-violet">El problema</span></FadeUpServ>
        <FadeUpServ delay={80}>
          <h2 className="h2-display">Lo que está fallando hoy</h2>
        </FadeUpServ>
      </div>
      <div className="grid-3">
        {d.problems.map((p, i) => {
          const I = iconFromName(p.icon);
          return (
            <FadeUpServ key={i} delay={i * 100}>
              <article className="dolor-card liquid-glass">
                <div className="dolor-icon-wrap"><I size={24}/></div>
                <h4 className="dolor-title">{p.title}</h4>
                <p className="dolor-body">{p.body}</p>
              </article>
            </FadeUpServ>
          );
        })}
      </div>
    </div>
  </section>
);

/* ---------- Proposals ---------- */
const ServProposals = ({ d }) => (
  <section id="proposals" className="section" data-screen-label="03 Propuestas">
    <div className="section-glow violet" data-parallax="0.18"
         style={{ top: '30%', right: '-200px' }}/>
    <div className="container">
      <div className="section-header">
        <FadeUpServ><span className="eyebrow-mono eyebrow-violet">Cómo trabajamos</span></FadeUpServ>
        <FadeUpServ delay={80}>
          <h2 className="h2-display">Dos enfoques, mismo nivel de exigencia.</h2>
        </FadeUpServ>
      </div>
      <div className="serv-proposals-grid">
        {d.proposals.map((p, i) => (
          <FadeUpServ key={i} delay={i * 120}>
            <article className="serv-proposal-card liquid-glass">
              <div className="serv-proposal-num mono">0{i+1}</div>
              <h3 className="serv-proposal-title">{p.title}</h3>
              <p className="serv-proposal-subtitle">{p.subtitle}</p>
              <p className="serv-proposal-desc">{p.desc}</p>
              <ul className="serv-proposal-bullets">
                {p.bullets.map((b, j) => (
                  <li key={j}>
                    <Icons.Check size={16}/>
                    <span>{b}</span>
                  </li>
                ))}
              </ul>
              <div className="serv-proposal-scope">
                <span className="serv-scope-label mono">¿Es para vos?</span>
                <p>{p.scope}</p>
              </div>
            </article>
          </FadeUpServ>
        ))}
      </div>
    </div>
  </section>
);

/* ---------- Deliverables ---------- */
const ServDeliverables = ({ d }) => (
  <section className="section" data-screen-label="04 Entregables">
    <div className="container">
      <div className="section-header">
        <FadeUpServ><span className="eyebrow-mono eyebrow-violet">Qué entregamos</span></FadeUpServ>
        <FadeUpServ delay={80}>
          <h2 className="h2-display">8 cosas que están incluidas siempre.</h2>
        </FadeUpServ>
        <FadeUpServ delay={160}>
          <p className="body-lead">
            No hay letra chica ni extras sorpresa. Esto es lo que recibe cada cliente sin importar el tamaño del proyecto.
          </p>
        </FadeUpServ>
      </div>
      <div className="serv-deliv-grid">
        {d.deliverables.map((item, i) => {
          const I = iconFromName(item.icon);
          return (
            <FadeUpServ key={i} delay={i * 60}>
              <article className="serv-deliv-card">
                <div className="serv-deliv-icon"><I size={20}/></div>
                <h4 className="serv-deliv-title">{item.title}</h4>
                <p className="serv-deliv-desc">{item.desc}</p>
              </article>
            </FadeUpServ>
          );
        })}
      </div>
    </div>
  </section>
);

/* ---------- Process timeline ---------- */
const ServProcess = ({ d }) => {
  if (!d.process || !d.process.length) return null;
  return (
  <section className="section" data-screen-label="05 Proceso">
    <div className="container">
      <div className="section-header">
        <FadeUpServ><span className="eyebrow-mono eyebrow-violet">Proceso</span></FadeUpServ>
        <FadeUpServ delay={80}>
          <h2 className="h2-display">De primera reunión a deploy en 4 semanas.</h2>
        </FadeUpServ>
      </div>
      <div className="timeline">
        <div className="timeline-line"/>
        {d.process.map((s, i) => (
          <FadeUpServ key={i} delay={i * 100}>
            <div className="timeline-step">
              <div className="timeline-dot"><span className="timeline-dot-inner"/></div>
              <div className="timeline-num mono">{s.w}</div>
              <h4 className="timeline-title">{s.title}</h4>
              <p className="timeline-desc">{s.body}</p>
            </div>
          </FadeUpServ>
        ))}
      </div>
    </div>
  </section>
  );
};

/* ---------- Final CTA ---------- */
const ServCTA = () => (
  <section className="section serv-cta-section" data-screen-label="06 CTA">
    <div className="section-glow violet" data-parallax="0.15"
         style={{ top: '0%', left: '50%', transform: 'translateX(-50%)' }}/>
    <div className="container">
      <div className="serv-cta-inner">
        <FadeUpServ>
          <span className="eyebrow-mono eyebrow-violet">¿Empezamos?</span>
        </FadeUpServ>
        <FadeUpServ delay={80}>
          <h2 className="h2-display">Hablemos sin compromiso.</h2>
        </FadeUpServ>
        <FadeUpServ delay={160}>
          <p className="body-lead">
            30 minutos para entender tu proyecto, tu objetivo y darte una propuesta concreta. Sin presentaciones genéricas.
          </p>
        </FadeUpServ>
        <FadeUpServ delay={240}>
          <div className="serv-cta-buttons">
            <a href="../index.html#contacto" className="btn-primary btn-warm-shimmer">
              Agendar reunión <Icons.ArrowRight size={15}/>
            </a>
            <a href="../index.html#soluciones" className="btn-glass">
              Ver otras soluciones
            </a>
          </div>
        </FadeUpServ>
      </div>
    </div>
  </section>
);

/* ---------- Footer ---------- */
const ServFooter = () => {
  const [emailValue, setEmailValue] = useStateServ('');
  const [newsletterStatus, setNewsletterStatus] = useStateServ('idle');

  const currentYear = new Date().getFullYear();
  const prefix = '../';

  return (
    <footer className="footer-section">
      <div className="container">
        <div className="footer-top">
          <div className="footer-brand-block">
            <a href={prefix + 'index.html'} className="footer-brand-logo">
              <LogoServ size={32}/>
            </a>
            <p className="footer-tagline">
              Operaciones que piensan solas. Automatización con IA para Empresas.
            </p>
            <div className="footer-socials">
              <span className="footer-socials-label">Pronto en:</span>
              <div className="footer-socials-icons">
                <span className="footer-social-placeholder" title="LinkedIn (próximamente)" aria-label="LinkedIn próximamente">
                  <Icons.Linkedin size={16}/>
                </span>
                <span className="footer-social-placeholder" title="Twitter/X (próximamente)" aria-label="Twitter próximamente">
                  <Icons.Twitter size={16}/>
                </span>
                <span className="footer-social-placeholder" title="GitHub (próximamente)" aria-label="GitHub próximamente">
                  <Icons.Github size={16}/>
                </span>
              </div>
            </div>
          </div>
        </div>

        <div className="footer-columns">
          <div className="footer-col">
            <h4 className="footer-col-title">Soluciones</h4>
            <ul className="footer-col-list">
              <li><a href={prefix + 'soluciones/facturacion.html'}>Facturación y cobranzas</a></li>
              <li><a href={prefix + 'soluciones/pedidos.html'}>Operaciones de ecommerce</a></li>
              <li><a href={prefix + 'soluciones/clientes.html'}>Atención al cliente</a></li>
              <li><a href={prefix + 'soluciones/reportes.html'}>Reportes y dashboards</a></li>
            </ul>
          </div>
          <div className="footer-col">
            <h4 className="footer-col-title">Servicios</h4>
            <ul className="footer-col-list">
              <li><a href={prefix + 'servicios/pagina-web.html'}>Página Web a medida</a></li>
              <li><a href={prefix + 'servicios/inteligencia-artificial.html'}>Inteligencia Artificial</a></li>
            </ul>
          </div>
          <div className="footer-col">
            <h4 className="footer-col-title">Empresa</h4>
            <ul className="footer-col-list">
              <li><a href={prefix + 'empresa/sobre-nosotros.html'}>Sobre nosotros</a></li>
              <li><a href={prefix + 'index.html#confiaron'}>Casos</a></li>
              <li><a href={prefix + 'index.html#proceso'}>Proceso</a></li>
              <li><a href={prefix + 'index.html#diagnostico'}>Diagnóstico gratis</a></li>
            </ul>
          </div>
          <div className="footer-col">
            <h4 className="footer-col-title">Contacto</h4>
            <ul className="footer-col-list">
              <li>
                <a
                  href="https://wa.me/5491131924144"
                  target="_blank"
                  rel="noopener noreferrer"
                  className="footer-contact-link"
                >
                  <Icons.MessageCircle size={14}/>
                  WhatsApp +54 9 11 3192-4144
                </a>
              </li>
              <li><a href="mailto:contacto@geishia.com">contacto@geishia.com</a></li>
              <li><a href={prefix + 'index.html#contacto'}>Formulario de contacto</a></li>
              <li className="footer-meta-item">Buenos Aires, Argentina</li>
              <li className="footer-meta-item">Lun a Vie 9:00 — 19:00 (ART)</li>
            </ul>
          </div>
        </div>

        <div className="footer-bottom">
          <div className="footer-copyright">
            © {currentYear} Geishia. Todos los derechos reservados.
          </div>
          <div className="footer-legal-links">
            <a href={prefix + 'legal/privacidad.html'}>Política de Privacidad</a>
            <span className="footer-sep">·</span>
            <a href={prefix + 'legal/terminos.html'}>Términos y Condiciones</a>
          </div>
          
        </div>
      </div>
    </footer>
  );
};

/* ---------- WhatsApp Floating Button ---------- */
const WhatsAppFloatServ = () => (
  <a
    href="https://wa.me/5491131924144"
    target="_blank"
    rel="noopener noreferrer"
    className="whatsapp-float"
    aria-label="Chatear por WhatsApp"
    title="Chatear por WhatsApp"
  >
    <Icons.WhatsApp size={26}/>
  </a>
);

/* ---------- Page composition ---------- */
const ServicioPage = ({ data }) => (
  <>
    <NavbarServ currentService={data.key}/>
    <ServHero d={data}/>
    <ServProblems d={data}/>
    <ServProposals d={data}/>
    <ServDeliverables d={data}/>
    <ServProcess d={data}/>
    <ServCTA/>
    <ServFooter/>
    <WhatsAppFloatServ/>
  </>
);

/* ---------- Global parallax ---------- */
function useGlobalParallaxServ() {
  useEffectServ(() => {
    const reduced = window.matchMedia('(prefers-reduced-motion: reduce)').matches;
    if (reduced) return;
    let raf = 0;
    function onScroll() {
      if (raf) return;
      raf = requestAnimationFrame(() => {
        const items = document.querySelectorAll('[data-parallax]');
        const y = window.scrollY;
        items.forEach(el => {
          const speed = parseFloat(el.dataset.parallax) || 0.3;
          const base = el.dataset.parallaxBase || '';
          el.style.transform = `${base} translate3d(0, ${y * speed}px, 0)`;
        });
        raf = 0;
      });
    }
    window.addEventListener('scroll', onScroll, { passive: true });
    onScroll();
    return () => window.removeEventListener('scroll', onScroll);
  }, []);
}

window.ServicioPage = ServicioPage;
window.useGlobalParallaxServ = useGlobalParallaxServ;
