/* PRODUCTOS SAAS — página principal */
const { useState: useStateP } = React;
const { list: products, compareRows, benefitsGeneral, faqGeneral } = window.MartzProducts;

const getProductDetail = (slug) => window.MartzProducts.details && window.MartzProducts.details[slug];

const getPlanSummary = (p) => {
  const detail = getProductDetail(p.slug);
  const plans = (detail && detail.plans) || [];
  const starter = plans[0];
  const featured = plans.find(plan => plan.featured) || starter;
  if (!starter) return { price: p.priceDetail || p.price, note: p.statusType === 'live' ? 'Disponible por suscripción mensual' : 'Lista de espera abierta' };
  const hasLaunchPrice = starter.price !== 'Próximamente';
  return {
    price: p.statusType === 'live' ? `${starter.name} ${starter.price}${starter.unit || ''}` : `${starter.price}${starter.unit || ''}`,
    note: p.statusType === 'live' ? 'Disponible por suscripción mensual' : hasLaunchPrice ? 'Precio estimado de lanzamiento' : 'Lista de espera abierta',
    capacity: starter.capacity,
    recommended: featured && featured.name !== starter.name ? `${featured.name} recomendado` : null,
  };
};

const getProductCtas = (p) => {
  if (p.statusType === 'live') {
    return { primary: 'Ver planes', secondary: 'Solicitar demo' };
  }
  if (p.slug === 'martz-hospitality') {
    return { primary: 'Ver planes previstos', secondary: 'Unirme a la lista' };
  }
  return { primary: 'Ver detalles', secondary: 'Unirme a la lista' };
};

const ProdHero = () => (
  <section className="page-hero">
    <div className="page-hero-bg" />
    <div className="container">
      <div className="crumb"><a href="../index.html">Inicio</a><span className="sep">/</span><span>Productos SaaS</span></div>
      <h1>Software propio que <span className="grad">opera desde el día uno</span>.</h1>
      <p className="lede">Productos SaaS desarrollados por Martz Forge para sectores específicos. Suscripción mensual, soporte incluido y actualizaciones continuas — sin proyecto de implementación de meses.</p>
    </div>
  </section>
);

const ProdBigNums = () => (
  <section style={{ padding: '0 0 64px' }}>
    <div className="container">
      <div className="big-num-grid">
        <div className="big-num"><div className="n"><span className="grad">3</span></div><div className="l">Productos en desarrollo activo</div></div>
        <div className="big-num"><div className="n"><span className="grad">$24.99</span></div><div className="l">Desde / mes · Martz POS</div></div>
        <div className="big-num"><div className="n"><span className="grad">&lt;24h</span></div><div className="l">Tiempo de respuesta soporte</div></div>
        <div className="big-num"><div className="n"><span className="grad">LATAM</span></div><div className="l">Diseñado para la región</div></div>
      </div>
    </div>
  </section>
);

