/* JRN — Componentes compartilhados */
const { useState, useEffect, useRef, useMemo } = React;

/* ---------- Logo da empresa em "chip" ---------- */
function CompanyMark({ company, size = 44, ring = false }) {
  return (
    <div style={{
      width: size, height: size, borderRadius: 10, background: '#fff',
      border: ring ? `1.5px solid ${company.cor}33` : '1px solid var(--line)',
      display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0, overflow: 'hidden',
    }}>
      <img src={company.logo} alt={company.nome}
        style={{ width: '78%', height: '78%', objectFit: 'contain' }} />
    </div>
  );
}

/* ---------- Badge de status ---------- */
function StatusBadge({ status }) {
  const map = {
    ativo: ['badge-ok', 'Ativo'],
    inativo: ['badge-neutral', 'Inativo'],
    manutencao: ['badge-warn', 'Manutenção'],
    online: ['badge-ok', 'Online'],
  };
  const [cls, label] = map[status] || ['badge-neutral', status];
  return <span className={'badge ' + cls}><span className="dot" style={{ background: 'currentColor' }}></span>{label}</span>;
}

/* ---------- Botão com ícone ---------- */
function Btn({ icon, children, variant = 'primary', sm, ...rest }) {
  const I = icon ? Icons[icon] : null;
  return (
    <button className={`btn btn-${variant}${sm ? ' btn-sm' : ''}`} {...rest}>
      {I && <I />}{children}
    </button>
  );
}

/* ---------- Campo de texto ---------- */
function Field({ label, hint, children, full }) {
  return (
    <div className="field" style={full ? { gridColumn: '1 / -1' } : null}>
      {label && <label>{label}</label>}
      {children}
      {hint && <span className="hint">{hint}</span>}
    </div>
  );
}
function TextInput(props) { return <input className="input" {...props} />; }
function Select({ children, ...rest }) {
  return (
    <div style={{ position: 'relative' }}>
      <select className="select" style={{ appearance: 'none', paddingRight: 34 }} {...rest}>{children}</select>
      <Icons.chevDown size={15} style={{ position: 'absolute', right: 12, top: '50%', transform: 'translateY(-50%)', color: 'var(--muted)', pointerEvents: 'none' }} />
    </div>
  );
}

/* ---------- Toggle / switch ---------- */
function Switch({ on, onChange, accent = 'var(--navy-800)' }) {
  return (
    <button onClick={() => onChange(!on)} aria-pressed={on} style={{
      width: 40, height: 23, borderRadius: 100, border: 'none', cursor: 'pointer',
      background: on ? accent : '#cdd4e0', position: 'relative', transition: '.18s', flexShrink: 0, padding: 0,
    }}>
      <span style={{
        position: 'absolute', top: 3, left: on ? 20 : 3, width: 17, height: 17, borderRadius: '50%',
        background: '#fff', transition: '.18s', boxShadow: '0 1px 3px rgba(0,0,0,.25)',
      }}></span>
    </button>
  );
}

/* ---------- Checkbox ---------- */
function Check({ on, onChange, accent = 'var(--navy-800)', size = 19 }) {
  return (
    <button onClick={() => onChange(!on)} role="checkbox" aria-checked={on} style={{
      width: size, height: size, borderRadius: 5, cursor: 'pointer', flexShrink: 0, padding: 0,
      border: on ? 'none' : '1.5px solid #c4ccda', background: on ? accent : '#fff',
      display: 'flex', alignItems: 'center', justifyContent: 'center', transition: '.12s',
    }}>
      {on && <Icons.check size={size - 6} sw={2.6} style={{ color: '#fff' }} />}
    </button>
  );
}

