// OKENTRA Website — Header with demo modal
function SiteIcon({ name, size = 20, color = 'currentColor', strokeWidth = 1.75, style }) {
  const ref = React.useRef(null);
  React.useEffect(() => {
    if (window.lucide && ref.current) {
      ref.current.innerHTML = '';
      const el = document.createElement('i');
      el.setAttribute('data-lucide', name);
      ref.current.appendChild(el);
      window.lucide.createIcons({ attrs: { width: size, height: size, 'stroke-width': strokeWidth } });
    }
  });
  return <span ref={ref} style={{ display: 'inline-flex', color, width: size, height: size, ...style }} />;
}

function SiteHeader({ onDemo, active, onNav }) {
  const { Button } = window.OKENTRADesignSystem_9c3390;
  const links = [
    { id: 'soluciones', label: 'Soluciones', sub: [
      { id: 'soluciones', label: 'Todas las soluciones' },
      { id: 'servicios', label: 'Servicios' },
      { id: 'hardware', label: 'Hardware' },
    ] },
    { id: 'industrias', label: 'Industrias' },
    { id: 'nosotros', label: 'Nosotros', sub: [
      { id: 'nosotros', label: 'Sobre OKentra' },
      { id: 'casos', label: 'Hitos' },
    ] },
    { id: 'blog', label: 'Blog' },
    { id: 'soporte', label: 'Soporte' },
  ];
  const go = (e, id) => { e.preventDefault(); if (onNav) onNav(id); };
  const [hover, setHover] = React.useState(null);
  return (
    <header style={{
      position: 'sticky', top: 0, zIndex: 100, background: 'rgba(255,255,255,0.86)',
      backdropFilter: 'saturate(150%) blur(10px)', WebkitBackdropFilter: 'saturate(150%) blur(10px)',
      borderBottom: '1px solid var(--border-subtle)',
    }}>
      <div style={{ maxWidth: 1240, margin: '0 auto', height: 70, display: 'flex', alignItems: 'center', gap: 24, padding: '0 28px' }}>
        <a className="ok-pressable" href="#" onClick={(e) => go(e, 'home')} style={{ display: 'flex', alignItems: 'center' }}>
          <img src="../../assets/logos/okentra-logo.png" alt="OKentra" style={{ height: 40 }} />
        </a>
        <nav style={{ display: 'flex', gap: 4, marginLeft: 14 }}>
          {links.map((l) => {
            const isActive = active === l.id;
            const isHover = hover === l.id;
            return (
              <div key={l.id} style={{ position: 'relative' }} onMouseEnter={() => setHover(l.id)} onMouseLeave={() => setHover(null)}>
                <a className="ok-pressable" href="#" onClick={(e) => go(e, l.id)}
                  style={{
                    display: 'inline-flex', alignItems: 'center', gap: 5,
                    fontSize: 14, fontWeight: isActive ? 800 : 700,
                    color: isActive || isHover ? 'var(--violet-600)' : 'var(--text-body)',
                    textDecoration: 'none', padding: '8px 12px', borderRadius: 'var(--radius-sm)',
                    background: isActive ? 'var(--violet-50)' : isHover ? 'var(--surface-sunken)' : 'transparent',
                    transition: 'background 0.15s ease, color 0.15s ease',
                  }}>{l.label}{l.sub && <SiteIcon name="chevron-down" size={14} color="currentColor" />}</a>
                {l.sub && isHover && (
                  <div style={{ position: 'absolute', top: '100%', left: 0, minWidth: 210, background: '#fff', border: '1px solid var(--border-subtle)', borderRadius: 'var(--radius-md)', boxShadow: 'var(--shadow-lg)', padding: 6, display: 'flex', flexDirection: 'column', gap: 2, zIndex: 200 }}>
                    {l.sub.map((s) => (
                      <a key={s.label} href="#" onClick={(e) => go(e, s.id)} style={{ fontSize: 13.5, fontWeight: 600, color: 'var(--text-body)', textDecoration: 'none', padding: '9px 12px', borderRadius: 'var(--radius-sm)' }} onMouseEnter={(e) => { e.currentTarget.style.background = 'var(--violet-50)'; e.currentTarget.style.color = 'var(--violet-600)'; }} onMouseLeave={(e) => { e.currentTarget.style.background = 'transparent'; e.currentTarget.style.color = 'var(--text-body)'; }}>{s.label}</a>
                    ))}
                  </div>
                )}
              </div>
            );
          })}
        </nav>
        <span style={{ flex: 1 }} />
        <a className="ok-pressable" href="#" onClick={(e) => go(e, 'contacto')}
          onMouseEnter={() => setHover('contacto')} onMouseLeave={() => setHover(null)}
          style={{ fontSize: 14, fontWeight: 700, letterSpacing: '0.04em', color: hover === 'contacto' ? 'var(--violet-600)' : 'var(--navy-700)', textDecoration: 'none', padding: '8px 12px', borderRadius: 'var(--radius-sm)', background: hover === 'contacto' ? 'var(--surface-sunken)' : 'transparent', transition: 'background 0.15s ease, color 0.15s ease' }}>CONTACTO</a>
        <Button variant="primary" onClick={onDemo}>Solicitar demo</Button>
      </div>
    </header>
  );
}

