// ═══════════════════════════════════════════════════════════════════
// UI primitives — Escalab Design System v2
// Inter + Instrument Serif, verde âncora #00967B, sem ribbons/gloss
// ═══════════════════════════════════════════════════════════════════

const { useState, useMemo, useEffect, useRef } = React;

// ─── Pequenos átomos visuais ──────────────────────────────────────
const Dot = () => (
  <svg width="22" height="22" viewBox="0 0 32 32" fill="none" aria-hidden="true">
    <path d="M4 20 Q 16 2, 28 20" stroke="currentColor" strokeWidth="3" strokeLinecap="round"/>
    <circle cx="16" cy="22" r="3" fill="currentColor"/>
  </svg>
);

const Chev = ({ dir = 'right' }) => {
  const rot = { right: 0, down: 90, left: 180, up: -90 }[dir];
  return <svg width="14" height="14" viewBox="0 0 24 24" style={{ transform: `rotate(${rot}deg)` }} fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M9 6l6 6-6 6"/></svg>;
};

const Icon = ({ name, size = 18 }) => {
  const paths = {
    home:     <><path d="M3 11l9-8 9 8"/><path d="M5 10v10h14V10"/></>,
    rules:    <><path d="M4 6h16M4 12h16M4 18h10"/></>,
    leads:    <><circle cx="9" cy="9" r="4"/><path d="M3 21v-2a4 4 0 0 1 4-4h4a4 4 0 0 1 4 4v2"/><path d="M17 11l2 2 4-4"/></>,
    chart:    <><path d="M4 20V10M10 20V4M16 20v-7M22 20H2"/></>,
    user:     <><circle cx="12" cy="8" r="4"/><path d="M4 21v-1a6 6 0 0 1 6-6h4a6 6 0 0 1 6 6v1"/></>,
    history:  <><path d="M3 12a9 9 0 1 0 3-6.7"/><path d="M3 4v5h5"/><path d="M12 7v5l3 2"/></>,
    lock:     <><rect x="5" y="11" width="14" height="10" rx="2"/><path d="M8 11V8a4 4 0 0 1 8 0v3"/></>,
    close:    <><path d="M6 6l12 12M18 6L6 18"/></>,
    plus:     <><path d="M12 5v14M5 12h14"/></>,
    edit:     <><path d="M14 4l6 6-12 12H2v-6z"/></>,
    check:    <><path d="M5 12l4 4L19 6"/></>,
    download: <><path d="M12 3v14M5 12l7 7 7-7"/><path d="M4 21h16"/></>,
    search:   <><circle cx="11" cy="11" r="7"/><path d="M20 20l-3.5-3.5"/></>,
    filter:   <><path d="M4 5h16l-6 8v6l-4-2v-4z"/></>,
    lock_o:   <><rect x="5" y="11" width="14" height="10" rx="2"/><path d="M8 11V8a4 4 0 0 1 4-4"/></>,
    mail:     <><rect x="3" y="5" width="18" height="14" rx="2"/><path d="M3 7l9 6 9-6"/></>,
    eye:      <><path d="M2 12s4-7 10-7 10 7 10 7-4 7-10 7-10-7-10-7z"/><circle cx="12" cy="12" r="3"/></>,
    menu:     <><path d="M4 6h16M4 12h16M4 18h16"/></>,
    warn:     <><path d="M12 3l10 18H2z"/><path d="M12 10v5M12 18v.5"/></>,
    info:     <><circle cx="12" cy="12" r="9"/><path d="M12 8v.5M12 11v5"/></>,
    copy:     <><rect x="9" y="9" width="12" height="12" rx="2"/><path d="M5 15V5a2 2 0 0 1 2-2h8"/></>,
    send:     <><path d="M4 12l16-8-5 18-4-8z"/></>,
    calc:     <><rect x="5" y="3" width="14" height="18" rx="2"/><path d="M9 7h6M8 12h.5M12 12h.5M16 12h.5M8 16h.5M12 16h.5M16 16h.5"/></>,
  };
  return <svg width={size} height={size} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round">{paths[name]}</svg>;
};

