// OKentra — Centro de Soporte. Landing dependiente pensada para soporte.okentra.com
const SOP_NAV = [
  { id: 'canales', label: 'Formas de contacto' },
  { id: 'base', label: 'Centro de ayuda' },
  { id: 'estado', label: 'Estado' },
  { id: 'sla', label: 'Niveles de servicio' },
  { id: 'faq', label: 'FAQ' },
  { id: 'ticket', label: 'Abrir ticket' },
];

// Access key de Web3Forms apuntando a soporte@inflexiumlabs.com (autoresponder para copia al remitente)
const SOP_WEB3FORMS_KEY = 'REEMPLAZAR_CON_TU_ACCESS_KEY';
const WA_LINK = 'https://wa.me/59897574400';

function SopHeader({ active, onNav, onHome }) {
  const { Button } = window.OKENTRADesignSystem_9c3390;
  const go = (e, id) => { e.preventDefault(); onNav(id); };
  return (
    <div style={{ position: 'sticky', top: 0, zIndex: 100 }}>
      <header style={{ background: 'rgba(255,255,255,0.92)', backdropFilter: 'saturate(150%) blur(10px)', WebkitBackdropFilter: 'saturate(150%) blur(10px)', borderBottom: '1px solid var(--border-subtle)' }}>
        <div style={{ maxWidth: 1240, margin: '0 auto', height: 64, display: 'flex', alignItems: 'center', gap: 22, padding: '0 28px' }}>
          <a href="#" onClick={(e) => { e.preventDefault(); onHome(); }} style={{ display: 'flex', alignItems: 'center', gap: 9 }}>
            <img src="../../assets/logos/okentra-logo.png" alt="OKentra" style={{ height: 40 }} />
            <span style={{ fontSize: 18, fontWeight: 800, color: 'var(--violet-600)', letterSpacing: '-0.01em' }}>Soporte</span>
          </a>
          <nav style={{ display: 'flex', gap: 22, marginLeft: 14 }}>
            {['Inicio', 'Soluciones', 'Servicios', 'Casos de éxito', 'Contacto'].map((l) => (
              <a key={l} href="#" onClick={(e) => { e.preventDefault(); onHome(); }} style={{ fontSize: 13.5, fontWeight: 700, color: 'var(--text-body)', textDecoration: 'none' }}>{l}</a>
            ))}
          </nav>
          <span style={{ flex: 1 }} />
          <Button variant="primary" onClick={() => onNav('ticket')}>Abrir un ticket</Button>
        </div>
      </header>
      <div style={{ background: 'var(--navy-600)', borderBottom: '1px solid rgba(255,255,255,0.08)' }}>
        <div style={{ maxWidth: 1240, margin: '0 auto', height: 46, display: 'flex', alignItems: 'center', gap: 4, padding: '0 28px', overflowX: 'auto' }}>
          <span style={{ display: 'flex', alignItems: 'center', gap: 7, fontSize: 12.5, color: 'rgba(255,255,255,0.6)', marginRight: 14, whiteSpace: 'nowrap' }}>
            <SiteIcon name="home" size={13} color="rgba(255,255,255,0.6)" /> Inicio <SiteIcon name="chevron-right" size={12} color="rgba(255,255,255,0.4)" /> <span style={{ color: 'var(--violet-300)', fontWeight: 700 }}>Soporte</span>
          </span>
          {SOP_NAV.map((l) => (
            <a key={l.id} href="#" onClick={(e) => go(e, l.id)} style={{ fontSize: 13, fontWeight: active === l.id ? 800 : 700, color: active === l.id ? '#fff' : 'rgba(255,255,255,0.7)', textDecoration: 'none', padding: '6px 10px', borderRadius: 'var(--radius-sm)', background: active === l.id ? 'rgba(255,255,255,0.12)' : 'transparent', whiteSpace: 'nowrap' }}>{l.label}</a>
          ))}
        </div>
      </div>
    </div>
  );
}