const ProdIntro = () => (
  <section className="section section-soft" style={{ borderTop: '1px solid var(--border)' }}>
    <div className="container">
      <div className="section-head">
        <div className="section-eyebrow">Dos líneas de negocio</div>
        <h2 className="section-title">Servicios a medida cuando lo necesitas. Productos SaaS cuando encaja.</h2>
        <p className="section-sub">Martz Forge combina consultoría y desarrollo personalizado con productos propios por suscripción. Si tu operación encaja en un producto SaaS, empiezas en días. Si necesitas algo único, construimos a medida — o combinamos ambos.</p>
      </div>
      <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 24 }} className="sol-detail-grid">
        <div className="svc-card">
          <div className="svc-head">
            <div className="svc-icon">
              <svg width="22" height="22" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round"><rect x="3" y="3" width="18" height="18" rx="2"/><path d="M9 9h6v6H9z"/></svg>
            </div>
            <span className="svc-status"><span className="dot" /> Línea 1</span>
          </div>
          <h3>Servicios profesionales</h3>
          <p className="svc-tag">Desarrollo · Automatización · IA · Integraciones</p>
          <p className="svc-desc">Proyectos personalizados para operaciones únicas. Tu lógica, tus reglas, tu propiedad intelectual.</p>
          <a href="soluciones.html" className="svc-cta">Ver soluciones →</a>
        </div>
        <div className="svc-card featured">
          <span className="svc-pop">Nuevo</span>
          <div className="svc-head">
            <div className="svc-icon" style={{ background: 'var(--grad)', color: '#fff' }}>
              <svg width="22" height="22" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round"><path d="M12 2L2 7l10 5 10-5-10-5z"/><path d="M2 17l10 5 10-5M2 12l10 5 10-5"/></svg>
            </div>
            <span className="svc-status"><span className="dot" /> Línea 2</span>
          </div>
          <h3>Productos SaaS</h3>
          <p className="svc-tag">POS · Hospitality · Health</p>
          <p className="svc-desc">Software propio por suscripción mensual. Listo para operar, con soporte y actualizaciones incluidas.</p>
          <a href="#productos" className="svc-cta">Ver productos ↓</a>
        </div>
      </div>
    </div>
  </section>
);

const ProductCard = ({ p }) => {
  const plan = getPlanSummary(p);
  const ctas = getProductCtas(p);
  const isSoon = p.statusType === 'soon';
  return (
    <div className={`svc-card product-saas-card ${p.featured ? 'featured' : ''}`} id={p.id}>
      {p.featured && <span className="svc-pop">Disponible ahora</span>}
      <div className="svc-head">
        <div className="svc-icon" style={p.featured ? { background: 'var(--grad)', color: '#fff' } : null}>
          <svg width="22" height="22" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round">{p.icon}</svg>
        </div>
        <span className="svc-status" style={isSoon ? { background: 'rgba(6,182,212,0.1)', color: 'var(--cyan)' } : null}>
          {isSoon ? null : <span className="dot" />}
          {p.status}
        </span>
      </div>
      <h3>{p.name}</h3>
      <p className="svc-tag">{p.tag}</p>
      <p className="svc-desc">{p.desc}</p>
      <div className="product-audience">{p.audience}</div>
      <ul className="svc-list product-module-list">
        {p.modules.slice(0, 4).map(m => (
          <li key={m}>
            <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.4" strokeLinecap="round" strokeLinejoin="round"><polyline points="20 6 9 17 4 12"/></svg>
            {m}
          </li>
        ))}
        {p.modules.length > 4 && (
          <li className="product-more-modules">+ {p.modules.length - 4} módulos más</li>
        )}
      </ul>
      <div className="svc-price-box product-price-box" style={p.featured ? { background: 'rgba(34,197,94,0.06)', borderColor: 'rgba(34,197,94,0.2)' } : null}>
        <div className="lbl">{isSoon ? 'Desde' : 'Plan inicial'}</div>
        <div className={`price ${p.featured ? 'grad' : ''}`}>{plan.price}</div>
        <div className="unit">{plan.note}</div>
        {plan.capacity && <div className="note">{plan.capacity}</div>}
        {plan.recommended && <div className="product-plan-pill">{plan.recommended}</div>}
      </div>
      <div className="product-card-actions">
        <a href={p.href} className="svc-cta">{ctas.primary} →</a>
        <a href="contacto.html" className="svc-cta product-secondary-cta">{ctas.secondary} →</a>
      </div>
    </div>
  );
};

const ProdCards = () => (
  <section className="section" id="productos">
    <div className="container">
      <div className="section-head">
        <div className="section-eyebrow">Catálogo</div>
        <h2 className="section-title">Tres productos. Tres industrias. Un mismo estándar.</h2>
        <p className="section-sub">Productos estandarizados por suscripción, separados de nuestros proyectos de software personalizado.</p>
      </div>
      <div className="svc-grid">
        {products.map(p => <ProductCard key={p.id} p={p} />)}
      </div>
    </div>
  </section>
);