const Avatar = ({ v, size = 36 }) => (
  <div style={{ width: size, height: size, borderRadius: '50%', background: v.cor, color: '#fff', display: 'flex', alignItems: 'center', justifyContent: 'center', fontWeight: 600, fontSize: size * 0.38, letterSpacing: '.02em', flexShrink: 0 }}>
    {v.iniciais}
  </div>
);

const Tag = ({ children, tone = 'neutral' }) => {
  const tones = {
    neutral:    { bg: 'rgba(74,85,96,.08)',   fg: 'var(--escalab-slate)',     border: 'transparent' },
    brand:      { bg: 'var(--escalab-brand-tint)', fg: 'var(--escalab-brand-deep)', border: 'var(--escalab-brand-soft)' },
    success:    { bg: '#E6F5F1', fg: '#00836B', border: 'var(--escalab-brand-soft)' },
    warn:       { bg: '#FFF4E6', fg: '#B56500', border: '#FFD6A3' },
    danger:     { bg: '#FDECEC', fg: '#B3261E', border: '#F4C7C3' },
    info:       { bg: '#EEF3FA', fg: '#1F4A8A', border: '#C9D7EC' },
    outline:    { bg: 'transparent', fg: 'var(--escalab-slate)', border: 'var(--escalab-line)' },
    dark:       { bg: 'var(--escalab-ink)', fg: '#fff', border: 'transparent' },
  };
  const t = tones[tone];
  return (
    <span style={{ display: 'inline-flex', alignItems: 'center', gap: 6, fontSize: 11.5, fontWeight: 600, letterSpacing: '.04em', textTransform: 'uppercase', padding: '4px 9px', borderRadius: 6, background: t.bg, color: t.fg, border: `1px solid ${t.border}`, whiteSpace: 'nowrap' }}>{children}</span>
  );
};

const Button = ({ variant = 'primary', size = 'md', icon, iconRight, children, onClick, disabled, style, type = 'button' }) => {
  const sizes = { sm: { padding: '7px 14px', fontSize: 13 }, md: { padding: '10px 18px', fontSize: 14 }, lg: { padding: '13px 22px', fontSize: 15 } };
  const variants = {
    primary: { background: 'var(--escalab-brand)', color: '#fff', border: '1px solid var(--escalab-brand)' },
    dark:    { background: 'var(--escalab-ink)', color: '#fff', border: '1px solid var(--escalab-ink)' },
    outline: { background: '#fff', color: 'var(--escalab-brand-deep)', border: '1px solid var(--escalab-line)' },
    ghost:   { background: 'transparent', color: 'var(--escalab-slate)', border: '1px solid transparent' },
    danger:  { background: '#fff', color: '#B3261E', border: '1px solid #F4C7C3' },
  };
  return (
    <button type={type} onClick={onClick} disabled={disabled} style={{ display: 'inline-flex', alignItems: 'center', gap: 8, borderRadius: 8, fontWeight: 500, letterSpacing: '-.005em', fontFamily: 'var(--font-sans)', cursor: disabled ? 'not-allowed' : 'pointer', opacity: disabled ? 0.5 : 1, transition: 'all .18s var(--ease-out)', ...sizes[size], ...variants[variant], ...style }}>
      {icon && <Icon name={icon} size={size === 'sm' ? 14 : 16} />}
      <span>{children}</span>
      {iconRight && <Icon name={iconRight} size={size === 'sm' ? 14 : 16} />}
    </button>
  );
};

const Card = ({ children, pad = 24, style, onClick }) => (
  <div onClick={onClick} style={{ background: '#fff', border: '1px solid var(--escalab-line)', borderRadius: 12, padding: pad, cursor: onClick ? 'pointer' : 'default', ...style }}>
    {children}
  </div>
);

