/* eslint-disable */
/* global React, ReactDOM, useLang, LangProvider, HeroNav, Footer, useJsonLd */
/* rentabilidad.jsx — landing "Producto" para /rentabilidad (redesign
   2026-09). Textos definitivos del handoff: no reescribir. Página en
   español únicamente (sin toggle EN) — mismo criterio que cierre-mensual.jsx
   y las páginas de industria. Reusa product.css/hero-nav.css tal cual
   quedaron después del pase de consistencia con la home — no redeclarar
   nada de nav/botones/cards/animación acá. */

const DIMENSION_CARDS = [
  { icon: 'ph-package', title: 'Por producto / SKU', body: 'Costos directos + costos indirectos asignados + precio real (con descuentos) = margen contribución por unidad. Ordenable por volumen, por margen, por combinación.' },
  { icon: 'ph-users-three', title: 'Por cliente', body: 'Cost-to-serve incluido: descuentos, plazo de pago, devoluciones, retrabajos. Un cliente grande que paga a 90 días con 20% de descuento puede ser menos rentable que uno chico.' },
  { icon: 'ph-storefront', title: 'Por canal', body: 'Distribuidor mayorista, retail propio, e-commerce, B2B directo. Cada canal con su estructura de costos y su comportamiento de precio. Comparados, no sumados.' },
];

const HOW_CHECKLIST = [
  'Análisis por SKU, cliente y canal — combinables',
  'Cost-to-serve incluido (descuentos, plazo, devoluciones)',
  'Comparativo temporal: mes vs mes anterior vs mismo mes año anterior',
  'Drill-down desde el agregado hasta la línea del ERP',
  'Alertas sobre cambios de margen mayores al umbral que definís',
];

const FAQ_ITEMS = [
  { q: '¿Necesito tener el costo por SKU cargado en el ERP?', a: 'Ayuda, pero no es requisito. Si el costo vive en planillas o en un sistema de costos aparte, <b>Teramot lo lee de ahí</b> y lo cruza con el volumen y el precio del ERP.' },
  { q: '¿Cómo maneja los costos indirectos?', a: 'Con <b>reglas de asignación que definís una vez</b>: por volumen, por facturación, por horas o por el driver que uses. Cada margen muestra qué regla lo afectó.' },
  { q: '¿Funciona para empresas de servicios?', a: 'Sí. En lugar de SKU, la dimensión es <b>proyecto, contrato o servicio</b>, con horas y costos directos asignados.' },
  { q: '¿Puedo ver rentabilidad por vendedor o por sucursal?', a: 'Sí. Cualquier dimensión que exista en tu ERP se puede usar como eje de análisis, sola o combinada con producto, cliente y canal.' },
];

const { useState: useStateRent, useEffect: useEffectRent, useRef: useRefRent } = React;

/* Scroll reveal — mismo hook que cierre-mensual.jsx/home.jsx/agro.jsx. */
const useScrollReveal = (rootRef) => {
  useEffectRent(() => {
    if (window.matchMedia('(prefers-reduced-motion: reduce)').matches) return;
    const root = rootRef.current;
    if (!root) return;
    const groups = [];
    root.querySelectorAll('section, footer').forEach((sec) => {
      const wrap = sec.firstElementChild && sec.children.length === 1 ? sec.firstElementChild : sec;
      const kids = Array.from(wrap.children).filter((el) => (
        el.nodeType === 1 && !el.classList.contains('tm-drawer') && !el.classList.contains('tm-drawer-overlay')
      ));
      if (kids.length) groups.push(kids);
    });
    const io = new IntersectionObserver((entries) => {
      entries.forEach((en) => {
        if (en.isIntersecting) {
          en.target.classList.add('rv-in');
          io.unobserve(en.target);
        }
      });
    }, { rootMargin: '0px 0px -8% 0px', threshold: 0.08 });
    groups.forEach((kids) => kids.forEach((el, i) => {
      el.classList.add('rv');
      el.style.transitionDelay = Math.min(i, 4) * 70 + 'ms';
      io.observe(el);
    }));
    return () => io.disconnect();
  }, []);
};