function SopHead({ eyebrow, title, sub, light }) {
  return (
    <div style={{ textAlign: 'center', maxWidth: 700, margin: '0 auto 44px' }}>
      <p style={{ fontSize: 12, fontWeight: 700, letterSpacing: '0.12em', textTransform: 'uppercase', color: light ? 'var(--violet-300)' : 'var(--violet-600)', margin: '0 0 12px' }}>{eyebrow}</p>
      <h2 style={{ margin: 0, fontSize: 36, fontWeight: 800, color: light ? '#fff' : 'var(--text-strong)', letterSpacing: '-0.02em' }}>{title}</h2>
      {sub && <p style={{ margin: '14px 0 0', fontSize: 17, color: light ? 'rgba(255,255,255,0.75)' : 'var(--text-muted)', lineHeight: 1.6 }}>{sub}</p>}
    </div>
  );
}

function SopHero({ onNav }) {
  const { Button } = window.OKENTRADesignSystem_9c3390;
  const quick = [
    { icon: 'ticket', t: 'Abrir un ticket', d: 'Registrá tu incidencia y hacé seguimiento.', action: () => onNav('ticket') },
    { icon: 'message-circle', t: 'WhatsApp', d: '+598 97 574 400', href: WA_LINK },
    { icon: 'book-open', t: 'Centro de ayuda', d: 'Guías y respuestas frecuentes.', action: () => onNav('base') },
  ];
  return (
    <section style={{ position: 'relative', overflow: 'hidden', background: 'var(--navy-600)', color: '#fff' }}>
      <div style={{ position: 'absolute', top: -160, right: -120, width: 540, height: 540, borderRadius: '50%', background: 'radial-gradient(circle, rgba(104,75,255,0.5), rgba(104,75,255,0) 68%)' }} />
      <div style={{ maxWidth: 1240, margin: '0 auto', padding: '76px 28px 40px', position: 'relative' }}>
        <div style={{ textAlign: 'center', maxWidth: 760, margin: '0 auto' }}>
          <span style={{ display: 'inline-flex', alignItems: 'center', gap: 8, fontSize: 13, fontWeight: 600, color: 'var(--violet-200)', background: 'rgba(255,255,255,0.08)', border: '1px solid rgba(255,255,255,0.16)', padding: '6px 14px', borderRadius: 999, marginBottom: 22 }}>
            <SiteIcon name="life-buoy" size={15} color="var(--violet-200)" /> Centro de Soporte OKentra
          </span>
          <h1 style={{ margin: 0, fontSize: 46, lineHeight: 1.1, fontWeight: 800, letterSpacing: '-0.03em' }}>
            ¿Cómo podemos <span style={{ color: 'var(--violet-300)' }}>ayudarte</span>?
          </h1>
          <p style={{ margin: '20px auto 0', fontSize: 17.5, lineHeight: 1.6, color: 'rgba(255,255,255,0.78)', maxWidth: 620 }}>
            Encontrá respuestas, seguí tus tickets y contactá a nuestro equipo especializado en Odoo. Soporte para todo el ecosistema OKentra — ERP, RRHH, Campus, PreObra, Pagos y Sensores.
          </p>
          <div style={{ display: 'flex', gap: 10, maxWidth: 560, margin: '28px auto 0', background: '#fff', borderRadius: 'var(--radius-lg)', padding: 8, boxShadow: 'var(--shadow-lg)' }}>
            <span style={{ display: 'flex', alignItems: 'center', paddingLeft: 12, color: 'var(--text-muted)' }}><SiteIcon name="search" size={20} color="var(--text-muted)" /></span>
            <input placeholder="Buscar en el centro de ayuda…" onKeyDown={(e) => { if (e.key === 'Enter') onNav('base'); }} style={{ flex: 1, border: 'none', outline: 'none', fontSize: 15, fontFamily: 'var(--font-sans)', color: 'var(--text-body)', background: 'transparent' }} />
            <Button variant="primary" onClick={() => onNav('base')}>Buscar</Button>
          </div>
        </div>
        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: 16, marginTop: 44 }}>
          {quick.map((q) => {
            const inner = (
              <React.Fragment>
                <div style={{ width: 46, height: 46, borderRadius: 'var(--radius-md)', background: 'rgba(104,75,255,0.28)', display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0 }}>
                  <SiteIcon name={q.icon} size={23} color="var(--violet-200)" />
                </div>
                <div>
                  <div style={{ fontSize: 15.5, fontWeight: 800, color: '#fff' }}>{q.t}</div>
                  <div style={{ fontSize: 13.5, color: 'rgba(255,255,255,0.7)' }}>{q.d}</div>
                </div>
                <SiteIcon name="arrow-right" size={18} color="rgba(255,255,255,0.5)" style={{ marginLeft: 'auto' }} />
              </React.Fragment>
            );
            const st = { display: 'flex', alignItems: 'center', gap: 15, background: 'rgba(255,255,255,0.06)', border: '1px solid rgba(255,255,255,0.14)', borderRadius: 'var(--radius-lg)', padding: '18px 20px', cursor: 'pointer', textDecoration: 'none' };
            return q.href
              ? <a key={q.t} href={q.href} target="_blank" rel="noopener noreferrer" style={st}>{inner}</a>
              : <div key={q.t} onClick={q.action} style={st}>{inner}</div>;
          })}
        </div>
      </div>
    </section>
  );
}

