/* SolucionPage — shared component rendering one solution-category page from data. */
const { useEffect: useEffectSP, useRef: useRefSP, useState: useStateSP } = React;

/* ---------- Logo (same as home) ---------- */
const LogoSP = ({ 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 (mega-menu, sub-page) ---------- */
const NavbarSol = ({ currentKey }) => {
  const ctx = window.useMegaMenuMM();
  return (
    <nav className="nav-fixed" ref={ctx.wrapRef}>
      <a href="../index.html" aria-label="Geishia"><LogoSP 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="../"
          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 copy — BlurText.jsx defines it but we want to be explicit) ---------- */
const FadeUpSP = window.FadeUp || (({ children, delay = 0, className = '' }) => {
  const ref = useRefSP(null);
  const [visible, setVisible] = useStateSP(false);
  useEffectSP(() => {
    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 Breadcrumb = ({ label }) => (
  <nav className="sol-breadcrumb" aria-label="Breadcrumb">
    <a href="../index.html">Inicio</a>
    <Icons.ChevronRight size={14}/>
    <a href="../index.html#soluciones">Soluciones</a>
    <Icons.ChevronRight size={14}/>
    <span className="sol-bc-current">{label}</span>
  </nav>
);

/* ---------- Hero ---------- */
const SolHero = ({ d }) => (
  <section className="sol-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">
      <Breadcrumb label={d.label}/>
      <FadeUpSP delay={80}>
        <span className="eyebrow-mono eyebrow-violet">{d.eyebrow}</span>
      </FadeUpSP>
      <FadeUpSP delay={160}>
        <h1 className="h1-display">{d.h1}</h1>
      </FadeUpSP>
      <FadeUpSP delay={280}>
        <p className="body-lead sol-hero-sub">{d.sub}</p>
      </FadeUpSP>
      <FadeUpSP delay={400}>
        <div className="sol-hero-stats mono">{d.stats}</div>
      </FadeUpSP>
      <FadeUpSP delay={520}>
        <div className="sol-hero-ctas">
          <a href="../index.html#contacto" className="btn-primary btn-warm-shimmer">
            Agendar reunión <Icons.ArrowRight size={15}/>
          </a>
          <a href="#workflows" className="btn-glass">
            Ver workflows <Icons.ArrowDown size={15}/>
          </a>
        </div>
      </FadeUpSP>
    </div>
  </section>
);

/* ---------- Problem ---------- */
const SolProblem = ({ d }) => (
  <section className="section" data-screen-label="02 Problema">
    <div className="section-glow violet" data-parallax="0.2"
         style={{ top: '0%', left: '-200px' }}/>
    <div className="container">
      <div className="section-header">
        <FadeUpSP><span className="eyebrow-mono eyebrow-violet">El problema hoy</span></FadeUpSP>
        <FadeUpSP delay={80}>
          <h2 className="h2-display">¿Te suena alguno de estos?</h2>
        </FadeUpSP>
      </div>
      <div className="grid-3">
        {d.problems.map((it, i) => {
          const I = iconFromName(it.icon);
          return (
            <FadeUpSP key={i} delay={i * 100}>
              <article className="dolor-card liquid-glass">
                <div className="dolor-icon-wrap"><I size={24}/></div>
                <h4 className="dolor-title">{it.title}</h4>
                <p className="dolor-body">{it.body}</p>
              </article>
            </FadeUpSP>
          );
        })}
      </div>
    </div>
  </section>
);

/* ---------- Workflows ---------- */
const SolWorkflows = ({ d }) => (
  <section id="workflows" className="section" data-screen-label="03 Workflows">
    <div className="section-glow violet" data-parallax="0.18"
         style={{ top: '10%', right: '-200px' }}/>
    <div className="container">
      <div className="section-header">
        <FadeUpSP><span className="eyebrow-mono eyebrow-violet">Workflows de esta categoría</span></FadeUpSP>
        <FadeUpSP delay={80}>
          <h2 className="h2-display">Tres automatizaciones que resuelven el 80% del trabajo repetitivo.</h2>
        </FadeUpSP>
      </div>
      <div className="sol-workflows-list">
        {d.workflows.map((w, i) => (
          <FadeUpSP key={w.id} delay={i * 80}>
            <WorkflowDetailCard w={w}/>
          </FadeUpSP>
        ))}
      </div>
    </div>
  </section>
);

const WorkflowDetailCard = ({ w }) => (
  <article id={w.id} className="sol-workflow-card liquid-glass">
    <div className="sol-workflow-header">
      <div className="sol-workflow-id mono">#{w.id}</div>
      <h3 className="sol-workflow-title">{w.title}</h3>
    </div>
    <p className="sol-workflow-desc">{w.desc}</p>
    <ul className="sol-workflow-bullets">
      {w.bullets.map((b, i) => (
        <li key={i}>
          <Icons.Check size={16}/>
          <span>{b}</span>
        </li>
      ))}
    </ul>
    <div className="sol-workflow-stack">
      {w.stack.map((s, i) => (
        <span key={i} className="int-chip">{s}</span>
      ))}
    </div>
  </article>
);

/* ---------- Stack técnico ---------- */
const SolStack = ({ d }) => (
  <section className="section" data-screen-label="04 Stack">
    <div className="container">
      <div className="section-header">
        <FadeUpSP><span className="eyebrow-mono eyebrow-violet">Stack técnico</span></FadeUpSP>
        <FadeUpSP delay={80}>
          <h2 className="h2-display">Las herramientas que operamos en esta categoría.</h2>
        </FadeUpSP>
      </div>
      <div className="grid-4">
        {d.stack.map((s, i) => {
          const Icon = iconFromName(s.icon);
          return (
            <FadeUpSP key={i} delay={i * 80}>
              <article className="diff-card liquid-glass">
                <div className="diff-icon-pill liquid-glass-strong"><Icon size={20}/></div>
                <h4 className="diff-title">{s.title}</h4>
                <p className="diff-body">{s.desc}</p>
              </article>
            </FadeUpSP>
          );
        })}
      </div>
    </div>
  </section>
);

/* ---------- Timeline (4 weeks) ---------- */
const SolTimeline = ({ d }) => (
  <section className="section" data-screen-label="05 Proceso">
    <div className="container">
      <div className="section-header">
        <FadeUpSP><span className="eyebrow-mono eyebrow-violet">Proceso</span></FadeUpSP>
        <FadeUpSP delay={80}>
          <h2 className="h2-display">De diagnóstico a producción en 4 semanas.</h2>
        </FadeUpSP>
      </div>
      <div className="timeline">
        <div className="timeline-line"/>
        {d.timeline.map((s, i) => (
          <FadeUpSP 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>
          </FadeUpSP>
        ))}
      </div>
    </div>
  </section>
);

/* ---------- Case study ---------- */
const SolCaseStudy = ({ d }) => (
  <section className="section" data-screen-label="06 Caso típico">
    <div className="container">
      <div className="section-header">
        <FadeUpSP><span className="eyebrow-mono eyebrow-violet">Caso típico</span></FadeUpSP>
        <FadeUpSP delay={80}>
          <h2 className="h2-display">{d.caseStudy.profile}</h2>
        </FadeUpSP>
        <FadeUpSP delay={160}>
          <p className="body-lead sol-case-disclaimer">{d.caseStudy.disclaimer}</p>
        </FadeUpSP>
      </div>
      <div className="sol-case-grid">
        {d.caseStudy.cols.map((c, i) => {
          const cls = c.label.toLowerCase()
            .normalize('NFD').replace(/[\u0300-\u036f]/g, '');
          return (
            <FadeUpSP key={i} delay={i * 100}>
              <article className={`sol-case-col sol-case-${cls}`}>
                <span className="eyebrow-mono">{c.label}</span>
                <p>{c.body}</p>
              </article>
            </FadeUpSP>
          );
        })}
      </div>
    </div>
  </section>
);

/* ---------- Related solutions ---------- */
const SolRelated = ({ d, currentKey }) => {
  const all = window.SOLUCIONES_DATA;
  const others = (d.related || []).filter(k => k !== currentKey).map(k => all[k]).filter(Boolean);
  return (
    <section className="section" data-screen-label="07 Otras soluciones">
      <div className="container">
        <div className="section-header">
          <FadeUpSP><span className="eyebrow-mono eyebrow-violet">Otras soluciones</span></FadeUpSP>
          <FadeUpSP delay={80}>
            <h2 className="h2-display">Otras categorías que resolvemos.</h2>
          </FadeUpSP>
        </div>
        <div className="sol-related-grid">
          {others.map((o, i) => {
            const Icon = iconFromName(o.icon);
            return (
              <FadeUpSP key={o.key} delay={i * 80}>
                <a href={`./${o.key}.html`} className="sol-related-card">
                  <div className="sol-related-icon"><Icon size={20}/></div>
                  <h4 className="sol-related-title">{o.label}</h4>
                  <p className="sol-related-sub">{o.sub.split('.')[0] + '.'}</p>
                  <Icons.ArrowUpRight size={18} className="sol-related-arrow"/>
                </a>
              </FadeUpSP>
            );
          })}
        </div>
      </div>
    </section>
  );
};

/* ---------- Final CTA ---------- */
const SolCTA = ({ d }) => (
  <section className="section sol-cta-section" data-screen-label="08 CTA">
    <div className="section-glow violet" data-parallax="0.15"
         style={{ top: '0%', left: '50%', transform: 'translateX(-50%)' }}/>
    <div className="container">
      <FadeUpSP>
        <div className="sol-cta-card liquid-glass">
          <span className="eyebrow-mono eyebrow-violet">¿Empezamos?</span>
          <h2 className="h2-display">Diagnóstico gratis sobre tu proceso de {d.category}.</h2>
          <p className="body-lead">
            30 minutos. Mapeamos lo automatizable, priorizamos por ROI y te decimos qué workflow construir primero.
          </p>
          <div className="sol-cta-actions">
            <a href="../index.html#contacto" className="btn-primary btn-warm-shimmer">
              Agendar reunión <Icons.ArrowRight size={15}/>
            </a>
            <a href="../index.html#diagnostico" className="btn-glass">
              Hacer el diagnóstico online <Icons.ArrowRight size={15}/>
            </a>
          </div>
        </div>
      </FadeUpSP>
    </div>
  </section>
);

/* ---------- Footer ---------- */
const SolFooter = () => {
  const [emailValue, setEmailValue] = useStateSP('');
  const [newsletterStatus, setNewsletterStatus] = useStateSP('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">
              <LogoSP 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 WhatsAppFloatSP = () => (
  <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 SolucionPage = ({ data }) => (
  <>
    <NavbarSol currentKey={data.key}/>
    <SolHero d={data}/>
    <SolProblem d={data}/>
    <SolWorkflows d={data}/>
    <SolStack d={data}/>
    <SolTimeline d={data}/>
    <SolCaseStudy d={data}/>
    <SolRelated d={data} currentKey={data.key}/>
    <SolCTA d={data}/>
    <SolFooter/>
    <WhatsAppFloatSP/>
  </>
);

/* ---------- Global parallax (same as home App.jsx) ---------- */
function useGlobalParallaxSP() {
  useEffectSP(() => {
    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.SolucionPage = SolucionPage;
window.useGlobalParallaxSP = useGlobalParallaxSP;