const ProdCompare = () => (
  <section className="section section-soft">
    <div className="container">
      <div className="section-head">
        <div className="section-eyebrow">Comparativa rápida</div>
        <h2 className="section-title">¿Producto SaaS o desarrollo a medida?</h2>
        <p className="section-sub">No compiten — se complementan. Elige según qué tan estándar es tu operación hoy.</p>
      </div>
      <div className="compare">
        <div className="compare-row">
          <div className="compare-cell compare-head">Aspecto</div>
          <div className="compare-cell compare-head us">Productos SaaS</div>
          <div className="compare-cell compare-head">Software a medida</div>
        </div>
        {compareRows.map((row, i) => (
          <div key={i} className="compare-row">
            <div className="compare-cell compare-feature">{row[0]}</div>
            <div className="compare-cell col-3">
              <svg className="c" width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.4" strokeLinecap="round" strokeLinejoin="round"><polyline points="20 6 9 17 4 12"/></svg>
              <span>{row[1]}</span>
            </div>
            <div className="compare-cell col-2">{row[2]}</div>
          </div>
        ))}
      </div>
    </div>
  </section>
);

const ProdBenefits = () => (
  <section className="section">
    <div className="container">
      <div className="section-head">
        <div className="section-eyebrow">Beneficios</div>
        <h2 className="section-title">Por qué elegir un producto Martz Forge.</h2>
      </div>
      <div className="features">
        {benefitsGeneral.map(b => (
          <div key={b.t} className="feature">
            <div className="feature-icon">
              <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round">{b.i}</svg>
            </div>
            <h4>{b.t}</h4>
            <p>{b.d}</p>
          </div>
        ))}
      </div>
    </div>
  </section>
);

const FaqItem = ({ q, a, open, onToggle }) => (
  <div style={{ borderBottom: '1px solid var(--border)', padding: '18px 0' }}>
    <button
      type="button"
      onClick={onToggle}
      style={{ width: '100%', display: 'flex', justifyContent: 'space-between', alignItems: 'center', gap: 16, background: 'none', border: 'none', cursor: 'pointer', textAlign: 'left', fontFamily: 'inherit', padding: 0 }}
    >
      <span style={{ fontSize: 15, fontWeight: 600, color: 'var(--fg)', lineHeight: 1.4 }}>{q}</span>
      <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.4" strokeLinecap="round" strokeLinejoin="round" style={{ flexShrink: 0, transform: open ? 'rotate(180deg)' : 'none', transition: 'transform 0.2s', color: 'var(--fg-muted)' }}>
        <polyline points="6 9 12 15 18 9"/>
      </svg>
    </button>
    {open && <p style={{ fontSize: 14.5, color: 'var(--fg-soft)', lineHeight: 1.6, margin: '12px 0 0', maxWidth: 680 }}>{a}</p>}
  </div>
);

const ProdFAQ = () => {
  const [open, setOpen] = useStateP(0);
  return (
    <section className="section section-soft">
      <div className="container">
        <div className="section-head">
          <div className="section-eyebrow">Preguntas frecuentes</div>
          <h2 className="section-title">Lo que nos preguntan antes de suscribirse.</h2>
        </div>
        <div style={{ maxWidth: 760, margin: '0 auto', padding: '8px 28px', borderRadius: 16, background: 'var(--bg)', border: '1px solid var(--border)' }}>
          {faqGeneral.map((f, i) => (
            <FaqItem key={i} q={f.q} a={f.a} open={open === i} onToggle={() => setOpen(open === i ? -1 : i)} />
          ))}
        </div>
      </div>
    </section>
  );
};

const ProdApp = () => (
  <>
    <SiteNav current="productos" />
    <ProdHero />
    <ProdBigNums />
    <ProdIntro />
    <ProdCards />
    <ProdCompare />
    <ProdBenefits />
    <ProdFAQ />
    <BigCTA />
    <SiteFooter />
  </>
);

ReactDOM.createRoot(document.getElementById('root')).render(<ProdApp />);