function DemoModal({ open, onClose }) {
  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: '', email: '', industry: '', employees: '', challenge: '', maturity: '', solution: '' });
  const set = (key) => (event) => setForm((current) => ({ ...current, [key]: event.target.value }));
  React.useEffect(() => {
    if (open) {
      setSent(false);
      setSending(false);
      setError('');
    }
  }, [open]);
  const submit = async () => {
    if (!form.name || !form.email) {
      setError('Completá al menos tu nombre y correo.');
      return;
    }
    setSending(true);
    setError('');
    try {
      const result = await fetch((window.OKENTRA_CONFIG || {}).CRM_WEBHOOK_URL || '/api/contacto', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json', Accept: 'application/json' },
        body: JSON.stringify({
          name: 'Solicitud de demo — ' + form.name,
          contact_name: form.name,
          email_from: form.email,
          x_industria: form.industry,
          x_empleados: form.employees,
          x_desafio_principal: form.challenge,
          x_madurez_digital: form.maturity,
          x_solucion_interes: form.solution,
          website_hp: '',
        }),
      });
      const data = await result.json();
      if (result.ok && data.ok) setSent(true);
      else setError('No se pudo enviar. Intentá de nuevo o escribinos por WhatsApp.');
    } catch (_error) {
      setError('No se pudo enviar. Revisá tu conexión e intentá de nuevo.');
    } finally {
      setSending(false);
    }
  };
  if (!open) return null;
  return (
    <div className="ok-modal-backdrop" onClick={onClose} style={{
      position: 'fixed', inset: 0, zIndex: 900, background: 'rgba(13,16,48,0.55)',
      backdropFilter: 'blur(2px)', display: 'flex', alignItems: 'center', justifyContent: 'center', padding: 20,
    }}>
      <div className="ok-modal-panel" onClick={(e) => e.stopPropagation()} style={{
        width: 460, maxWidth: '100%', background: '#fff', borderRadius: 'var(--radius-xl)',
        boxShadow: 'var(--shadow-xl)', padding: 28, position: 'relative',
      }}>
        <button onClick={onClose} aria-label="Cerrar" style={{ position: 'absolute', top: 18, right: 18, border: 'none', background: 'transparent', cursor: 'pointer', color: 'var(--text-muted)' }}>
          <SiteIcon name="x" size={20} />
        </button>
        {sent ? (
          <div style={{ textAlign: 'center', padding: '20px 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)' }}>¡Gracias!</h3>
            <p style={{ margin: 0, color: 'var(--text-muted)', fontSize: 14 }}>Un especialista de OKENTRA se pondrá en contacto a la brevedad.</p>
          </div>
        ) : (
          <React.Fragment>
            <h3 style={{ margin: '0 0 4px', fontSize: 21, fontWeight: 800, color: 'var(--text-strong)', letterSpacing: '-0.01em' }}>Solicitar una demo</h3>
            <p style={{ margin: '0 0 18px', color: 'var(--text-muted)', fontSize: 14 }}>Elegí día y hora en nuestra agenda, o dejanos tus datos y te contactamos.</p>
            <a href={(window.OKENTRA_CONFIG || {}).APPOINTMENT_URL || '#'} target="_blank" rel="noopener" style={{ display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 9, background: 'var(--violet-600)', color: '#fff', textDecoration: 'none', fontSize: 15, fontWeight: 700, padding: '13px 18px', borderRadius: 'var(--radius-md)', marginBottom: 16 }}>
              <SiteIcon name="calendar-check" size={17} color="#fff" /> Agendar en el calendario
            </a>
            <div style={{ display: 'flex', alignItems: 'center', gap: 12, margin: '0 0 16px' }}>
              <span style={{ flex: 1, height: 1, background: 'var(--border-subtle)' }} />
              <span style={{ fontSize: 12, fontWeight: 700, color: 'var(--text-muted)', textTransform: 'uppercase', letterSpacing: '0.08em' }}>o dejanos tus datos</span>
              <span style={{ flex: 1, height: 1, background: 'var(--border-subtle)' }} />
            </div>
            <div style={{ display: 'flex', flexDirection: 'column', gap: 14, maxHeight: '52vh', overflowY: 'auto', paddingRight: 4 }}>
              <Input label="Nombre y apellido" placeholder="Tu nombre" value={form.name} onChange={set('name')} />
              <Input label="Correo corporativo" placeholder="nombre@empresa.com" type="email" value={form.email} onChange={set('email')} />
              <Select label="¿A qué industria pertenece tu empresa?" placeholder="Seleccionar industria…" value={form.industry} onChange={set('industry')} options={['Logística','Retail y comercio','Manufactura','Servicios profesionales','Salud y farmacia','Construcción','Educación','Sector público','Otro']} />
              <Select label="¿Cuántos empleados conforman el equipo?" placeholder="Seleccionar tamaño…" value={form.employees} onChange={set('employees')} options={['1 a 10','11 a 50','51 a 200','Más de 200']} />
              <Select label="¿Cuál es el principal desafío a resolver a corto plazo?" placeholder="Seleccionar desafío…" value={form.challenge} onChange={set('challenge')} options={['Ordenar finanzas y contabilidad','Controlar el inventario','Centralizar RRHH y asistencias','Mejorar las ventas y el CRM','Integrar todas las áreas de la empresa','Otro']} />
              <Select label="¿Cómo gestionan sus procesos actualmente?" placeholder="Seleccionar situación…" value={form.maturity} onChange={set('maturity')} options={['Usamos Excel y papel','Tenemos varios sistemas desconectados','Usamos un ERP pero queremos cambiarlo']} />
              <Select label="¿Qué te interesa?" placeholder="Seleccionar solución…" value={form.solution} onChange={set('solution')} options={['OKentra ERP','OKentra Evolución RRHH','OKentra Campus','OKentra PreObra','OKentra Tap','OKentra Sens','OKentra LIMS','Hardware','Servicios','Otra']} />
            </div>
            <div style={{ display: 'flex', flexDirection: 'column', gap: 12, marginTop: 16 }}>
              {error && <p style={{ margin: 0, fontSize: 13, color: 'var(--danger-500)' }}>{error}</p>}
              <Button variant="primary" fullWidth disabled={sending} onClick={submit}>{sending ? 'Enviando…' : 'Enviar solicitud'}</Button>
              <a href={'https://wa.me/' + ((window.OKENTRA_CONFIG || {}).WHATSAPP_NUMBER || '59897574400') + '?text=' + encodeURIComponent(((window.OKENTRA_CONFIG || {}).WHATSAPP_TEXT) || 'Hola OKentra, quiero una demo')} target="_blank" rel="noopener" style={{ display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 9, fontSize: 14, fontWeight: 700, color: '#128C4A', textDecoration: 'none', background: 'rgba(37,211,102,0.10)', border: '1px solid rgba(37,211,102,0.35)', borderRadius: 'var(--radius-md)', padding: '12px 16px' }}>
                <SiteIcon name="message-circle" size={16} color="#128C4A" /> Prefiero escribir por WhatsApp
              </a>
            </div>
          </React.Fragment>
        )}
      </div>
    </div>
  );
}

