/* DEV module — dense, dark-first. Vercel/Linear/Langfuse/Grafana vibe.
   Exports: DevOverview, DevCosts, DevArchitecture, DevShell
   Reuses: Icon, DigiMark, ChatDrawer */

// ============ Utilities ============
const Spark = ({ data, width = 120, height = 28, stroke = 'var(--ai-500)', fill = 'color-mix(in oklch, var(--ai-500) 18%, transparent)' }) => {
  if (!data?.length) return null;
  const max = Math.max(...data), min = Math.min(...data);
  const range = max - min || 1;
  const pts = data.map((v, i) => {
    const x = (i / (data.length - 1)) * width;
    const y = height - ((v - min) / range) * (height - 4) - 2;
    return [x, y];
  });
  const path = pts.map((p, i) => `${i === 0 ? 'M' : 'L'}${p[0].toFixed(1)},${p[1].toFixed(1)}`).join(' ');
  const area = `${path} L${width},${height} L0,${height} Z`;
  return (
    <svg width={width} height={height} style={{ display: 'block' }}>
      <path d={area} fill={fill} />
      <path d={path} fill="none" stroke={stroke} strokeWidth="1.5" />
      <circle cx={pts[pts.length - 1][0]} cy={pts[pts.length - 1][1]} r="2.5" fill={stroke} />
    </svg>
  );
};

const StatusDot = ({ status }) => {
  const c = { ok: 'var(--success)', warn: 'var(--warning)', crit: 'var(--danger)', info: 'var(--info)' }[status] || 'var(--text-dim)';
  return (
    <span style={{ position: 'relative', display: 'inline-block', width: 8, height: 8 }}>
      <span style={{ position: 'absolute', inset: 0, borderRadius: '50%', background: c }} />
      {status === 'ok' && <span style={{ position: 'absolute', inset: -3, borderRadius: '50%', background: c, opacity: 0.3, animation: 'ai-shimmer 2s infinite' }} />}
    </span>
  );
};

const devSparks = {
  anthropic: [12, 15, 14, 18, 22, 19, 24, 28, 25, 31, 29, 34, 38, 42, 38, 45, 48, 52, 49, 55, 62, 58, 64, 70, 67, 73, 68, 71, 82, 87],
  conv: [420, 445, 460, 438, 501, 522, 518],
  cost: [38, 42, 40, 45, 52, 48, 54],
  latency: [320, 340, 310, 350, 380, 360, 345],
};

// ============ DEV Secondary Sidebar ============
const DEV_NAV = [
  { id: 'inbox', label: 'Inbox · Live', icon: 'chat', kbd: '1', hero: true, badge: 4 },
  { id: 'overview', label: 'Overview', icon: 'dashboard', kbd: '2' },
  { id: 'architecture', label: 'Architecture', icon: 'layers', kbd: '3' },
  { id: 'conversations', label: 'Replay', icon: 'history', kbd: '4' },
  { id: 'prompts', label: 'Prompts', icon: 'doc', kbd: '5' },
  { id: 'kb', label: 'Knowledge Base', icon: 'bi', kbd: '6' },
  { id: 'agents', label: 'Agents', icon: 'sparkle', kbd: '7' },
  { id: 'costs', label: 'Costs', icon: 'dollar', kbd: '8' },
  { id: 'integrations', label: 'Integrations', icon: 'link', kbd: '9' },
  { id: 'deploy', label: 'Deploy', icon: 'zap', kbd: 'D' },
  { id: 'alerts', label: 'Alerts', icon: 'bell', kbd: 'A', badge: 2 },
];

