/* global React, Icon */
const { useState: uS, useEffect: uE, useMemo: uM, Fragment: Fr } = React;

// ============== SIDEBAR ==============
function Sidebar({ active, onNav, onLogout, user }) {
  return (
    <aside className="sidebar">
      <div className="sidebar-brand">
        <div className="brand-mark">S</div>
        <div className="brand-text">
          <div className="name">SGL</div>
          <div className="org">BTM · CNPJ 33.804.351</div>
        </div>
      </div>
      <div className="sidebar-search">
        <input className="search-input" placeholder="Buscar  ·  ⌘K" />
      </div>
      <nav className="sidebar-nav">
        <div className="nav-group">
          <div className="nav-group-label">Operação</div>
          {MODULES.slice(0, 6).map(m => (
            <NavItem key={m.id} m={m} active={active === m.id} onClick={() => onNav(m.id)} />
          ))}
        </div>
        <div className="nav-group">
          <div className="nav-group-label">Pós-venda</div>
          {MODULES.slice(6, 8).map(m => (
            <NavItem key={m.id} m={m} active={active === m.id} onClick={() => onNav(m.id)} />
          ))}
        </div>
        <div className="nav-group">
          <div className="nav-group-label">Inteligência</div>
          {MODULES.slice(8, 10).map(m => (
            <NavItem key={m.id} m={m} active={active === m.id} onClick={() => onNav(m.id)} />
          ))}
        </div>
        <div className="nav-group">
          <div className="nav-group-label">Plataforma</div>
          {MODULES.slice(10).map(m => (
            <NavItem key={m.id} m={m} active={active === m.id} onClick={() => onNav(m.id)} />
          ))}
        </div>
      </nav>
      <div className="sidebar-user">
        <div className="avatar">{user?.initials || 'U'}</div>
        <div className="info">
          <div className="n">{user?.displayName || 'Usuário'}</div>
          <div className="r">{user?.role || '—'}</div>
        </div>
        {onLogout && (
          <button
            onClick={onLogout}
            title="Sair"
            style={{ width: 28, height: 28, borderRadius: 5, background: 'transparent', border: '1px solid var(--line-2)', color: 'var(--fg-2)', cursor: 'pointer', display: 'grid', placeItems: 'center', marginLeft: 'auto' }}
          >
            <Icon name="arrowR" size={12} />
          </button>
        )}
      </div>
    </aside>
  );
}

function NavItem({ m, active, onClick }) {
  return (
    <div className={`nav-item${active ? ' active' : ''}`} onClick={onClick}>
      <Icon name={m.icon} size={14} />
      <span>{m.name}</span>
      <span className="num">{m.n}</span>
      {m.badge && <span className="badge">{m.badge}</span>}
      {m.badgeRed && <span className="badge red">{m.badgeRed}</span>}
    </div>
  );
}

// ============== TOPBAR ==============
function Topbar({ moduleId, crumbs, right, onNav, onMenuClick }) {
  const mod = MODULES.find(m => m.id === moduleId);
  const [showNotif, setShowNotif] = uS(false);
  return (
    <div className="topbar">
      {onMenuClick && (
        <button className="topbar-hamburger" onClick={onMenuClick} aria-label="Abrir menu">
          <Icon name="menu" size={18} />
        </button>
      )}
      <div className="crumbs">
        {mod && <span className="mod-num">M{mod.n}</span>}
        <span>{mod?.name || ''}</span>
        {crumbs && crumbs.map((c, i) => (
          <Fr key={i}>
            <span className="sep">/</span>
            <span className={i === crumbs.length - 1 ? 'cur' : ''}>{c}</span>
          </Fr>
        ))}
      </div>
      <div className="topbar-actions">
        {right}
        <div
          className="tb-pill clickable"
          role="button" tabIndex={0}
          title="Configurar integração PNCP"
          onClick={() => onNav?.('config')}
          onKeyDown={e => (e.key === 'Enter' || e.key === ' ') && onNav?.('config')}
        ><span className="dot"></span>PNCP · ONLINE</div>
        <div
          className="tb-pill clickable"
          role="button" tabIndex={0}
          title="Abrir Comunicação"
          onClick={() => onNav?.('integracoes')}
          onKeyDown={e => (e.key === 'Enter' || e.key === ' ') && onNav?.('integracoes')}
        ><span className="dot"></span>Gmail · 24 não lidos</div>
        <div style={{ position: 'relative' }}>
          <button
            className="tb-btn has-dot"
            title="Notificações"
            onClick={() => setShowNotif(v => !v)}
          ><Icon name="bell" /></button>
          {showNotif && (
            <>
              <div onClick={() => setShowNotif(false)} style={{ position: 'fixed', inset: 0, zIndex: 90 }}></div>
              <div style={{ position: 'absolute', top: '100%', right: 0, marginTop: 6, width: 320, background: 'var(--bg-1)', border: '1px solid var(--line-2)', borderRadius: 8, boxShadow: '0 12px 32px rgba(0,0,0,0.5)', zIndex: 100, overflow: 'hidden' }}>
                <div className="card-head"><Icon name="bell" /><div className="t">Notificações</div></div>
                <div style={{ padding: 0, maxHeight: 320, overflowY: 'auto' }}>
                  <NotifItem tone="red"   title="CND Municipal vence em 6 dias" sub="Pref. Niterói · habilitação em risco" onClick={() => { setShowNotif(false); onNav?.('auditoria'); }} />
                  <NotifItem tone="amber" title="CND INSS vence em 15 dias"      sub="Receita Federal · renovar"            onClick={() => { setShowNotif(false); onNav?.('auditoria'); }} />
                  <NotifItem tone="cyan"  title="3 pregões agendados"            sub="Próximos 7 dias"                      onClick={() => { setShowNotif(false); onNav?.('disputa'); }} />
                  <NotifItem tone="lime"  title="Backup diário concluído"        sub="12.4 MB · há 2h"                      onClick={() => setShowNotif(false)} />
                </div>
                <div style={{ padding: 10, borderTop: '1px solid var(--line-1)', textAlign: 'center' }}>
                  <button className="btn btn-ghost btn-sm" onClick={() => { setShowNotif(false); onNav?.('auditoria'); }}>Ver todas no M12</button>
                </div>
              </div>
            </>
          )}
        </div>
        <button
          className="tb-btn"
          title="Configurações"
          onClick={() => onNav?.('config')}
        ><Icon name="settings" /></button>
      </div>
    </div>
  );
}