const Stat = ({ label, value, sublabel, tone = 'dark', trend }) => {
  const colors = tone === 'dark' ? { bg: 'var(--escalab-ink)', fg: '#fff', sub: 'rgba(255,255,255,.65)' } : { bg: '#fff', fg: 'var(--escalab-brand-deep)', sub: 'var(--escalab-slate)' };
  return (
    <div style={{ background: colors.bg, border: '1px solid var(--escalab-line)', borderRadius: 12, padding: '22px 24px' }}>
      <div style={{ fontSize: 11, fontWeight: 600, letterSpacing: '.12em', textTransform: 'uppercase', color: colors.sub, marginBottom: 12 }}>{label}</div>
      <div style={{ fontFamily: 'var(--font-sans)', fontSize: 36, fontWeight: 700, letterSpacing: '-.02em', color: colors.fg, lineHeight: 1 }}>{value}</div>
      {sublabel && <div style={{ fontSize: 12.5, color: colors.sub, marginTop: 8 }}>{sublabel}</div>}
      {trend != null && (
        <div style={{ display: 'inline-flex', alignItems: 'center', gap: 4, marginTop: 10, fontSize: 11.5, fontWeight: 600, color: trend >= 0 ? 'var(--escalab-brand-accent)' : '#FFB4B0' }}>
          {trend >= 0 ? '▲' : '▼'} {Math.abs(trend).toFixed(1)}% vs. trimestre anterior
        </div>
      )}
    </div>
  );
};

const Field = ({ label, hint, children, span }) => (
  <div style={{ display: 'flex', flexDirection: 'column', gap: 6, gridColumn: span ? `span ${span}` : undefined }}>
    <label style={{ fontSize: 11, fontWeight: 600, letterSpacing: '.1em', textTransform: 'uppercase', color: 'var(--escalab-slate)' }}>{label}</label>
    {children}
    {hint && <div style={{ fontSize: 12, color: 'var(--escalab-mute)' }}>{hint}</div>}
  </div>
);

const Input = ({ value, onChange, type = 'text', placeholder, prefix, suffix, style }) => (
  <div style={{ display: 'flex', alignItems: 'center', border: '1px solid var(--escalab-line)', borderRadius: 8, background: '#fff', overflow: 'hidden', ...style }}>
    {prefix && <span style={{ padding: '0 10px 0 12px', color: 'var(--escalab-mute)', fontSize: 14 }}>{prefix}</span>}
    <input value={value ?? ''} onChange={e => onChange?.(e.target.value)} type={type} placeholder={placeholder} style={{ border: 0, outline: 0, flex: 1, padding: '10px 12px', fontSize: 14, fontFamily: 'var(--font-sans)', background: 'transparent', color: 'var(--escalab-ink)' }} />
    {suffix && <span style={{ padding: '0 12px 0 6px', color: 'var(--escalab-mute)', fontSize: 13 }}>{suffix}</span>}
  </div>
);

const Select = ({ value, onChange, options, placeholder }) => (
  <div style={{ position: 'relative', border: '1px solid var(--escalab-line)', borderRadius: 8, background: '#fff' }}>
    <select value={value ?? ''} onChange={e => onChange?.(e.target.value)} style={{ width: '100%', border: 0, outline: 0, padding: '10px 36px 10px 12px', fontSize: 14, fontFamily: 'var(--font-sans)', background: 'transparent', appearance: 'none', color: 'var(--escalab-ink)' }}>
      {placeholder && <option value="">{placeholder}</option>}
      {options.map(o => <option key={o.value} value={o.value}>{o.label}</option>)}
    </select>
    <div style={{ position: 'absolute', right: 10, top: '50%', transform: 'translateY(-50%)', pointerEvents: 'none', color: 'var(--escalab-slate)' }}><Chev dir="down" /></div>
  </div>
);

const Toggle = ({ checked, onChange, label }) => (
  <label style={{ display: 'inline-flex', alignItems: 'center', gap: 10, cursor: 'pointer', userSelect: 'none' }}>
    <span style={{ position: 'relative', width: 36, height: 20, background: checked ? 'var(--escalab-brand)' : '#D4D8DC', borderRadius: 999, transition: 'all .18s' }}>
      <span style={{ position: 'absolute', top: 2, left: checked ? 18 : 2, width: 16, height: 16, background: '#fff', borderRadius: '50%', transition: 'all .18s', boxShadow: '0 1px 2px rgba(0,0,0,.15)' }} />
    </span>
    {label && <span style={{ fontSize: 13.5, color: 'var(--escalab-slate)' }}>{label}</span>}
    <input type="checkbox" checked={checked} onChange={e => onChange?.(e.target.checked)} style={{ position: 'absolute', opacity: 0, pointerEvents: 'none' }} />
  </label>
);