/* ---------- Modal ---------- */
function Modal({ title, sub, onClose, children, footer, width = 560 }) {
  useEffect(() => {
    const h = (e) => e.key === 'Escape' && onClose();
    window.addEventListener('keydown', h);
    return () => window.removeEventListener('keydown', h);
  }, [onClose]);
  return (
    <div onClick={onClose} style={{
      position: 'fixed', inset: 0, background: 'rgba(13,23,48,.42)', backdropFilter: 'blur(3px)',
      display: 'flex', alignItems: 'flex-start', justifyContent: 'center', zIndex: 200, padding: '6vh 20px 40px', overflowY: 'auto',
    }}>
      <div onClick={(e) => e.stopPropagation()} className="fade-in" style={{
        background: '#fff', borderRadius: 'var(--r-lg)', width: '100%', maxWidth: width, boxShadow: 'var(--sh-lg)',
      }}>
        <div style={{ display: 'flex', alignItems: 'flex-start', justifyContent: 'space-between', padding: '22px 24px 16px', borderBottom: '1px solid var(--line-2)' }}>
          <div>
            <h3 style={{ fontSize: 19 }}>{title}</h3>
            {sub && <p style={{ margin: '5px 0 0', fontSize: 13, color: 'var(--muted)' }}>{sub}</p>}
          </div>
          <button onClick={onClose} className="btn btn-ghost btn-sm" style={{ border: 'none', padding: 7 }}><Icons.x size={18} /></button>
        </div>
        <div style={{ padding: '20px 24px' }}>{children}</div>
        {footer && <div style={{ display: 'flex', justifyContent: 'flex-end', gap: 10, padding: '16px 24px', borderTop: '1px solid var(--line-2)', background: 'var(--surface-2)', borderRadius: '0 0 var(--r-lg) var(--r-lg)' }}>{footer}</div>}
      </div>
    </div>
  );
}

/* ---------- Toast ---------- */
function useToast() {
  const [toast, setToast] = useState(null);
  const show = (msg, kind = 'ok') => {
    setToast({ msg, kind });
    setTimeout(() => setToast(null), 2800);
  };
  const node = toast ? (
    <div className="fade-in" style={{
      position: 'fixed', bottom: 26, left: '50%', transform: 'translateX(-50%)', zIndex: 300,
      background: 'var(--navy-800)', color: '#fff', padding: '13px 18px', borderRadius: 10,
      display: 'flex', alignItems: 'center', gap: 11, boxShadow: 'var(--sh-lg)', fontSize: 13.5, fontWeight: 500,
    }}>
      <span style={{ display: 'flex', width: 20, height: 20, borderRadius: '50%', background: toast.kind === 'ok' ? 'var(--ok)' : 'var(--danger)', alignItems: 'center', justifyContent: 'center' }}>
        <Icons.check size={13} sw={2.6} />
      </span>
      {toast.msg}
    </div>
  ) : null;
  return [node, show];
}

/* ---------- Page header ---------- */
function PageHead({ kicker, title, sub, actions }) {
  return (
    <div style={{ display: 'flex', alignItems: 'flex-end', justifyContent: 'space-between', gap: 20, marginBottom: 26, flexWrap: 'wrap' }}>
      <div>
        {kicker && <div className="kicker" style={{ marginBottom: 9 }}>{kicker}</div>}
        <h1 style={{ fontSize: 28, lineHeight: 1.1 }}>{title}</h1>
        {sub && <p style={{ margin: '9px 0 0', color: 'var(--muted)', fontSize: 14.5, maxWidth: 620 }}>{sub}</p>}
      </div>
      {actions && <div style={{ display: 'flex', gap: 10 }}>{actions}</div>}
    </div>
  );
}

/* ---------- Empty state ---------- */
function Empty({ icon = 'search', title, sub }) {
  const I = Icons[icon];
  return (
    <div style={{ textAlign: 'center', padding: '54px 20px', color: 'var(--muted)' }}>
      <div style={{ width: 52, height: 52, borderRadius: 14, background: 'var(--navy-50)', display: 'inline-flex', alignItems: 'center', justifyContent: 'center', color: 'var(--muted-2)', marginBottom: 14 }}><I size={24} /></div>
      <div style={{ fontFamily: 'var(--font-head)', fontSize: 17, color: 'var(--ink-2)', fontWeight: 600 }}>{title}</div>
      {sub && <div style={{ fontSize: 13.5, marginTop: 6 }}>{sub}</div>}
    </div>
  );
}

Object.assign(window, {
  CompanyMark, StatusBadge, Btn, Field, TextInput, Select, Switch, Check,
  Modal, useToast, PageHead, Empty,
});
