/* global React, Icon, Spark */

window.Dashboard = function Dashboard({ setPage }) {
  const m = window.MOCK || {};
  const [range, setRange] = React.useState('30D');
  function setDashboardPeriod(period) {
    setRange(period);
  }
  window.setDashboardPeriod = setDashboardPeriod;
  window.renderDashboard = () => setRange(current => current);
  const tickets = m.tickets || [];
  const conversations = m.conversations || [];
  const agents = m.agents || [];
  const instances = m.instances || [];
  const runs = m.runs || [];
  const draftAgents = agents.filter(agent => !agent.isPublished);
  const openTickets = tickets.filter(t => ['Aberto', 'Em andamento'].includes(t.status)).length;
  const paused = conversations.filter(c => c.paused).length;
  const onlineInstances = instances.filter(i => i.status === 'online').length;
  const attentionInstances = instances.filter(i => i.status !== 'online').length;
  const activeAgents = agents.filter(a => a.status === 'online').length;
  const msgCount = conversations.reduce((acc, c) => acc + Number(c.raw?.messages || 0), 0);
  const latencyValues = runs.map(r => Number(r.latency_ms || 0)).filter(Boolean);
  const avgLatency = latencyValues.length ? Math.round(latencyValues.reduce((a, b) => a + b, 0) / latencyValues.length) : 0;
  const agentById = Object.fromEntries(agents.map(a => [a.id, a.name]));
  const ticketStatuses = ['Aberto', 'Em andamento', 'Resolvido', 'Fechado'];
  const telemetryRows = runs.slice(0, 7).map(r => {
    const status = r.error ? 'bad' : Number(r.latency_ms || 0) > 1500 ? 'warn' : 'ok';
    return {
      time: window.fmtTime ? window.fmtTime(r.created_at) : '--',
      agent: agentById[r.agent_id] || `#${r.agent_id || '-'}`,
      conversation: r.conversation_id || '--',
      decision: r.output?.decision || r.output?.action || r.status || 'executar',
      tool: r.output?.tool || r.input?.tool || '--',
      latency: r.latency_ms ? `${r.latency_ms} ms` : '--',
      status,
      label: r.error || r.status || 'OK',
    };
  });

  const kpis = [
    { label: 'Tickets abertos', value: String(openTickets), unit: 'na fila', delta: `${tickets.length} total`, dn: openTickets > 0, spark: sparkFrom(openTickets, 2) },
    { label: 'Conversas pausadas', value: String(paused), unit: 'humano', delta: `${conversations.length} conversas`, dn: paused > 0, spark: sparkFrom(paused, 4) },
    { label: 'SLA 1a resposta', value: tickets.length ? 'ativo' : '--', unit: '', delta: 'CRM online', up: true, spark: [4.1, 3.6, 3.2, 2.9, 2.8, 2.6, 2.5, 2.4] },
    { label: 'Mensagens', value: msgCount.toLocaleString('pt-BR'), unit: 'hist.', delta: `${runs.length} runs`, up: true, spark: sparkFrom(msgCount, 6) },
    { label: 'Agentes ativos', value: String(activeAgents), unit: `/ ${agents.length}`, delta: `${agents.length} cadastrados`, up: activeAgents > 0, spark: sparkFrom(activeAgents, 8) },
    { label: 'Latência IA', value: avgLatency ? String(avgLatency) : '--', unit: avgLatency ? 'ms' : '', delta: latencyValues.length ? `${latencyValues.length} amostras` : 'sem runs', up: true, spark: latencyValues.slice(0, 8).length ? latencyValues.slice(0, 8) : [1, 1, 1, 1, 1, 1, 1, 1] },
  ];

  return (
    <>
      <div className="page-head">
        <div>
          <div className="page-eyebrow">Operação - {new Date().toLocaleDateString('pt-BR')} - ao vivo</div>
          <h1 className="page-title">Dashboard</h1>
          <p className="page-sub">Visão consolidada da malha de agentes, conexões WhatsApp, fila humana e saúde do orquestrador.</p>
        </div>
        <div className="page-meta">
          <div className="meta-row"><span className="sw ok"/> {onlineInstances} conexões ativas</div>
          <div className="meta-row"><span className="sw warn"/> {attentionInstances} requerem ação</div>
          <div className="meta-row"><span className="sw bad"/> {paused} conversas pausadas</div>
        </div>
      </div>

      <div className="page">
        {draftAgents.length > 0 && (
          <div className="banner banner-warn">
            <div>
              <div className="banner-title">{draftAgents.length} bot(s) em rascunho</div>
              <div className="banner-body">Complete o setup antes de liberar respostas em mensagens reais.</div>
            </div>
            <button className="tb-btn primary" onClick={() => setPage && setPage('agents')}>Abrir setup</button>
          </div>
        )}

        <div className="grid-kpis">
          {kpis.map((k, i) => (
            <div key={i} className="kpi">
              <div className="kpi-label">{k.label}</div>
              <div className="kpi-value">{k.value} <span className="unit">{k.unit}</span></div>
              <Spark data={k.spark} color="var(--accent)"/>
              <div className="kpi-foot">
                <span className={`delta ${k.up ? 'up' : k.dn ? 'dn' : ''}`}>{k.delta}</span>
                <span>backend</span>
              </div>
            </div>
          ))}
        </div>

        <div className="grid-2">
          <div className="panel">
            <div className="panel-head">
              <div>
                <div className="panel-eyebrow">Fila de handoff humano - ao vivo</div>
                <div className="panel-title">Conversas pausadas</div>
              </div>
              <span className="badge bad">{(m.handoffQueue || []).length} em espera</span>
            </div>
            <div>
              {(m.handoffQueue || []).map(h => (
                <div className="handoff-row" key={h.id}>
                  <div>
                    <div className="handoff-name">{h.name}</div>
                    <div className="handoff-reason">{h.reason} - agente: {h.agent}</div>
                  </div>
                  <span className="handoff-time">{h.wait}</span>
                  <button className="handoff-take" onClick={() => setPage && setPage('tickets')}>Tomar posse</button>
                </div>
              ))}
              {!(m.handoffQueue || []).length && <div className="empty">Sem handoff pendente.</div>}
            </div>
          </div>

          <div className="panel">
            <div className="panel-head">
              <div>
                <div className="panel-eyebrow">Tickets</div>
                <div className="panel-title">Por status</div>
              </div>
              <button className="tb-btn ghost" onClick={() => setPage && setPage('tickets')}>Ver todos <Icon name="arrow" size={11}/></button>
            </div>
            <div style={{ padding: 12 }}>
              <div className="kanban-mini">
                {ticketStatuses.map(status => {
                  const bucket = tickets.filter(t => t.status === status);
                  return (
                    <KCol key={status} title={status} n={bucket.length}>
                      {bucket.slice(0, 3).map(t => <KCard key={t.id} who={t.client} sub={`${t.id} - ${t.summary.slice(0, 34)}`} priority={t.priority === 'alta'}/>)}
                      {!bucket.length && <div className="km-card muted">vazio</div>}
                    </KCol>
                  );
                })}
              </div>
            </div>
          </div>
        </div>

        <div className="grid-2">
          <div className="panel">
            <div className="panel-head">
              <div>
                <div className="panel-eyebrow">Atividade do orquestrador</div>
                <div className="panel-title">Mensagens & latencia</div>
              </div>
              <div className="filter-row">
                {['Hoje', '30D', '6M'].map(r => (
                  <button key={r} data-dash-period={r.toLowerCase()} className={`fp ${range === r ? 'active' : ''}`} onClick={() => setDashboardPeriod(r)}>{r}</button>
                ))}
              </div>
            </div>
            <div className="dash-month-bars" style={{ padding: '14px 16px 16px' }}>
              <Barchart range={range} seed={msgCount + runs.length}/>
              <div style={{ display:'flex', gap: 16, marginTop: 8, fontSize: 11.5, color:'var(--ink-3)' }}>
                <span style={{ display:'inline-flex', alignItems:'center', gap:5}}><span className="sw ink"/> mensagens</span>
                <span style={{ display:'inline-flex', alignItems:'center', gap:5}}><span className="sw accent"/> latencia (ms)</span>
                <span style={{ marginLeft:'auto'}}>{msgCount} mensagens - media {avgLatency || '--'}ms</span>
              </div>
            </div>
          </div>

          <div className="panel">
            <div className="panel-head">
              <div>
                <div className="panel-eyebrow">Conexões WhatsApp</div>
                <div className="panel-title">Saude dos canais</div>
              </div>
              <button className="tb-btn" onClick={() => setPage && setPage('channels')}><Icon name="plus" size={11}/> Canais</button>
            </div>
            <div>
              {instances.map(i => <InstanceRow key={i.id} i={i}/>)}
              {!instances.length && <div className="empty">Sem instância registrada.</div>}
            </div>
          </div>
        </div>

        <div className="panel">
          <div className="panel-head">
            <div>
              <div className="panel-eyebrow">Densidade operacional</div>
              <div className="panel-title">Mensagens por hora & dia</div>
            </div>
            <div style={{ display:'flex', alignItems:'center', gap: 4, fontSize: 11, color:'var(--ink-3)'}}>
              <span>baixo</span>
              <span className="sw" style={{background:'var(--hover)', borderRadius:3}}/>
              <span className="sw l1" style={{borderRadius:3}}/>
              <span className="sw l2" style={{borderRadius:3}}/>
              <span className="sw l3" style={{borderRadius:3}}/>
              <span className="sw accent" style={{borderRadius:3}}/>
              <span>alto</span>
            </div>
          </div>
          <div className="hm-wrap" style={{ padding: 16 }}>
            <Heatmap seed={msgCount}/>
          </div>
        </div>

        <div className="panel">
          <div className="panel-head">
            <div>
              <div className="panel-eyebrow">Telemetria</div>
              <div className="panel-title">Execuções recentes da IA</div>
            </div>
            <button className="tb-btn ghost" onClick={() => setPage && setPage('logs')}>Ver logs <Icon name="arrow" size={11}/></button>
          </div>
          <table className="dt">
            <thead>
              <tr><th>Timestamp</th><th>Agente</th><th>Conversa</th><th>Decisão</th><th>Ferramenta</th><th className="num">Latência</th><th>Status</th></tr>
            </thead>
            <tbody>
              {telemetryRows.map((r, i) => (
                <tr key={i}>
                  <td className="mono" data-label="Timestamp">{r.time}</td>
                  <td data-label="Agente">{r.agent}</td>
                  <td data-label="Conversa" className="mono">{r.conversation}</td>
                  <td data-label="Decisão">{r.decision}</td>
                  <td data-label="Ferramenta" className="mono muted">{r.tool}</td>
                  <td className="num mono" data-label="Latência">{r.latency}</td>
                  <td data-label="Status"><span className={`badge ${r.status}`}><span className={`sw ${r.status}`}/> {r.label}</span></td>
                </tr>
              ))}
              {!telemetryRows.length && <tr><td colSpan="7" className="empty">Sem execucoes recentes.</td></tr>}
            </tbody>
          </table>
        </div>
      </div>
    </>
  );
};