// Progress bar
const Progress = ({ value, max, tone = 'brand' }) => {
  const pctV = Math.min(100, (value / max) * 100);
  const color = { brand: 'var(--escalab-brand)', mint: 'var(--escalab-brand-accent)', warn: '#E89B3B' }[tone];
  return (
    <div style={{ width: '100%', height: 6, background: 'var(--escalab-line)', borderRadius: 999, overflow: 'hidden' }}>
      <div style={{ width: pctV + '%', height: '100%', background: color, transition: 'width .4s var(--ease-out)' }} />
    </div>
  );
};

// Eyebrow (index + label)
const Eyebrow = ({ idx, children }) => (
  <div style={{ display: 'inline-flex', alignItems: 'center', gap: 10, fontSize: 11, fontWeight: 600, letterSpacing: '.14em', textTransform: 'uppercase', color: 'var(--escalab-slate)', marginBottom: 14 }}>
    <span style={{ color: 'var(--escalab-brand)' }}>{idx}</span>
    <span style={{ width: 1, height: 10, background: 'var(--escalab-line)' }} />
    <span>{children}</span>
  </div>
);

// Toast / inline notification
const Banner = ({ tone = 'info', icon = 'info', children, onClose }) => {
  const styles = {
    info:    { bg: '#EEF3FA', fg: '#1F4A8A', border: '#C9D7EC' },
    success: { bg: 'var(--escalab-brand-tint)', fg: 'var(--escalab-brand-deep)', border: 'var(--escalab-brand-soft)' },
    warn:    { bg: '#FFF7EB', fg: '#7A4A00', border: '#FFD6A3' },
  };
  const s = styles[tone];
  return (
    <div style={{ display: 'flex', gap: 12, alignItems: 'flex-start', background: s.bg, border: `1px solid ${s.border}`, color: s.fg, padding: '12px 16px', borderRadius: 10 }}>
      <div style={{ flexShrink: 0, marginTop: 1 }}><Icon name={icon} size={17} /></div>
      <div style={{ flex: 1, fontSize: 13.5, lineHeight: 1.5 }}>{children}</div>
      {onClose && <button onClick={onClose} style={{ border: 0, background: 'transparent', cursor: 'pointer', color: 'inherit', opacity: .6 }}><Icon name="close" size={14} /></button>}
    </div>
  );
};

// Modal
const Modal = ({ open, onClose, title, children, width = 560, footer }) => {
  if (!open) return null;
  return (
    <div onClick={onClose} style={{ position: 'fixed', inset: 0, background: 'rgba(10,15,18,.55)', display: 'flex', alignItems: 'center', justifyContent: 'center', zIndex: 1000, padding: 20, animation: 'fadeIn .18s var(--ease-out)' }}>
      <div onClick={e => e.stopPropagation()} style={{ background: '#fff', borderRadius: 14, width: '100%', maxWidth: width, boxShadow: 'var(--shadow-lg)', overflow: 'hidden', animation: 'popIn .22s var(--ease-out)' }}>
        <div style={{ padding: '20px 24px', borderBottom: '1px solid var(--escalab-line)', display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
          <h3 style={{ fontSize: 18, fontWeight: 600, margin: 0, letterSpacing: '-.01em' }}>{title}</h3>
          <button onClick={onClose} style={{ border: 0, background: 'transparent', cursor: 'pointer', color: 'var(--escalab-slate)', padding: 4 }}><Icon name="close" size={18} /></button>
        </div>
        <div style={{ padding: 24, maxHeight: '70vh', overflowY: 'auto' }}>{children}</div>
        {footer && <div style={{ padding: '14px 24px', borderTop: '1px solid var(--escalab-line)', background: 'var(--escalab-paper)', display: 'flex', justifyContent: 'flex-end', gap: 10 }}>{footer}</div>}
      </div>
    </div>
  );
};

function useMobile() {
  const [w, setW] = React.useState(window.innerWidth);
  React.useEffect(() => {
    const h = () => setW(window.innerWidth);
    window.addEventListener('resize', h);
    return () => window.removeEventListener('resize', h);
  }, []);
  return { isMobile: w <= 768, isTablet: w <= 1100 };
}

Object.assign(window, { Dot, Icon, Chev, Avatar, Tag, Button, Card, Stat, Field, Input, Select, Toggle, Progress, Eyebrow, Banner, Modal, useMobile });