function PartnerBadge({ style }) {
  return (
    <div style={{ display: 'inline-flex', alignItems: 'center', gap: 16, background: 'rgba(255,255,255,0.06)', border: '1px solid rgba(255,255,255,0.14)', borderRadius: 999, padding: '9px 18px', ...(style || {}) }}>
      <span style={{ display: 'inline-flex', alignItems: 'center', gap: 8, fontSize: 13, fontWeight: 700, color: '#fff' }}><SiteIcon name="badge-check" size={16} color="var(--violet-200)" /> Partner Oficial Odoo</span>
      <span style={{ width: 1, height: 16, background: 'rgba(255,255,255,0.18)' }} />
      <span style={{ fontSize: 13, fontWeight: 700, color: 'rgba(255,255,255,0.85)' }}>100% desarrollado en Uruguay</span>
      <span style={{ width: 1, height: 16, background: 'rgba(255,255,255,0.18)' }} />
      <span style={{ fontSize: 13, fontWeight: 700, color: 'rgba(255,255,255,0.85)' }}>Enterprise + Community</span>
    </div>
  );
}

function WhatsAppFab() {
  const [hov, setHov] = React.useState(false);
  return (
    <a href={'https://wa.me/' + ((window.OKENTRA_CONFIG || {}).WHATSAPP_NUMBER || '59897574400') + '?text=' + encodeURIComponent(((window.OKENTRA_CONFIG || {}).WHATSAPP_TEXT) || 'Hola OKentra, quiero hacer una consulta')} target="_blank" rel="noopener" aria-label="Escribinos por WhatsApp"
      onMouseEnter={() => setHov(true)} onMouseLeave={() => setHov(false)}
      style={{ position: 'fixed', bottom: 24, right: 24, zIndex: 900, display: 'inline-flex', alignItems: 'center', gap: 10, background: '#25D366', color: '#fff', textDecoration: 'none', fontSize: 14.5, fontWeight: 800, padding: hov ? '14px 20px' : '14px', borderRadius: 999, boxShadow: '0 12px 32px rgba(37,211,102,0.42)', transition: 'padding 0.2s ease' }}>
      <SiteIcon name="message-circle" size={24} color="#fff" strokeWidth={2.2} />
      {hov && <span style={{ whiteSpace: 'nowrap' }}>Escribinos</span>}
    </a>
  );
}

Object.assign(window, { SiteIcon, SiteHeader, DemoModal, PartnerBadge, WhatsAppFab });