function NotifItem({ tone, title, sub, onClick }) {
  const cols = { red: 'var(--red)', amber: 'var(--amber)', cyan: 'var(--cyan)', lime: 'var(--lime)' };
  return (
    <div className="clickable" role="button" tabIndex={0} onClick={onClick} onKeyDown={e => (e.key === 'Enter' || e.key === ' ') && onClick()} style={{ padding: '10px 14px', borderBottom: '1px solid var(--line-1)', display: 'flex', gap: 10, alignItems: 'flex-start' }}>
      <span style={{ width: 8, height: 8, borderRadius: '50%', background: cols[tone], marginTop: 5, flexShrink: 0 }}></span>
      <div style={{ flex: 1 }}>
        <div style={{ fontSize: 12, fontWeight: 500, color: 'var(--fg-0)' }}>{title}</div>
        <div style={{ fontSize: 11, color: 'var(--fg-3)', marginTop: 2 }}>{sub}</div>
      </div>
    </div>
  );
}

// ============== TICKER ==============
let _tickerCache = null;
let _tickerCacheAt = 0;
const TICKER_TTL_MS = 60000;

function Ticker() {
  const [stats, setStats] = uS(_tickerCache);

  uE(() => {
    let mounted = true;
    const load = async () => {
      const now = Date.now();
      if (_tickerCache && (now - _tickerCacheAt) < TICKER_TTL_MS) {
        setStats(_tickerCache);
        return;
      }
      try {
        const data = await window.dataApi.getTickerStats();
        if (!mounted) return;
        _tickerCache = data;
        _tickerCacheAt = Date.now();
        setStats(data);
      } catch (_) { /* silencioso — ticker é decorativo */ }
    };
    load();
    const intv = setInterval(load, TICKER_TTL_MS);
    return () => { mounted = false; clearInterval(intv); };
  }, []);

  const items = stats ? [
    { l: 'Editais ativos', v: String(stats.editaisAtivos), cls: '' },
    { l: 'Empenhos ativos', v: String(stats.empenhosAtivos), cls: '' },
    { l: 'A receber', v: BRL(stats.aReceber), cls: 'up' },
    ...(stats.cndDias !== null ? [{ l: 'Próx. CND vence em', v: `${stats.cndDias}d`, cls: stats.cndDias <= 10 ? 'dn' : '' }] : []),
    { l: 'Lances hoje', v: String(stats.lancesHoje), cls: '' },
  ] : [];

  return (
    <div className="ticker">
      <span className="dot-pulse" style={{ flexShrink: 0 }}></span>
      <span style={{ color: 'var(--fg-3)' }}>LIVE</span>
      {items.map((t, i) => (
        <span key={i} className="ticker-item">
          <span>{t.l}</span>
          <span className={`v ${t.cls || ''}`}>{t.v}</span>
        </span>
      ))}
    </div>
  );
}

// ============== SHARED COMPONENTS ==============
function Sparkline({ data, color = 'lime', w = 90, h = 26, filled = true }) {
  const max = Math.max(...data);
  const min = Math.min(...data);
  const r = max - min || 1;
  const step = w / (data.length - 1);
  const pts = data.map((v, i) => [i * step, h - 2 - ((v - min) / r) * (h - 4)]);
  const path = pts.map((p, i) => `${i === 0 ? 'M' : 'L'}${p[0].toFixed(1)},${p[1].toFixed(1)}`).join(' ');
  const fill = `${path} L ${w},${h} L 0,${h} Z`;
  const cls = color === 'red' ? 'red' : color === 'cyan' ? 'cyan' : '';
  return (
    <svg width={w} height={h}>
      {filled && <path d={fill} className={`spark-fill ${cls}`} fill={color === 'red' ? 'rgba(255,93,93,0.12)' : color === 'cyan' ? 'rgba(106,215,229,0.12)' : 'rgba(212,247,82,0.12)'} />}
      <path d={path} className={`spark ${cls}`} />
    </svg>
  );
}