function sparkFrom(value, seed) {
  const n = Math.max(1, Number(value || 0));
  return Array.from({ length: 8 }, (_, i) => Math.max(1, Math.round(n * (0.6 + ((i + seed) % 5) * 0.12))));
}

function KCol({ title, n, children }) {
  return (
    <div className="km-col">
      <div className="km-col-head"><span>{title}</span><span className="n">{n}</span></div>
      {children}
    </div>
  );
}

function KCard({ who, sub, priority }) {
  return (
    <div className="km-card" style={priority ? { borderLeft: '2px solid var(--accent)' } : {}}>
      <div className="who"><span>{who}</span><span>{priority ? 'P1' : ''}</span></div>
      <div>{sub}</div>
    </div>
  );
}

function InstanceRow({ i }) {
  const m = { tag: i.statusTag || statusTag(i.status), label: i.statusLabel || friendlyWhatsAppStatus(i.status) };
  return (
    <div className="instance">
      <div className="instance-icon">w</div>
      <div>
        <div className="instance-name">{i.name}</div>
        <div className="instance-meta">{m.label} - {i.queue} mensagens</div>
      </div>
      <span className={`badge ${m.tag}`} title="Status da conexão WhatsApp"><span className={`sw ${m.tag}`}/> {m.label}</span>
    </div>
  );
}