const SOP_CANALES = [
  { icon: 'ticket', t: 'Portal de tickets', d: 'Registrá incidencias y solicitudes con seguimiento y número de caso. La vía recomendada para todo pedido de soporte.', meta: 'Respuesta según tu SLA', cta: 'Abrir ticket', nav: 'ticket' },
  { icon: 'message-circle', t: 'WhatsApp', d: 'Para consultas rápidas y urgencias operativas durante el horario de atención.', meta: '+598 97 574 400', cta: 'Escribir por WhatsApp', href: WA_LINK },
  { icon: 'mail', t: 'Correo de soporte', d: 'Envianos el detalle y adjuntos. Se genera un ticket automáticamente al recibirlo.', meta: 'soporte@okentra.com', cta: 'Enviar correo', href: 'mailto:soporte@okentra.com' },
  { icon: 'phone', t: 'Teléfono', d: 'Atención telefónica para clientes con soporte Premium y casos críticos.', meta: 'Lun a Vie · 9–18 h', cta: 'Ver niveles', nav: 'sla' },
];

function SopCanales({ innerRef, onNav }) {
  const { Card } = window.OKENTRADesignSystem_9c3390;
  return (
    <section ref={innerRef} style={{ maxWidth: 1240, margin: '0 auto', padding: '84px 28px' }}>
      <SopHead eyebrow="Formas de contacto" title="Contactanos por donde te resulte más cómodo" sub="Todos los canales quedan registrados como tickets para que ninguna consulta se pierda." />
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(2, 1fr)', gap: 18 }}>
        {SOP_CANALES.map((c) => (
          <Card key={c.t} padding="lg" interactive>
            <div style={{ display: 'flex', alignItems: 'flex-start', gap: 16 }}>
              <div style={{ width: 52, height: 52, borderRadius: 'var(--radius-md)', background: 'var(--violet-50)', display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0 }}>
                <SiteIcon name={c.icon} size={26} color="var(--violet-600)" />
              </div>
              <div style={{ flex: 1 }}>
                <h3 style={{ margin: '0 0 8px', fontSize: 18, fontWeight: 800, color: 'var(--navy-600)' }}>{c.t}</h3>
                <p style={{ margin: '0 0 12px', fontSize: 14, lineHeight: 1.6, color: 'var(--text-muted)' }}>{c.d}</p>
                <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: 12, flexWrap: 'wrap', borderTop: '1px solid var(--border-subtle)', paddingTop: 12 }}>
                  <span style={{ fontSize: 13.5, fontWeight: 700, color: 'var(--navy-600)', fontFamily: 'var(--font-mono)' }}>{c.meta}</span>
                  {c.href
                    ? <a href={c.href} target={c.href.startsWith('http') ? '_blank' : undefined} rel="noopener noreferrer" style={{ fontSize: 13.5, fontWeight: 700, color: 'var(--violet-600)', textDecoration: 'none', display: 'inline-flex', alignItems: 'center', gap: 6 }}>{c.cta} <SiteIcon name="arrow-right" size={15} color="var(--violet-600)" /></a>
                    : <a href="#" onClick={(e) => { e.preventDefault(); onNav(c.nav); }} style={{ fontSize: 13.5, fontWeight: 700, color: 'var(--violet-600)', textDecoration: 'none', display: 'inline-flex', alignItems: 'center', gap: 6 }}>{c.cta} <SiteIcon name="arrow-right" size={15} color="var(--violet-600)" /></a>}
                </div>
              </div>
            </div>
          </Card>
        ))}
      </div>
    </section>
  );
}