function Avatar({ initials, color, size = 22 }) {
  return (
    <div className="avatar" style={{ width: size, height: size, background: color, fontSize: size * 0.4 }}>{initials}</div>
  );
}

function StatusPill({ status }) {
  const map = {
    novo: { l: 'NOVO', c: 'var(--fg-2)' },
    analise: { l: 'ANÁLISE', c: 'var(--cyan)' },
    precificacao: { l: 'PRECIF.', c: 'var(--amber)' },
    disputa: { l: 'DISPUTA', c: 'var(--red)' },
    ganho: { l: 'GANHO', c: 'var(--lime)' },
    descartado: { l: 'DESCART.', c: 'var(--fg-4)' },
  };
  const s = map[status] || map.novo;
  return <span className="status-pill"><span className="d" style={{ background: s.c }}></span>{s.l}</span>;
}

function ScoreDial({ score }) {
  const color = score >= 85 ? 'var(--lime)' : score >= 70 ? 'var(--amber)' : 'var(--fg-3)';
  const r = 10;
  const c = 2 * Math.PI * r;
  const off = c - (score / 100) * c;
  return (
    <div style={{ position: 'relative', width: 28, height: 28 }}>
      <svg width="28" height="28" style={{ transform: 'rotate(-90deg)' }}>
        <circle cx="14" cy="14" r={r} stroke="var(--bg-3)" strokeWidth="2.5" fill="none" />
        <circle cx="14" cy="14" r={r} stroke={color} strokeWidth="2.5" fill="none" strokeDasharray={c} strokeDashoffset={off} strokeLinecap="round" />
      </svg>
      <div style={{ position: 'absolute', inset: 0, display: 'grid', placeItems: 'center', fontFamily: 'IBM Plex Mono', fontSize: 9, fontWeight: 600, color }}>{score}</div>
    </div>
  );
}

function Toggle({ on, onToggle }) {
  return <div className={`toggle${on ? ' on' : ''}`} onClick={onToggle}></div>;
}

function Section({ title, sub, right, children, padTop }) {
  return (
    <section style={{ marginTop: padTop || 22, marginBottom: 14 }}>
      <div className="flex items-center justify-between" style={{ marginBottom: 10 }}>
        <div>
          <div className="eyebrow">{sub}</div>
          <div style={{ fontSize: 15, fontWeight: 600, letterSpacing: '-0.01em' }}>{title}</div>
        </div>
        {right}
      </div>
      {children}
    </section>
  );
}

// ============== DRAWER ==============
function Drawer({ open, onClose, title, subtitle, eyebrow, width, headRight, tabs, activeTab, onTabChange, footer, children }) {
  uE(() => {
    if (!open) return;
    const onKey = e => { if (e.key === 'Escape') onClose(); };
    document.addEventListener('keydown', onKey);
    const prevOverflow = document.body.style.overflow;
    document.body.style.overflow = 'hidden';
    return () => {
      document.removeEventListener('keydown', onKey);
      document.body.style.overflow = prevOverflow;
    };
  }, [open, onClose]);

  if (!open) return null;

  return (
    <Fr>
      <div className="drawer-backdrop" onClick={onClose}></div>
      <div className="drawer" role="dialog" aria-modal="true" style={width ? { width } : undefined}>
        <div className="drawer-head">
          <div style={{ minWidth: 0, flex: 1 }}>
            {eyebrow && <div className="eyebrow" style={{ marginBottom: 4 }}>{eyebrow}</div>}
            <div className="t" style={{ overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{title}</div>
            {subtitle && <div className="s" style={{ marginTop: 2 }}>{subtitle}</div>}
          </div>
          {headRight}
          <button className="drawer-close" onClick={onClose} aria-label="Fechar">
            <Icon name="x" size={14} />
          </button>
        </div>
        {tabs && tabs.length > 0 && (
          <div className="drawer-tabs">
            {tabs.map(t => (
              <div key={t.id} className={`drawer-tab${activeTab === t.id ? ' active' : ''}`} onClick={() => onTabChange(t.id)}>
                {t.label}
                {t.count !== undefined && <span className="count">{t.count}</span>}
              </div>
            ))}
          </div>
        )}
        <div className="drawer-body">{children}</div>
        {footer && <div className="drawer-foot">{footer}</div>}
      </div>
    </Fr>
  );
}

Object.assign(window, { Sidebar, Topbar, Ticker, Sparkline, Avatar, StatusPill, ScoreDial, Toggle, Section, Drawer });