const DevSecondarySidebar = ({ active, onNavigate }) => (
  <aside style={{
    width: 212, flexShrink: 0,
    borderRight: '1px solid var(--border)',
    background: 'var(--bg-sunken)',
    display: 'flex', flexDirection: 'column',
    height: '100%', minHeight: 0,
  }}>
    <div style={{ padding: '14px 16px 8px', display: 'flex', alignItems: 'center', gap: 8 }}>
      <div style={{ width: 20, height: 20, borderRadius: 4, background: 'var(--brand-900)', border: '1px solid var(--border-strong)', display: 'grid', placeItems: 'center', color: 'var(--ai-500)' }}>
        <Icon name="dev" size={11} />
      </div>
      <div style={{ fontFamily: 'var(--font-display)', fontWeight: 700, fontSize: 12, letterSpacing: '0.08em' }}>DEV</div>
      <span className="font-mono" style={{ fontSize: 9, color: 'var(--text-dim)', padding: '2px 6px', background: 'var(--bg-elev)', border: '1px solid var(--border)', borderRadius: 4 }}>v2.3.1</span>
    </div>
    <div style={{ padding: '4px 8px', flex: 1, overflowY: 'auto' }} className="scrollbar">
      {DEV_NAV.map(item => {
        const isActive = item.id === active;
        return (
          <button key={item.id}
            onClick={() => onNavigate(item.id)}
            style={{
              width: '100%', display: 'flex', alignItems: 'center', gap: 10,
              padding: '6px 10px', borderRadius: 6, marginBottom: 1,
              fontSize: 12, fontWeight: 500,
              background: isActive ? 'var(--bg-elev)' : 'transparent',
              color: isActive ? 'var(--text)' : 'var(--text-muted)',
              border: isActive ? '1px solid var(--border)' : '1px solid transparent',
              position: 'relative',
            }}
            onMouseEnter={e => { if (!isActive) e.currentTarget.style.color = 'var(--text)'; }}
            onMouseLeave={e => { if (!isActive) e.currentTarget.style.color = 'var(--text-muted)'; }}
          >
            <Icon name={item.icon} size={13} style={{ color: item.hero ? 'var(--ai-500)' : 'inherit' }} />
            <span style={{ flex: 1, textAlign: 'left' }}>{item.label}</span>
            {item.badge && <span style={{ padding: '0 5px', fontSize: 9, fontFamily: 'var(--font-mono)', color: 'var(--danger)', background: 'color-mix(in oklch, var(--danger) 14%, transparent)', borderRadius: 3 }}>{item.badge}</span>}
            <kbd style={{ fontFamily: 'var(--font-mono)', fontSize: 9, color: 'var(--text-dim)', padding: '1px 4px', border: '1px solid var(--border)', borderRadius: 3, background: 'var(--bg-sunken)' }}>{item.kbd}</kbd>
          </button>
        );
      })}
    </div>
    <div style={{ padding: 12, borderTop: '1px solid var(--border)', display: 'flex', flexDirection: 'column', gap: 6, fontSize: 10, fontFamily: 'var(--font-mono)', color: 'var(--text-dim)' }}>
      <div style={{ display: 'flex', justifyContent: 'space-between' }}><span>env</span><span style={{ color: 'var(--success)' }}>produção</span></div>
      <div style={{ display: 'flex', justifyContent: 'space-between' }}><span>region</span><span>eu-hel-1</span></div>
      <div style={{ display: 'flex', justifyContent: 'space-between' }}><span>uptime</span><span>42d · 18h</span></div>
    </div>
  </aside>
);

// ============ Panel header ============
const PanelHeader = ({ title, sub, right, tag }) => (
  <div style={{ display: 'flex', alignItems: 'center', gap: 10, padding: '10px 14px', borderBottom: '1px solid var(--border)' }}>
    <h3 className="font-display" style={{ margin: 0, fontSize: 13, fontWeight: 600, letterSpacing: '0.04em', textTransform: 'uppercase' }}>{title}</h3>
    {tag && <span className="font-mono" style={{ fontSize: 10, color: 'var(--text-dim)' }}>{tag}</span>}
    <div style={{ flex: 1 }} />
    {sub && <span style={{ fontSize: 11, color: 'var(--text-muted)' }}>{sub}</span>}
    {right}
  </div>
);