const RentabilidadHero = () => {
  const { c } = useLang();
  return (
    <section className="tm-hero-gradient">
      <HeroNav current="rentabilidad" />
      <div className="tm-prod-hero-grid">
        <div className="tm-prod-hero-copy">
          <p className="tm-prod-hero-eyebrow">Cost-to-serve incluido · Trazabilidad completa</p>
          <h1>Análisis de rentabilidad por producto, cliente y canal — <span>al instante</span>, con IA.</h1>
          <p className="tm-prod-hero-sub">Margen real por SKU, cliente y canal sobre tu ERP. Cruzá costos, precios y volumen sin armar la planilla a mano. Cada número, con su fórmula y su fuente.</p>
          <div className="tm-prod-hero-actions">
            <a href={c.links.call} target="_blank" rel="noopener noreferrer" className="tm-hero-btn tm-hero-btn-lg tm-hero-btn-white">Pedí tu demo <i className="ph ph-arrow-right" /></a>
            <a href={c.links.app} className="tm-hero-btn tm-hero-btn-lg tm-hero-btn-ghost-light"><i className="ph ph-play-circle" style={{ fontSize: 21 }} /> Comenzá Gratis</a>
          </div>
        </div>
        <div className="tm-prod-hero-art">
          <div className="tm-prod-hero-art-glow" />
          <div className="tm-prod-hero-mockup" style={{ position: 'relative', zIndex: 1, width: '100%', background: 'rgba(255,255,255,.96)', border: '1px solid rgba(255,255,255,.55)', borderRadius: 16, padding: 18, boxShadow: '0 2px 4px rgba(11,15,20,.05), 0 1px 2px rgba(11,15,20,.03)' }} role="img" aria-label="Panel de análisis de rentabilidad en Teramot">
            <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: 12 }}>
              <span style={{ display: 'inline-flex', alignItems: 'center', gap: 7, padding: '6px 12px', borderRadius: 9999, background: '#253DE5', color: '#fff', fontSize: 11, fontWeight: 600, whiteSpace: 'nowrap' }}><i className="ph-bold ph-chart-pie-slice" style={{ fontSize: 12 }} /> Rentabilidad</span>
              <span style={{ fontSize: 10.5, fontWeight: 600, letterSpacing: '.12em', textTransform: 'uppercase', color: '#6B7280' }}>Marzo 2026</span>
            </div>
            <div style={{ marginTop: 16, borderRadius: 10, background: '#fff', border: '1px solid #EEF0F4', overflow: 'hidden' }}>
              {[
                { icon: 'ph-package', label: 'Costos directos por SKU', status: 'Mapeados' },
                { icon: 'ph-sliders-horizontal', label: 'Reglas de asignación', status: 'Aplicadas' },
                { icon: 'ph-truck', label: 'Cost-to-serve', status: 'Incluido', neutral: true },
                { icon: 'ph-storefront', label: 'Margen por cliente y canal', status: 'Calculado' },
              ].map((row, i, arr) => (
                <div key={row.label} style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: 14, padding: '14px 16px', borderBottom: i < arr.length - 1 ? '1px solid rgba(11,15,20,.05)' : 'none' }}>
                  <div style={{ display: 'flex', alignItems: 'center', gap: 10, minWidth: 0 }}><i className={`ph ${row.icon}`} style={{ fontSize: 15, color: '#253DE5', flex: 'none' }} /><span style={{ fontSize: 13.5, fontWeight: 500, letterSpacing: '-.005em', color: '#0B0F14' }}>{row.label}</span></div>
                  {row.neutral ? (
                    <span style={{ flex: 'none', whiteSpace: 'nowrap', padding: '4px 10px', borderRadius: 9999, border: '1px solid #E5E7EB', background: '#fff', fontSize: 10.5, fontWeight: 600, color: '#4B5563' }}>{row.status}</span>
                  ) : (
                    <span style={{ flex: 'none', whiteSpace: 'nowrap', display: 'inline-flex', alignItems: 'center', gap: 5, padding: '4px 10px', borderRadius: 9999, background: 'rgba(123,193,173,.22)', fontSize: 10.5, fontWeight: 600, color: '#2F6B58' }}><i className="ph-bold ph-check" style={{ fontSize: 11 }} /> {row.status}</span>
                  )}
                </div>
              ))}
            </div>
            <div style={{ display: 'flex', alignItems: 'flex-end', minHeight: 80, padding: '18px 100px 0 4px' }}>
              <p style={{ fontSize: 11.5, fontWeight: 500, lineHeight: 1.45, color: '#4B5563' }}>Cada margen abre su regla de asignación</p>
            </div>
          </div>
          <div style={{ position: 'absolute', right: -16, bottom: -24, zIndex: 2, width: 172, background: '#fff', border: '1px solid #E5E7EB', borderRadius: 11, boxShadow: '0 2px 4px rgba(11,15,20,.06), 0 1px 2px rgba(11,15,20,.04)', padding: '12px 13px' }}>
            <p style={{ fontSize: 8.5, fontWeight: 600, letterSpacing: '.14em', textTransform: 'uppercase', color: '#9CA3AF' }}>Margen · Marzo</p>
            <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginTop: 9 }}>
              <span style={{ flex: 'none', width: 22, height: 22, borderRadius: 9999, background: '#263185', display: 'flex', alignItems: 'center', justifyContent: 'center' }}><i className="ph-bold ph-check" style={{ color: '#91DFC8', fontSize: 11 }} /></span>
              <span style={{ fontSize: 12.5, fontWeight: 600, letterSpacing: '-.01em', color: '#0B0F14' }}>Margen por SKU</span>
            </div>
            <div style={{ display: 'flex', alignItems: 'center', gap: 6, marginTop: 9, paddingTop: 9, borderTop: '1px solid #EEF0F4' }}>
              <i className="ph ph-git-commit" style={{ color: '#253DE5', fontSize: 12, flex: 'none' }} />
              <span style={{ fontSize: 10, fontWeight: 500, lineHeight: 1.35, color: '#4B5563' }}>Cost-to-serve incluido</span>
            </div>
          </div>
        </div>
      </div>
    </section>
  );
};