const SOP_ESTADO = [
  { t: 'OKentra ERP (Odoo)', s: 'ok' },
  { t: 'Evolución RRHH y Nómina', s: 'ok' },
  { t: 'Facturación electrónica (DGI)', s: 'ok' },
  { t: 'Integraciones de pago', s: 'ok' },
  { t: 'Portal Campus', s: 'ok' },
  { t: 'Monitoreo Sensores', s: 'ok' },
];

function SopEstado({ innerRef }) {
  const map = { ok: ['Operativo', 'var(--success-100)', '#15734f', 'check-circle-2'], deg: ['Degradado', 'var(--warning-100)', '#8a5a00', 'alert-triangle'], down: ['Interrumpido', 'var(--danger-100)', '#a3232a', 'x-circle'] };
  return (
    <section ref={innerRef} style={{ background: 'var(--neutral-50)', borderTop: '1px solid var(--border-subtle)', borderBottom: '1px solid var(--border-subtle)' }}>
      <div style={{ maxWidth: 1000, margin: '0 auto', padding: '84px 28px' }}>
        <SopHead eyebrow="Estado del sistema" title="Todos los servicios operativos" />
        <div style={{ background: '#fff', border: '1px solid var(--border-subtle)', borderRadius: 'var(--radius-xl)', boxShadow: 'var(--shadow-sm)', overflow: 'hidden' }}>
          <div style={{ display: 'flex', alignItems: 'center', gap: 12, padding: '18px 24px', background: 'var(--success-100)', borderBottom: '1px solid var(--border-subtle)' }}>
            <SiteIcon name="check-circle-2" size={22} color="#15734f" strokeWidth={2.2} />
            <span style={{ fontSize: 15.5, fontWeight: 800, color: '#15734f' }}>Todos los sistemas funcionan con normalidad</span>
          </div>
          {SOP_ESTADO.map((row, i) => {
            const [label, bg, fg, ic] = map[row.s];
            return (
              <div key={row.t} style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', padding: '16px 24px', borderTop: i === 0 ? 'none' : '1px solid var(--border-subtle)' }}>
                <span style={{ fontSize: 14.5, fontWeight: 600, color: 'var(--text-body)' }}>{row.t}</span>
                <span style={{ display: 'inline-flex', alignItems: 'center', gap: 7, fontSize: 12.5, fontWeight: 700, color: fg, background: bg, padding: '5px 12px', borderRadius: 999 }}><SiteIcon name={ic} size={14} color={fg} /> {label}</span>
              </div>
            );
          })}
        </div>
        <p style={{ margin: '16px 0 0', textAlign: 'center', fontSize: 13, color: 'var(--text-muted)' }}>Última actualización: hoy · Los incidentes se comunican por correo a los clientes afectados.</p>
      </div>
    </section>
  );
}

const SOP_BASE = [
  { icon: 'boxes', t: 'OKentra ERP (Odoo)', n: 18, d: 'Configuración, módulos, permisos y flujos de trabajo.' },
  { icon: 'users', t: 'Evolución RRHH', n: 14, d: 'Asistencia, prenómina, nómina y legajos.' },
  { icon: 'file-check-2', t: 'Facturación electrónica', n: 9, d: 'DGI e-Factura, CFE, notas y contingencia.' },
  { icon: 'credit-card', t: 'Pagos e integraciones', n: 11, d: 'Redpagos, Abitab, Mercado Pago y conciliación.' },
  { icon: 'graduation-cap', t: 'Campus', n: 7, d: 'Cursos, inscripciones y certificados.' },
  { icon: 'thermometer', t: 'Sensores y hardware', n: 8, d: 'Instalación, alarmas y monitoreo remoto.' },
];