function Barchart({ range, seed = 1 }) {
  const N = range === 'Hoje' ? 24 : range === '30D' ? 30 : 26;
  function rand(i) { return Math.abs(Math.sin((i + seed) * 12.9898) * 43758.5453 % 1); }
  const data = Array.from({ length:N }, (_, i) => Math.max(0.1, 0.45 + Math.sin((i / N) * Math.PI) * 0.4 + (rand(i) - 0.5) * 0.3));
  const lat = Array.from({ length:N }, (_, i) => 0.5 + Math.cos((i / N) * Math.PI * 1.6) * 0.18 + (rand(i + 99) - 0.5) * 0.08);
  const W = 800, H = 220, pad = { l: 36, r: 36, t: 10, b: 26 };
  const cw = W - pad.l - pad.r;
  const ch = H - pad.t - pad.b;
  const bw = cw / N - 3;
  const linePts = lat.map((v, i) => `${pad.l + (i + 0.5) * (cw / N)},${pad.t + (1 - v) * ch}`).join(' ');
  const xLabels = range === 'Hoje' ? ['00', '06', '12', '18', '23'] : range === '30D' ? ['1', '8', '15', '22', '30'] : ['Nov', 'Dez', 'Jan', 'Fev', 'Mar', 'Abr'];

  return (
    <svg className="barchart" viewBox={`0 0 ${W} ${H}`} preserveAspectRatio="none">
      {[0.25, 0.5, 0.75, 1].map((g, i) => <line key={i} x1={pad.l} x2={W - pad.r} y1={pad.t + g * ch} y2={pad.t + g * ch} stroke="var(--rule)" strokeDasharray="2 3" strokeWidth="0.6"/>)}
      {data.map((v, i) => <rect key={i} x={pad.l + i * (cw / N) + 1.5} y={pad.t + ch - v * ch} width={bw} height={v * ch} rx="1.5" fill="var(--ink)" opacity="0.85"/>)}
      <polyline points={linePts} fill="none" stroke="var(--accent)" strokeWidth="1.8" strokeLinejoin="round"/>
      {lat.map((v, i) => <circle key={i} cx={pad.l + (i + 0.5) * (cw / N)} cy={pad.t + (1 - v) * ch} r="2" fill="var(--accent)"/>)}
      {[0, 0.5, 1].map((g, i) => <text key={i} x={pad.l - 8} y={pad.t + (1 - g) * ch + 3} fontFamily="var(--mono)" fontSize="10" fill="var(--ink-3)" textAnchor="end">{Math.round(g * 620)}</text>)}
      {xLabels.map((l, i) => <text key={i} x={pad.l + (i / (xLabels.length - 1)) * cw} y={H - 8} fontFamily="var(--mono)" fontSize="10" fill="var(--ink-3)" textAnchor="middle">{l}</text>)}
    </svg>
  );
}

