// 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' },
    { id: 'servicios', label: 'Servicios' },
    { id: 'hardware', label: 'Hardware' },
    { id: 'industrias', label: 'Industrias' },
    { id: 'casos', label: 'Hitos' },
    { id: 'blog', label: 'Blog' },
    { id: 'nosotros', label: 'Nosotros' },
    { 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 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 (
              <a key={l.id} href="#" onClick={(e) => go(e, l.id)}
                onMouseEnter={() => setHover(l.id)} onMouseLeave={() => setHover(null)}
                style={{
                  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}</a>
            );
          })}
        </nav>
        <span style={{ flex: 1 }} />
        <a 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 WEB3FORMS_ACCESS_KEY = '6279f379-6ade-4053-9a70-3496cc897890';
  const [sent, setSent] = React.useState(false);
  const [sending, setSending] = React.useState(false);
  const [error, setError] = React.useState(null);
  const [form, setForm] = React.useState({ name: '', email: '', solution: '' });
  const setField = (field) => (e) => setForm((f) => ({ ...f, [field]: e.target.value }));
  React.useEffect(() => {
    if (open) { setSent(false); setSending(false); setError(null); setForm({ name: '', email: '', solution: '' }); }
  }, [open]);
  const submit = async () => {
    setError(null);
    if (!form.name.trim() || !form.email.trim()) {
      setError('Completá tu nombre y correo corporativo.');
      return;
    }
    setSending(true);
    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: WEB3FORMS_ACCESS_KEY,
          subject: 'Nueva solicitud de demo desde OKENTRA Web',
          from_name: 'OKENTRA Web',
          replyto: form.email,
          name: form.name,
          email: form.email,
          interes: form.solution,
        }),
      });
      const data = await res.json();
      if (!res.ok || !data.success) {
        throw new Error(data.message || 'No se pudo enviar la solicitud.');
      }
      setSent(true);
    } catch (e) {
      setError('No se pudo enviar la solicitud. Intentá nuevamente.');
    } finally {
      setSending(false);
    }
  };
  if (!open) return null;
  return (
    <div 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 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 20px', color: 'var(--text-muted)', fontSize: 14 }}>Contanos sobre tu empresa y te mostramos OKentra en acción.</p>
            <div style={{ display: 'flex', flexDirection: 'column', gap: 14 }}>
              <Input label="Nombre y apellido" placeholder="Tu nombre" value={form.name} onChange={setField('name')} />
              <Input label="Correo corporativo" placeholder="nombre@empresa.com" type="email" value={form.email} onChange={setField('email')} />
              <Select label="¿Qué te interesa?" placeholder="Seleccionar solución…" options={['OKentra ERP','OKentra Evolución RRHH','OKentra Campus','OKentra PreObra','OKentra Pagos','OKentra Sensor','Otra']} value={form.solution} onChange={setField('solution')} />
              {error && <p style={{ margin: 0, fontSize: 13.5, color: 'var(--danger-500)' }}>{error}</p>}
              <Button variant="primary" fullWidth disabled={sending} onClick={submit}>{sending ? 'Enviando…' : 'Enviar solicitud'}</Button>
            </div>
          </React.Fragment>
        )}
      </div>
    </div>
  );
}

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