function SopBase({ innerRef, onNav }) {
  return (
    <section ref={innerRef} style={{ maxWidth: 1240, margin: '0 auto', padding: '84px 28px' }}>
      <SopHead eyebrow="Centro de ayuda" title="Explorá por categoría" sub="Guías paso a paso y respuestas a las consultas más frecuentes de cada solución." />
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: 18 }}>
        {SOP_BASE.map((c) => (
          <a key={c.t} href="#" onClick={(e) => { e.preventDefault(); onNav('ticket'); }} style={{ textDecoration: 'none', background: '#fff', border: '1px solid var(--border-subtle)', borderRadius: 'var(--radius-lg)', boxShadow: 'var(--shadow-sm)', padding: 24, display: 'block' }}>
            <div style={{ display: 'flex', alignItems: 'center', gap: 14, marginBottom: 12 }}>
              <div style={{ width: 46, height: 46, borderRadius: 'var(--radius-md)', background: 'var(--violet-50)', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
                <SiteIcon name={c.icon} size={23} color="var(--violet-600)" />
              </div>
              <span style={{ fontSize: 12, fontWeight: 700, color: 'var(--text-muted)', background: 'var(--surface-sunken)', padding: '4px 10px', borderRadius: 999 }}>{c.n} artículos</span>
            </div>
            <h3 style={{ margin: '0 0 6px', fontSize: 17, fontWeight: 800, color: 'var(--navy-600)' }}>{c.t}</h3>
            <p style={{ margin: 0, fontSize: 13.5, lineHeight: 1.55, color: 'var(--text-muted)' }}>{c.d}</p>
          </a>
        ))}
      </div>
    </section>
  );
}

const SOP_SLA = [
  { t: 'Estándar', d: 'Incluido en toda implementación OKentra.', tag: false, items: [['Canal', 'Ticket y correo'], ['Horario', 'Lun a Vie · 10–17 h'], ['1ª respuesta', 'Hasta 24 h hábiles'], ['Crítico', '48 h hábiles']] },
  { t: 'Priority', d: 'Para operaciones que no pueden esperar.', tag: true, items: [['Canal', 'Ticket, correo y WhatsApp'], ['Horario', 'Lun a Vie · 8–20 h'], ['1ª respuesta', 'Hasta 4 h hábiles'], ['Crítico', 'Hasta 4 h hábiles']] },
  { t: 'Premium', d: 'Acompañamiento cercano y atención telefónica.', tag: false, items: [['Canal', 'Todos + teléfono directo'], ['Horario', 'Extendido, con guardias'], ['1ª respuesta', 'Hasta 2 h hábiles'], ['Crítico', 'Atención inmediata']] },
];

function SopSLA({ innerRef, onNav }) {
  const { Button } = window.OKENTRADesignSystem_9c3390;
  return (
    <section ref={innerRef} style={{ background: 'var(--navy-700)', color: '#fff', position: 'relative', overflow: 'hidden' }}>
      <div style={{ position: 'absolute', bottom: -160, left: -100, width: 480, height: 480, borderRadius: '50%', background: 'radial-gradient(circle, rgba(104,75,255,0.3), rgba(104,75,255,0) 70%)' }} />
      <div style={{ maxWidth: 1240, margin: '0 auto', padding: '84px 28px', position: 'relative' }}>
        <SopHead eyebrow="Niveles de servicio" title="Tiempos de respuesta según tu plan" sub="Definimos el SLA junto a cada cliente. Estos son nuestros niveles de referencia." light />
        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: 18, alignItems: 'stretch' }}>
          {SOP_SLA.map((p) => (
            <div key={p.t} style={{ display: 'flex', flexDirection: 'column', background: p.tag ? 'rgba(104,75,255,0.16)' : 'rgba(255,255,255,0.05)', border: p.tag ? '1px solid var(--violet-300)' : '1px solid rgba(255,255,255,0.12)', borderRadius: 'var(--radius-xl)', padding: 26, position: 'relative' }}>
              {p.tag && <span style={{ position: 'absolute', top: -12, right: 20, fontSize: 11.5, fontWeight: 800, letterSpacing: '0.06em', textTransform: 'uppercase', color: '#fff', background: 'var(--violet-500)', padding: '5px 12px', borderRadius: 999 }}>Recomendado</span>}
              <h3 style={{ margin: '0 0 6px', fontSize: 22, fontWeight: 800 }}>{p.t}</h3>
              <p style={{ margin: '0 0 18px', fontSize: 13.5, color: 'rgba(255,255,255,0.7)', lineHeight: 1.5 }}>{p.d}</p>
              <div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
                {p.items.map(([k, v]) => (
                  <div key={k} style={{ display: 'flex', alignItems: 'baseline', justifyContent: 'space-between', gap: 12, borderBottom: '1px solid rgba(255,255,255,0.1)', paddingBottom: 9 }}>
                    <span style={{ fontSize: 12.5, color: 'rgba(255,255,255,0.6)' }}>{k}</span>
                    <span style={{ fontSize: 13.5, fontWeight: 700, textAlign: 'right' }}>{v}</span>
                  </div>
                ))}
              </div>
            </div>
          ))}
        </div>
        <div style={{ textAlign: 'center', marginTop: 32 }}>
          <Button variant="secondary" size="lg" onClick={() => onNav('ticket')} style={{ background: '#fff', color: 'var(--navy-600)', borderColor: '#fff' }}>Consultar mi nivel de soporte</Button>
        </div>
      </div>
    </section>
  );
}