function Heatmap({ seed = 1 }) {
  const days = ['SEG', 'TER', 'QUA', 'QUI', 'SEX', 'SAB', 'DOM'];
  function intensity(d, h) {
    const work = h >= 9 && h <= 18 ? 0.55 : 0.12;
    const weekend = d >= 5 ? -0.2 : 0;
    return Math.max(0, Math.min(1, work + weekend + Math.sin((d * 7 + h + seed) * 1.3) * 0.18));
  }
  function lvl(v) {
    if (v < 0.12) return 0;
    if (v < 0.3) return 1;
    if (v < 0.5) return 2;
    if (v < 0.75) return 3;
    if (v < 0.9) return 4;
    return 5;
  }
  return (
    <>
      <div className="hm">
        <div></div>
        {Array.from({ length:24 }).map((_, h) => <div key={h} className="col-label">{h % 6 === 0 ? String(h).padStart(2, '0') : ''}</div>)}
        {days.map((d, di) => (
          <React.Fragment key={d}>
            <div className="row-label">{d}</div>
            {Array.from({ length:24 }).map((_, h) => {
              const v = intensity(di, h);
              const l = lvl(v);
              return <div key={h} className={`cell ${l ? 'l' + l : ''}`} title={`${d} ${h}h - ${(v * 620 | 0)} msg`}/>;
            })}
          </React.Fragment>
        ))}
      </div>
      <div style={{ display:'flex', justifyContent:'space-between', marginTop: 10, fontSize: 11, color:'var(--ink-3)'}}>
        <span>Semana atual</span>
        <span>densidade calculada por atividade recente</span>
      </div>
    </>
  );
}