const ProblemaSection = () => (
  <section className="tm-prod-section tm-prod-section-paper">
    <div className="tm-container">
      <div className="tm-prod-head" style={{ maxWidth: 900 }}>
        <h2>El margen que reportás no es el margen que tenés</h2>
        <p>El P&amp;L consolidado te dice si la empresa gana plata. Pero no te dice qué SKU está perdiendo, qué cliente está siendo subsidiado por el resto, o qué canal está creciendo a costo de rentabilidad. Esas preguntas requieren cruzar tres dimensiones — y en la mayoría de los equipos se resuelven una vez cada seis meses, con un reporte hecho a mano que ya no refleja el mes actual.</p>
      </div>
    </div>
  </section>
);

const DimensionesSection = () => (
  <section className="tm-prod-section tm-prod-section-white">
    <div className="tm-container">
      <div className="tm-prod-head">
        <h2>Rentabilidad, en las tres dimensiones que importan</h2>
      </div>
      <div className="tm-prod-cards">
        {DIMENSION_CARDS.map((card) => (
          <article className="tm-prod-card" key={card.title}>
            <div className="tm-prod-card-icon"><i className={`ph ${card.icon}`} /></div>
            <h3>{card.title}</h3>
            <p>{card.body}</p>
          </article>
        ))}
      </div>
    </div>
  </section>
);