const SOP_FAQ = [
  { q: '¿Cómo abro un ticket de soporte?', a: 'Desde el formulario de esta página, escribiendo a soporte@okentra.com o por WhatsApp. En todos los casos generamos un número de caso para hacer seguimiento.' },
  { q: '¿Cuál es el horario de atención?', a: 'El horario estándar es de lunes a viernes de 9 a 18 h (Uruguay). Los planes Priority y Premium cuentan con horarios extendidos y guardias para casos críticos.' },
  { q: '¿Qué información debo incluir al reportar un problema?', a: 'Describí qué intentabas hacer, qué ocurrió, el módulo o solución afectada y, si es posible, capturas de pantalla o el mensaje de error. Cuanto más detalle, más rápida la resolución.' },
  { q: '¿El soporte cubre la facturación electrónica ante la DGI?', a: 'Sí. Damos soporte a la emisión de CFE, contingencia y ajustes de e-Factura sobre Odoo, en coordinación con los requisitos vigentes de la DGI.' },
  { q: '¿Atienden urgencias fuera de horario?', a: 'Las urgencias críticas se atienden según el SLA contratado. Los clientes Premium disponen de guardias y atención inmediata para incidentes que detienen la operación.' },
  { q: '¿Cómo sé si un problema es general o solo mío?', a: 'Consultá la sección Estado del sistema de esta página: ahí publicamos el estado de cada servicio y cualquier incidente en curso.' },
];

function SopFAQ({ innerRef }) {
  const [open, setOpen] = React.useState(0);
  return (
    <section ref={innerRef} style={{ maxWidth: 880, margin: '0 auto', padding: '84px 28px' }}>
      <SopHead eyebrow="FAQ" title="Preguntas frecuentes" />
      <div style={{ display: 'flex', flexDirection: 'column', gap: 12 }}>
        {SOP_FAQ.map((f, i) => {
          const isOpen = open === i;
          return (
            <div key={i} style={{ border: '1px solid var(--border-subtle)', borderRadius: 'var(--radius-lg)', background: '#fff', overflow: 'hidden' }}>
              <button onClick={() => setOpen(isOpen ? -1 : i)} style={{ width: '100%', display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: 12, padding: '18px 22px', border: 'none', background: 'transparent', cursor: 'pointer', textAlign: 'left', fontFamily: 'var(--font-sans)' }}>
                <span style={{ fontSize: 15.5, fontWeight: 700, color: 'var(--navy-600)' }}>{f.q}</span>
                <SiteIcon name={isOpen ? 'chevron-up' : 'chevron-down'} size={18} color="var(--violet-600)" />
              </button>
              {isOpen && <div style={{ padding: '0 22px 18px', fontSize: 14.5, lineHeight: 1.6, color: 'var(--text-muted)' }}>{f.a}</div>}
            </div>
          );
        })}
      </div>
    </section>
  );
}