// ============ SECTION: OVERVIEW ============
const DevOverview = ({ onOpenChat }) => {
  const health = [
    { name: 'Anthropic API', status: 'ok', detail: '99.98% · 340ms' },
    { name: 'PostgreSQL', status: 'ok', detail: '61G free · p95 12ms' },
    { name: 'Redis', status: 'ok', detail: '84MB · 0 evict' },
    { name: 'WhatsApp WH', status: 'ok', detail: 'last 12s ago' },
    { name: 'Meta Ads', status: 'warn', detail: 'rate-limit 3×/h' },
    { name: 'Primavera', status: 'crit', detail: 'pending setup' },
  ];

  const today = [
    { label: 'Conversas', value: '518', delta: '+3,1%', spark: devSparks.conv },
    { label: 'Leads capt.', value: '47', delta: '+14%', spark: [22, 28, 31, 35, 38, 42, 47] },
    { label: 'Tickets abert.', value: '12', delta: '−2', spark: [14, 12, 18, 15, 11, 13, 12] },
    { label: 'Custo hoje', value: '$67.42', delta: '+23%', spark: devSparks.cost, accent: 'var(--warning)' },
  ];

  const modes = [
    { name: 'Clientes', conv: 312, pct: 60, color: 'oklch(0.62 0.18 20)' },
    { name: 'Colaboradores', conv: 141, pct: 27, color: 'var(--ai-500)' },
    { name: 'DEV', conv: 48, pct: 9, color: 'var(--info)' },
    { name: 'Board', conv: 17, pct: 4, color: 'oklch(0.72 0.14 80)' },
  ];

  return (
    <div style={{ padding: 16, display: 'flex', flexDirection: 'column', gap: 14 }}>
      {/* Header */}
      <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: 12 }}>
        <div>
          <div style={{ fontSize: 10, color: 'var(--text-dim)', fontFamily: 'var(--font-mono)', letterSpacing: '0.08em' }}>DEV · OVERVIEW · 09:42 WET · 23 ABR 2026</div>
          <h2 className="font-display" style={{ margin: '4px 0 0', fontSize: 22, fontWeight: 600, letterSpacing: '-0.01em' }}>System cockpit</h2>
        </div>
        <div style={{ display: 'flex', gap: 6 }}>
          <button className="btn btn-xs"><Icon name="refresh" size={11} />Refresh</button>
          <button className="btn btn-xs"><Icon name="download" size={11} />Export JSON</button>
          <button className="btn btn-xs btn-ai" onClick={onOpenChat}><Icon name="sparkle" size={11} />Ask Digi</button>
        </div>
      </div>

      {/* Health strip */}
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(6, 1fr)', gap: 1, background: 'var(--border)', border: '1px solid var(--border)', borderRadius: 6, overflow: 'hidden' }}>
        {health.map(h => (
          <div key={h.name} style={{ padding: '10px 12px', background: 'var(--bg-elev)', display: 'flex', flexDirection: 'column', gap: 6 }}>
            <div style={{ display: 'flex', alignItems: 'center', gap: 6 }}>
              <StatusDot status={h.status} />
              <span style={{ fontSize: 11, fontWeight: 500 }}>{h.name}</span>
            </div>
            <div className="font-mono" style={{ fontSize: 10, color: 'var(--text-dim)' }}>{h.detail}</div>
          </div>
        ))}
      </div>

      {/* Row: counters + Digi brief */}
      <div style={{ display: 'grid', gridTemplateColumns: '1.8fr 1fr', gap: 14 }}>
        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: 1, background: 'var(--border)', border: '1px solid var(--border)', borderRadius: 8, overflow: 'hidden' }}>
          {today.map(k => (
            <div key={k.label} style={{ background: 'var(--bg-elev)', padding: 14, display: 'flex', flexDirection: 'column', gap: 6 }}>
              <div style={{ fontSize: 10, color: 'var(--text-dim)', fontFamily: 'var(--font-display)', fontWeight: 600, letterSpacing: '0.08em', textTransform: 'uppercase' }}>{k.label}</div>
              <div className="font-display" style={{ fontSize: 26, fontWeight: 600, letterSpacing: '-0.02em', lineHeight: 1 }}>{k.value}</div>
              <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-end' }}>
                <span className="font-mono" style={{ fontSize: 10, color: k.accent || 'var(--text-muted)' }}>{k.delta}</span>
                <Spark data={k.spark} width={80} height={22} stroke={k.accent || 'var(--ai-500)'} fill={k.accent ? 'color-mix(in oklch, var(--warning) 18%, transparent)' : 'color-mix(in oklch, var(--ai-500) 18%, transparent)'} />
              </div>
            </div>
          ))}
        </div>

        <div className="ai-surface" style={{ padding: 14, borderRadius: 8, display: 'flex', flexDirection: 'column', gap: 8 }}>
          <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
            <span className="ai-chip"><span className="ai-dot" />Digi AI · brief</span>
            <span style={{ fontSize: 10, color: 'var(--text-dim)', fontFamily: 'var(--font-mono)' }}>auto · 4m ago</span>
          </div>
          <div style={{ fontSize: 12.5, lineHeight: 1.55 }}>
            System healthy. Custo de ontem <strong>$54.18</strong>. <strong>quality_kb</strong> ainda pendente da Sónia Casimiro há 14 dias. Deploy <strong className="font-mono">FRAME‑GESTAO‑TICKETS</strong> em staging — diff +42 / −18, low risk. Sugiro aprovar.
          </div>
          <div style={{ display: 'flex', gap: 6, marginTop: 4 }}>
            <button className="btn btn-xs btn-ai" onClick={onOpenChat}>Discutir</button>
            <button className="btn btn-xs">Ver deploy</button>
          </div>
        </div>
      </div>

      {/* Row: modes + activity chart */}
      <div style={{ display: 'grid', gridTemplateColumns: '1fr 1.6fr', gap: 14 }}>
        <div className="card" style={{ padding: 0 }}>
          <PanelHeader title="Modos ativos" tag="agora" sub={<span className="font-mono" style={{ fontSize: 10 }}>518 conversas</span>} />
          <div style={{ padding: 14, display: 'flex', flexDirection: 'column', gap: 10 }}>
            {modes.map(m => (
              <div key={m.name}>
                <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'baseline', marginBottom: 4 }}>
                  <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
                    <span style={{ width: 8, height: 8, background: m.color, borderRadius: 2 }} />
                    <span style={{ fontSize: 12, fontWeight: 500 }}>{m.name}</span>
                  </div>
                  <div>
                    <span className="font-display" style={{ fontWeight: 600 }}>{m.conv}</span>
                    <span className="font-mono" style={{ fontSize: 10, color: 'var(--text-dim)', marginLeft: 6 }}>{m.pct}%</span>
                  </div>
                </div>
                <div style={{ height: 4, background: 'var(--bg-sunken)', borderRadius: 2, overflow: 'hidden' }}>
                  <div style={{ width: `${m.pct}%`, height: '100%', background: m.color }} />
                </div>
              </div>
            ))}
          </div>
        </div>

        <div className="card" style={{ padding: 0 }}>
          <PanelHeader title="Atividade 7 dias" tag="conv/dia por modo"
            right={<div style={{ display: 'flex', gap: 10, fontSize: 10, fontFamily: 'var(--font-mono)', color: 'var(--text-dim)' }}>
              {modes.slice(0, 3).map(m => <span key={m.name} style={{ display: 'flex', alignItems: 'center', gap: 4 }}><span style={{ width: 8, height: 8, background: m.color, borderRadius: 2 }} />{m.name}</span>)}
            </div>}
          />
          <div style={{ padding: 14 }}>
            <ActivityChart />
          </div>
        </div>
      </div>

      {/* Alerts + quick actions */}
      <div style={{ display: 'grid', gridTemplateColumns: '2fr 1fr', gap: 14 }}>
        <div className="card" style={{ padding: 0 }}>
          <PanelHeader title="Top alerts" tag="2 críticos · 2 warnings" right={<button className="btn btn-xs btn-ghost">Ver todos (11)</button>} />
          <table style={{ width: '100%', borderCollapse: 'collapse', fontSize: 12 }}>
            <tbody>
              {[
                { sev: 'crit', source: 'kb.quality_kb', msg: 'Pending source — aguarda Sónia Casimiro', time: '14d', owner: 'FC' },
                { sev: 'warn', source: 'cost.anthropic.opus', msg: 'Custo +23% WoW — Opus em Sales spiked', time: '2h', owner: 'FC' },
                { sev: 'warn', source: 'infra.postgres', msg: 'Espaço livre 61G — monitorar abaixo de 20G', time: '6h', owner: 'JP' },
                { sev: 'info', source: 'prompts.flagged', msg: '3 conversas sinalizadas para prompt improvement', time: '1d', owner: 'FC' },
                { sev: 'ok', source: 'core.systems', msg: 'Todos os core systems nominais', time: 'now', owner: '—' },
              ].map((a, i) => (
                <tr key={i} style={{ borderTop: i ? '1px solid var(--border)' : 'none' }}>
                  <td style={{ padding: '8px 14px', width: 30 }}><StatusDot status={a.sev} /></td>
                  <td style={{ padding: '8px 0', width: 200, fontFamily: 'var(--font-mono)', fontSize: 11, color: 'var(--text-muted)' }}>{a.source}</td>
                  <td style={{ padding: '8px 14px' }}>{a.msg}</td>
                  <td style={{ padding: '8px 14px', textAlign: 'right', fontFamily: 'var(--font-mono)', fontSize: 11, color: 'var(--text-dim)' }}>{a.time}</td>
                  <td style={{ padding: '8px 14px', textAlign: 'right' }}><span className="badge" style={{ fontFamily: 'var(--font-mono)', fontSize: 10 }}>{a.owner}</span></td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>

        <div className="card" style={{ padding: 0 }}>
          <PanelHeader title="Quick actions" />
          <div style={{ padding: 10, display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 6 }}>
            {[
              ['doc', 'Edit SP'],
              ['zap', 'Deploy'],
              ['bi', 'Reindex KB'],
              ['chat', 'Replay conv'],
              ['dollar', 'Cost report'],
              ['refresh', 'Restart worker'],
            ].map(([ic, l]) => (
              <button key={l} className="btn btn-xs" style={{ justifyContent: 'flex-start', padding: '8px 10px' }}>
                <Icon name={ic} size={12} />{l}
              </button>
            ))}
          </div>
        </div>
      </div>
    </div>
  );
};

const ActivityChart = () => {
  // 7 days x 3 modes stacked
  const days = ['17', '18', '19', '20', '21', '22', '23'];
  const data = [
    [240, 120, 28], [260, 135, 31], [255, 140, 40], [238, 115, 29],
    [298, 152, 45], [305, 165, 42], [312, 141, 48],
  ];
  const max = 500;
  const W = 620, H = 160, pad = 24;
  const bw = (W - pad * 2) / days.length;
  return (
    <svg width="100%" viewBox={`0 0 ${W} ${H}`} style={{ display: 'block' }}>
      {[0, 125, 250, 375, 500].map(g => {
        const y = H - pad - (g / max) * (H - pad * 2);
        return <g key={g}>
          <line x1={pad} x2={W - pad} y1={y} y2={y} stroke="var(--border)" strokeDasharray="2 3" />
          <text x={pad - 4} y={y + 3} fontSize="9" fill="var(--text-dim)" textAnchor="end" fontFamily="var(--font-mono)">{g}</text>
        </g>;
      })}
      {data.map((stack, i) => {
        let acc = 0;
        return stack.map((v, j) => {
          const color = ['oklch(0.62 0.18 20)', 'var(--ai-500)', 'var(--info)'][j];
          const h = (v / max) * (H - pad * 2);
          const y = H - pad - acc - h;
          acc += h;
          return <rect key={`${i}-${j}`} x={pad + i * bw + bw * 0.18} y={y} width={bw * 0.64} height={h} fill={color} opacity={j === 0 ? 0.9 : 1} />;
        });
      })}
      {days.map((d, i) => (
        <text key={d} x={pad + i * bw + bw / 2} y={H - 6} fontSize="9" fill="var(--text-dim)" textAnchor="middle" fontFamily="var(--font-mono)">{d}/04</text>
      ))}
    </svg>
  );
};

window.DevOverview = DevOverview;
window.DevSecondarySidebar = DevSecondarySidebar;
window.PanelHeader = PanelHeader;
window.StatusDot = StatusDot;
window.Spark = Spark;
