/* ============================================================
   ZERO — Shared UI components. window.UI
   ============================================================ */
(function () {
  const { useState, useEffect } = React;
  const I = window.Icon;

  const NAV = [
    { id: 'dashboard', label: 'Dashboard', icon: 'grid' },
    { id: 'command', label: 'Central de Comando', icon: 'cpu' },
    { id: 'roadmap', label: 'Roadmap & Produto', icon: 'map' },
    { id: 'marketing', label: 'Marketing', icon: 'mega' },
    { id: 'sales', label: 'Pipeline de Vendas', icon: 'funnel' },
    { id: 'support', label: 'Suporte ao Cliente', icon: 'headset' },
    { id: 'settings', label: 'Configurações', icon: 'cog' },
  ];

  const BUILD_NAV = [
    { id: 'agentbuilder', label: 'Criar Agente', icon: 'wand' },
    { id: 'teambuilder', label: 'Montar Equipe', icon: 'network' },
    { id: 'marketplace', label: 'Marketplace', icon: 'store' },
  ];

  // ---------- Logo ----------
  function Logo({ size = 30 }) {
    return (
      <div className="row gap10">
        <div style={{ width: size, height: size, borderRadius: 9, position: 'relative',
          background: 'linear-gradient(140deg, var(--violet-2), var(--violet))',
          boxShadow: '0 4px 16px oklch(0.64 0.17 288 / 0.45), 0 1px 0 oklch(1 0 0 /.25) inset',
          display: 'grid', placeItems: 'center', flex: 'none' }}>
          <div style={{ position: 'absolute', inset: 0, borderRadius: 9,
            background: 'conic-gradient(from 200deg, transparent, oklch(1 0 0 /.25), transparent 60%)' }} />
          <span style={{ fontWeight: 800, fontSize: size * 0.5, color: 'white', letterSpacing: '-0.05em', zIndex: 1 }}>0</span>
        </div>
      </div>
    );
  }

  // ---------- Sidebar ----------
  function Sidebar({ active, onNav, onLanding }) {
    const agents = window.DATA.agents;
    return (
      <aside style={{ width: 'var(--sidebar-w)', flex: 'none', height: '100%', display: 'flex', flexDirection: 'column',
        borderRight: '1px solid var(--line)', background: 'oklch(0.16 0.013 265 / 0.6)', backdropFilter: 'blur(12px)' }}>
        <div className="row between" style={{ padding: '16px 18px 14px' }}>
          <div className="row gap10">
            <Logo />
            <div>
              <div style={{ fontWeight: 800, fontSize: 15, letterSpacing: '-0.03em' }}>Zero</div>
              <div style={{ fontSize: 10.5, color: 'var(--tx-2)', marginTop: -2 }}>Equipe autônoma de IA</div>
            </div>
          </div>
        </div>

        <nav style={{ padding: '6px 12px', display: 'flex', flexDirection: 'column', gap: 2 }}>
          {NAV.map(n => <NavBtn key={n.id} n={n} on={active === n.id} onNav={onNav} />)}
          <div className="eyebrow" style={{ margin: '14px 0 6px', paddingLeft: 11 }}>Construtor</div>
          {BUILD_NAV.map(n => <NavBtn key={n.id} n={n} on={active === n.id} onNav={onNav} />)}
        </nav>

        <div style={{ padding: '14px 16px 8px' }}>
          <div className="eyebrow" style={{ marginBottom: 10, paddingLeft: 4 }}>Agentes ao vivo</div>
          <div style={{ display: 'flex', flexDirection: 'column', gap: 3 }}>
            {agents.map(a => <MiniAgent key={a.id} a={a} onClick={() => onNav('command')} />)}
          </div>
        </div>

        <div style={{ marginTop: 'auto', padding: 12 }}>
          <button onClick={onLanding} className="row gap8" style={{ width: '100%', justifyContent: 'center', padding: '9px',
            borderRadius: 9, cursor: 'pointer', border: '1px solid var(--line)', background: 'var(--bg-1)', color: 'var(--tx-2)', fontSize: 12.5, fontWeight: 600 }}>
            <I.eye w={15} /> Ver landing page
          </button>
          <div className="row gap10" style={{ marginTop: 12, padding: '8px 6px', borderRadius: 10 }}>
            <div className="avatar" style={{ background: 'linear-gradient(140deg, var(--teal), var(--blue))' }}>JD</div>
            <div className="grow">
              <div style={{ fontSize: 12.5, fontWeight: 700 }}>Jordan Diaz</div>
              <div style={{ fontSize: 10.5, color: 'var(--tx-2)' }}>Founder · Pro</div>
            </div>
            <span style={{ color: 'var(--tx-3)' }}><I.chevDown w={15} /></span>
          </div>
        </div>
      </aside>
    );
  }

  function NavBtn({ n, on, onNav }) {
    const Ic = I[n.icon];
    return (
      <button onClick={() => onNav(n.id)} className="row gap10"
        style={{ width: '100%', textAlign: 'left', padding: '9px 11px', borderRadius: 9, cursor: 'pointer',
          border: '1px solid ' + (on ? 'var(--line)' : 'transparent'),
          background: on ? 'linear-gradient(100deg, var(--violet-soft), transparent)' : 'transparent',
          color: on ? 'var(--tx-0)' : 'var(--tx-2)', fontSize: 13.5, fontWeight: on ? 700 : 500,
          position: 'relative', transition: 'all .14s ease' }}
        onMouseEnter={e => { if (!on) { e.currentTarget.style.background = 'var(--bg-2)'; e.currentTarget.style.color = 'var(--tx-1)'; } }}
        onMouseLeave={e => { if (!on) { e.currentTarget.style.background = 'transparent'; e.currentTarget.style.color = 'var(--tx-2)'; } }}>
        {on && <span style={{ position: 'absolute', left: -12, top: '50%', transform: 'translateY(-50%)', width: 3, height: 18, borderRadius: 4, background: 'var(--violet-2)' }} />}
        <span style={{ color: on ? 'var(--violet-2)' : 'inherit', display: 'grid', placeItems: 'center' }}><Ic w={17} /></span>
        {n.label}
      </button>
    );
  }

  function MiniAgent({ a, onClick }) {    const sc = statusColor(a.status);
    return (
      <button onClick={onClick} className="row gap8" style={{ width: '100%', padding: '6px 8px', borderRadius: 8, cursor: 'pointer',
        border: '1px solid transparent', background: 'transparent', textAlign: 'left' }}
        onMouseEnter={e => e.currentTarget.style.background = 'var(--bg-2)'}
        onMouseLeave={e => e.currentTarget.style.background = 'transparent'}>
        <span className="avatar" style={{ width: 22, height: 22, fontSize: 9.5, background: a.hue, color: 'white' }}>{a.name[0]}</span>
        <span className="grow ellipsis" style={{ fontSize: 12, fontWeight: 600, color: 'var(--tx-1)' }}>{a.name}</span>
        <span className="dot" style={{ background: sc, color: sc, ...(a.status === 'executing' || a.status === 'thinking' ? {} : {}) }} />
      </button>
    );
  }

  function statusColor(s) {
    return s === 'executing' ? 'var(--green)' : s === 'thinking' ? 'var(--violet-2)' : s === 'online' ? 'var(--teal)' : 'var(--tx-3)';
  }

  // ---------- Topbar ----------
  function Topbar({ title, sub, onMenu }) {
    return (
      <header className="row between" style={{ height: 'var(--topbar-h)', flex: 'none', padding: '0 24px 0 30px',
        borderBottom: '1px solid var(--line)', background: 'oklch(0.16 0.013 265 / 0.5)', backdropFilter: 'blur(14px)', position: 'sticky', top: 0, zIndex: 20 }}>
        <div className="row gap12">
          <div>
            <div className="h2">{title}</div>
            {sub && <div style={{ fontSize: 12, color: 'var(--tx-2)', marginTop: -1 }}>{sub}</div>}
          </div>
        </div>
        <div className="row gap10">
          <div className="row gap8" style={{ padding: '7px 12px', borderRadius: 9, border: '1px solid var(--line)', background: 'var(--bg-1)', color: 'var(--tx-3)', width: 230 }}>
            <I.search w={15} />
            <span style={{ fontSize: 12.5 }}>Buscar ou perguntar à Zero…</span>
            <span className="mono" style={{ marginLeft: 'auto', fontSize: 10, padding: '1px 5px', borderRadius: 4, border: '1px solid var(--line)', color: 'var(--tx-3)' }}>⌘K</span>
          </div>
          <button className="btn btn-icon" style={{ position: 'relative' }}>
            <I.bell w={16} />
            <span style={{ position: 'absolute', top: 7, right: 8, width: 7, height: 7, borderRadius: 9, background: 'var(--rose)', border: '2px solid var(--bg-0)' }} />
          </button>
          <button className="btn btn-primary btn-sm"><I.sparkle w={15} /> Nova tarefa</button>
        </div>
      </header>
    );
  }

  // ---------- Reusable bits ----------
  function Badge({ children, color = 'var(--tx-2)', soft, dot }) {
    return (
      <span className="badge" style={{
        color: color, borderColor: soft ? 'transparent' : 'var(--line)',
        background: soft || 'transparent' }}>
        {dot && <span className="dot" style={{ background: color }} />}
        {children}
      </span>
    );
  }

  function StatusBadge({ status }) {
    const map = {
      executing: ['var(--green)', 'var(--green-soft)', 'Executando'],
      thinking: ['var(--violet-2)', 'var(--violet-soft)', 'Pensando'],
      online: ['var(--teal)', 'var(--teal-soft)', 'Online'],
      idle: ['var(--tx-2)', 'oklch(1 0 0 /.06)', 'Ocioso'],
    };
    const [c, bg, label] = map[status] || map.idle;
    const live = status === 'executing' || status === 'thinking';
    return (
      <span className="badge" style={{ color: c, background: bg, borderColor: 'transparent' }}>
        <span className={'dot' + (live ? ' dot-pulse' : '')} style={{ background: c, color: c }} />
        {label}
      </span>
    );
  }

  function Card({ children, className = '', style, ...rest }) {
    return <div className={'panel lift ' + className} style={{ padding: 18, ...style }} {...rest}>{children}</div>;
  }

  function SectionHead({ icon, title, action, sub }) {
    const Ic = icon ? I[icon] : null;
    return (
      <div className="row between" style={{ marginBottom: 14 }}>
        <div className="row gap10">
          {Ic && <span style={{ color: 'var(--tx-2)' }}><Ic w={17} /></span>}
          <div>
            <div className="h3">{title}</div>
            {sub && <div style={{ fontSize: 11.5, color: 'var(--tx-2)' }}>{sub}</div>}
          </div>
        </div>
        {action}
      </div>
    );
  }

  // priority pill
  function Priority({ level }) {
    const m = { 'Crítico': 'var(--rose)', Alto: 'var(--amber)', 'Médio': 'var(--teal)', Baixo: 'var(--tx-2)', Critical: 'var(--rose)', High: 'var(--amber)', Med: 'var(--teal)', Medium: 'var(--teal)', Low: 'var(--tx-2)' };
    const c = m[level] || 'var(--tx-2)';
    return <span className="badge" style={{ color: c, borderColor: 'transparent', background: `color-mix(in oklab, ${c}, transparent 86%)`, fontSize: 10.5, padding: '2px 7px' }}>{level}</span>;
  }

  function Toggle({ on, onChange }) {
    return (
      <button onClick={() => onChange(!on)} style={{ width: 38, height: 22, borderRadius: 99, padding: 2, cursor: 'pointer',
        border: '1px solid ' + (on ? 'transparent' : 'var(--line-strong)'),
        background: on ? 'linear-gradient(180deg, var(--violet-2), var(--violet))' : 'var(--bg-3)', transition: 'all .2s ease', position: 'relative' }}>
        <span style={{ display: 'block', width: 16, height: 16, borderRadius: 99, background: 'white',
          transform: on ? 'translateX(16px)' : 'translateX(0)', transition: 'transform .2s cubic-bezier(.2,.7,.2,1)',
          boxShadow: '0 1px 3px oklch(0 0 0 /.4)' }} />
      </button>
    );
  }

  // typing dots
  function Typing({ color = 'var(--tx-2)' }) {
    return (
      <span className="row gap4" style={{ alignItems: 'center' }}>
        {[0,1,2].map(i => <span key={i} style={{ width: 5, height: 5, borderRadius: 9, background: color,
          animation: `blink 1.2s ${i*0.18}s infinite` }} />)}
      </span>
    );
  }

  window.UI = { Sidebar, Topbar, Badge, StatusBadge, Card, SectionHead, Priority, Toggle, Logo, Typing, statusColor, NAV };
})();