function SopTicket({ innerRef }) {
  const { Button, Input, Select } = window.OKENTRADesignSystem_9c3390;
  const [sent, setSent] = React.useState(false);
  const [sending, setSending] = React.useState(false);
  const [error, setError] = React.useState('');
  const [form, setForm] = React.useState({ name: '', company: '', email: '', phone: '', area: '', priority: '', subject: '', message: '' });
  const set = (k) => (e) => setForm((f) => ({ ...f, [k]: e.target.value }));
  const submit = async () => {
    if (!form.name || !form.email || !form.subject) { setError('Completá al menos nombre, correo y asunto.'); return; }
    setSending(true); setError('');
    try {
      const res = await fetch('https://api.web3forms.com/submit', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json', Accept: 'application/json' },
        body: JSON.stringify({
          access_key: SOP_WEB3FORMS_KEY,
          subject: 'Nuevo ticket de soporte — ' + (form.subject || 'Sin asunto'),
          from_name: 'OKENTRA Soporte',
          replyto: form.email,
          name: form.name,
          email: form.email,
          empresa: form.company,
          telefono: form.phone,
          area: form.area,
          prioridad: form.priority,
          asunto: form.subject,
          message: form.message,
        }),
      });
      const data = await res.json();
      if (data.success) setSent(true);
      else setError(data.message || 'No se pudo enviar. Intentá de nuevo.');
    } catch (err) {
      setError('No se pudo enviar. Revisá tu conexión e intentá de nuevo.');
    } finally { setSending(false); }
  };
  return (
    <section ref={innerRef} style={{ background: 'var(--neutral-50)', borderTop: '1px solid var(--border-subtle)' }}>
      <div style={{ maxWidth: 1240, margin: '0 auto', padding: '84px 28px' }}>
        <SopHead eyebrow="Abrir un ticket" title="Contanos qué está pasando" sub="Completá el formulario y te devolvemos un número de caso. También podés escribir a soporte@okentra.com." />
        <div style={{ display: 'grid', gridTemplateColumns: '0.85fr 1.15fr', gap: 28, alignItems: 'start' }}>
          <div style={{ display: 'flex', flexDirection: 'column', gap: 12 }}>
            {[
              { icon: 'clock', t: 'Tiempo de respuesta', d: 'Según tu SLA. Confirmamos la recepción al instante.' },
              { icon: 'mail', t: 'Correo de soporte', d: 'soporte@okentra.com' },
              { icon: 'message-circle', t: 'WhatsApp', d: '+598 97 574 400' },
              { icon: 'shield-check', t: 'Confidencial', d: 'Tratamos tus datos según nuestra política de privacidad.' },
            ].map((r) => (
              <div key={r.t} style={{ display: 'flex', alignItems: 'center', gap: 15, background: '#fff', border: '1px solid var(--border-subtle)', borderRadius: 'var(--radius-lg)', padding: '16px 18px' }}>
                <div style={{ width: 44, height: 44, borderRadius: 'var(--radius-md)', background: 'var(--violet-50)', display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0 }}>
                  <SiteIcon name={r.icon} size={21} color="var(--violet-600)" />
                </div>
                <div>
                  <div style={{ fontSize: 14.5, fontWeight: 700, color: 'var(--navy-600)' }}>{r.t}</div>
                  <div style={{ fontSize: 13, color: 'var(--text-muted)' }}>{r.d}</div>
                </div>
              </div>
            ))}
          </div>
          <div style={{ background: '#fff', border: '1px solid var(--border-subtle)', borderRadius: 'var(--radius-xl)', boxShadow: 'var(--shadow-md)', padding: 28 }}>
            {sent ? (
              <div style={{ textAlign: 'center', padding: '48px 0' }}>
                <div style={{ width: 56, height: 56, margin: '0 auto 16px', borderRadius: '50%', background: 'var(--success-100)', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
                  <SiteIcon name="check" size={28} color="#15734f" strokeWidth={2.4} />
                </div>
                <h3 style={{ margin: '0 0 6px', fontSize: 20, fontWeight: 700, color: 'var(--text-strong)' }}>¡Ticket recibido!</h3>
                <p style={{ margin: 0, color: 'var(--text-muted)', fontSize: 14 }}>Te enviamos una confirmación por correo y nuestro equipo se pondrá en contacto según tu SLA.</p>
              </div>
            ) : (
              <React.Fragment>
                <h3 style={{ margin: '0 0 18px', fontSize: 20, fontWeight: 800, color: 'var(--text-strong)' }}>Nuevo ticket</h3>
                <div style={{ display: 'flex', flexDirection: 'column', gap: 14 }}>
                  <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 14 }}>
                    <Input label="Nombre completo" placeholder="Tu nombre" value={form.name} onChange={set('name')} required />
                    <Input label="Empresa" placeholder="Tu empresa" value={form.company} onChange={set('company')} />
                  </div>
                  <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 14 }}>
                    <Input label="Correo electrónico" placeholder="nombre@empresa.com" type="email" value={form.email} onChange={set('email')} required />
                    <Input label="Teléfono" placeholder="+598 99 000 000" value={form.phone} onChange={set('phone')} />
                  </div>
                  <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 14 }}>
                    <Select label="Área / solución" placeholder="Seleccionar…" value={form.area} onChange={set('area')} options={['OKentra ERP (Odoo)', 'Evolución RRHH', 'Facturación electrónica', 'Pagos e integraciones', 'Campus', 'Sensores y hardware', 'Otra']} />
                    <Select label="Prioridad" placeholder="Seleccionar…" value={form.priority} onChange={set('priority')} options={['Baja', 'Media', 'Alta', 'Crítica (operación detenida)']} />
                  </div>
                  <Input label="Asunto" placeholder="Resumen breve del problema" value={form.subject} onChange={set('subject')} required />
                  <TicketTextarea value={form.message} onChange={set('message')} />
                  {error && <p style={{ margin: 0, fontSize: 13, color: 'var(--danger-500)' }}>{error}</p>}
                  <Button variant="primary" fullWidth disabled={sending} onClick={submit}>{sending ? 'Enviando…' : 'Enviar ticket'}</Button>
                </div>
              </React.Fragment>
            )}
          </div>
        </div>
      </div>
    </section>
  );
}