const ComoFuncionaSection = () => (
  <section className="tm-prod-section tm-prod-section-wash">
    <div className="tm-container">
      <h2 style={{ maxWidth: 820, margin: '0 auto 48px', textAlign: 'center', fontSize: 'clamp(26px,2.6vw,34px)', lineHeight: 1.18, fontWeight: 600, letterSpacing: '-.035em', color: '#1C2536', textWrap: 'pretty' }}>No más planillas de asignación</h2>
      <div className="tm-prod-split">
        <div style={{ borderRadius: 12, overflow: 'hidden', background: '#fff', border: '1px solid rgba(11,15,20,.06)', boxShadow: '0 2px 4px rgba(11,15,20,.05), 0 1px 2px rgba(11,15,20,.03)' }}>
          <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: 12, padding: '13px 18px', borderBottom: '1px solid #EEF0F4', background: '#FCFCFE' }}>
            <p style={{ fontSize: 10, fontWeight: 600, letterSpacing: '.14em', textTransform: 'uppercase', color: '#9CA3AF' }}>Margen · Marzo</p>
            <span style={{ display: 'inline-flex', alignItems: 'center', gap: 6, padding: '4px 10px', borderRadius: 9999, background: 'rgba(123,193,173,.18)', fontSize: 10.5, fontWeight: 600, color: '#2F6B58' }}><i className="ph-bold ph-check-circle" style={{ fontSize: 12 }} /> Trazable</span>
          </div>
          <div style={{ display: 'grid', gap: 6, padding: '16px 18px' }}>
            <div style={{ border: '1px solid #EEF0F4', borderRadius: 10, padding: '13px 14px' }}>
              <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
                <i className="ph ph-plugs-connected" style={{ fontSize: 14, color: '#253DE5' }} />
                <span style={{ fontSize: 12, fontWeight: 600, letterSpacing: '-.01em', color: '#0B0F14' }}>Datos que cruza</span>
              </div>
              <div style={{ display: 'flex', flexWrap: 'wrap', gap: 8, marginTop: 11 }}>
                {['Costos directos', 'Volumen y precio', 'Descuentos'].map((t) => (
                  <span key={t} style={{ display: 'inline-flex', alignItems: 'center', gap: 6, padding: '5px 10px', borderRadius: 9999, border: '1px solid #E5E7EB', fontSize: 11, fontWeight: 500, color: '#374151' }}><span style={{ width: 6, height: 6, borderRadius: 9999, background: '#7BC1AD' }} /> {t}</span>
                ))}
              </div>
            </div>
            <div style={{ display: 'flex', justifyContent: 'center', color: '#9CA3AF' }}><i className="ph ph-arrow-down" style={{ fontSize: 14 }} /></div>
            <div style={{ border: '1px solid #EEF0F4', borderRadius: 10, padding: '13px 14px' }}>
              <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: 10 }}>
                <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
                  <i className="ph ph-sliders-horizontal" style={{ fontSize: 14, color: '#253DE5' }} />
                  <span style={{ fontSize: 12, fontWeight: 600, letterSpacing: '-.01em', color: '#0B0F14' }}>Reglas de asignación</span>
                </div>
                <span style={{ fontSize: 9.5, fontWeight: 600, letterSpacing: '.1em', textTransform: 'uppercase', color: '#253DE5' }}>Definidas</span>
              </div>
              <div style={{ display: 'grid', gap: 7, marginTop: 11 }}>
                {['Indirectos por volumen', 'Logística por canal', 'Retrabajos por cliente'].map((t) => (
                  <div key={t} style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: 10, padding: '7px 10px', borderRadius: 7, background: '#F7F8FD' }}>
                    <span style={{ fontSize: 11, fontWeight: 500, color: '#374151' }}>{t}</span>
                    <span style={{ fontSize: 10, color: '#6B7280' }}>aplicada</span>
                  </div>
                ))}
              </div>
            </div>
            <div style={{ display: 'flex', justifyContent: 'center', color: '#9CA3AF' }}><i className="ph ph-arrow-down" style={{ fontSize: 14 }} /></div>
            <div style={{ border: '1px solid rgba(37,61,229,.18)', borderRadius: 10, padding: '13px 14px', background: '#F7F8FD' }}>
              <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
                <i className="ph ph-table" style={{ fontSize: 14, color: '#253DE5' }} />
                <span style={{ fontSize: 12, fontWeight: 600, letterSpacing: '-.01em', color: '#0B0F14' }}>Margen real</span>
              </div>
              <div style={{ display: 'grid', gap: 1, marginTop: 11, borderRadius: 7, overflow: 'hidden', border: '1px solid #E5E7EB', background: '#E5E7EB' }}>
                {[['Por SKU', false], ['Por cliente', false], ['Por canal', true]].map(([label, bold]) => (
                  <div key={label} style={{ display: 'grid', gridTemplateColumns: '1fr auto auto', gap: 14, padding: '8px 11px', background: '#fff' }}>
                    <span style={{ fontSize: 11, fontWeight: bold ? 600 : 500, color: bold ? '#0B0F14' : '#4B5563' }}>{label}</span>
                    <span style={{ fontSize: 11, fontWeight: bold ? 600 : 400, color: '#0B0F14' }}>—</span>
                    <i className="ph ph-git-commit" style={{ fontSize: 12, color: '#253DE5' }} />
                  </div>
                ))}
              </div>
              <p style={{ marginTop: 10, fontSize: 10.5, fontWeight: 500, color: '#6B7280' }}>Cada margen abre su fórmula y su fuente</p>
            </div>
          </div>
        </div>
        <div className="tm-prod-split-copy">
          <p>La IA multi-agente lee tu ERP, mapea los costos directos por SKU, aplica las reglas de asignación de costos indirectos que definiste una vez, y calcula el margen real. Cada línea del análisis viene con su fórmula: bajás del margen agregado al SKU, del SKU al cliente, del cliente al canal, y del canal a la línea del ERP.</p>
          <div className="tm-prod-checklist">
            {HOW_CHECKLIST.map((t) => (
              <div className="tm-prod-checklist-item" key={t}><i className="ph-bold ph-check" />{t}</div>
            ))}
          </div>
        </div>
      </div>
    </div>
  </section>
);