function TicketTextarea({ value, onChange }) {
  return (
    <label style={{ display: 'flex', flexDirection: 'column', gap: 6 }}>
      <span style={{ fontSize: 13, fontWeight: 600, color: 'var(--text-body)' }}>Descripción</span>
      <textarea value={value} onChange={onChange} rows={5} placeholder="Contanos qué intentabas hacer, qué ocurrió y en qué módulo. Adjuntá capturas si podés." style={{ width: '100%', boxSizing: 'border-box', resize: 'vertical', fontFamily: 'var(--font-sans)', fontSize: 14, color: 'var(--text-body)', padding: '11px 13px', border: '1px solid var(--border-default)', borderRadius: 'var(--radius-md)', outline: 'none', lineHeight: 1.5 }} />
    </label>
  );
}

function SoportePage({ onHome }) {
  const refs = {
    canales: React.useRef(null), estado: React.useRef(null), base: React.useRef(null),
    sla: React.useRef(null), faq: React.useRef(null), ticket: React.useRef(null),
  };
  const [active, setActive] = React.useState('');
  const nav = (id) => {
    setActive(id);
    const t = refs[id];
    if (t && t.current) { const top = t.current.offsetTop - 112; window.scrollTo(0, top); try { window.scrollTo({ top, behavior: 'smooth' }); } catch (e) {} }
  };
  const goHome = onHome || (() => { window.scrollTo(0, 0); });
  return (
    <React.Fragment>
      <SopHeader active={active} onNav={nav} onHome={goHome} />
      <SopHero onNav={nav} />
      <SopCanales innerRef={refs.canales} onNav={nav} />
      <SopEstado innerRef={refs.estado} />
      <SopBase innerRef={refs.base} onNav={nav} />
      <SopSLA innerRef={refs.sla} onNav={nav} />
      <SopFAQ innerRef={refs.faq} />
      <SopTicket innerRef={refs.ticket} />
      <SiteFooter />
    </React.Fragment>
  );
}

Object.assign(window, { SoportePage });