const FaqSection = () => {
  useJsonLd({
    '@context': 'https://schema.org',
    '@type': 'FAQPage',
    mainEntity: FAQ_ITEMS.map((item) => ({
      '@type': 'Question',
      name: item.q,
      acceptedAnswer: { '@type': 'Answer', text: item.a.replace(/<\/?b>/g, '') },
    })),
  });
  return (
    <section className="tm-prod-section tm-prod-section-white">
      <div className="tm-container">
        <div className="tm-prod-faq-grid">
          <aside className="tm-prod-faq-aside">
            <span className="tm-prod-faq-eyebrow"><span className="tm-prod-faq-eyebrow-dot" /> Preguntas frecuentes</span>
            <h2>Preguntas frecuentes sobre <span>análisis de rentabilidad</span></h2>
          </aside>
          <div className="tm-prod-faq-list">
            {FAQ_ITEMS.map((item, i) => (
              <details className="tm-prod-faq-item" key={item.q} open={i === 0 ? true : undefined}>
                <summary>
                  <span className="tm-prod-faq-q">{item.q}</span>
                  <span className="tm-prod-faq-icon"><i className="ph-bold ph-plus" /></span>
                </summary>
                <p className="tm-prod-faq-a" dangerouslySetInnerHTML={{ __html: item.a }} />
              </details>
            ))}
          </div>
        </div>
      </div>
    </section>
  );
};

const CtaFinalSection = () => {
  const { c } = useLang();
  return (
    <section id="demo" className="tm-prod-cta">
      <div className="tm-prod-cta-inner">
        <p className="tm-prod-cta-kicker">Empezá ahora</p>
        <h2>Empezá a ver tu margen real</h2>
        <p className="tm-prod-cta-sub">Agendá 30 minutos y te mostramos Teramot sobre tu propio caso, no un demo genérico.</p>
        <div className="tm-prod-cta-actions">
          <a href={c.links.call} target="_blank" rel="noopener noreferrer" className="tm-btn tm-btn-lg" style={{ background: '#fff', color: '#253DE5', borderColor: 'transparent', borderRadius: 9999, fontWeight: 600 }}>Pedí tu demo</a>
          <a href={c.links.app} className="tm-btn tm-btn-lg" style={{ background: 'transparent', color: '#fff', border: '1px solid rgba(255,255,255,.5)', borderRadius: 9999, fontWeight: 600 }}>Comenzá Gratis</a>
        </div>
        <p className="tm-prod-cta-fine">Sin proyecto de IT · Setup en semanas, no meses · Tus planillas siguen funcionando</p>
      </div>
    </section>
  );
};

const RentabilidadApp = () => {
  const rootRef = useRefRent(null);
  useScrollReveal(rootRef);
  return (
    <main ref={rootRef} className="tm-prod">
      <RentabilidadHero />
      <ProblemaSection />
      <DimensionesSection />
      <ComoFuncionaSection />
      <FaqSection />
      <CtaFinalSection />
      <Footer />
    </main>
  );
};

const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
  <LangProvider defaultLang="es">
    <RentabilidadApp />
  </LangProvider>
);
