/* Visão do gestor — acompanhar a execução dela (secundária) */
function VisaoGestor({ done, go, meta }) {
  const OE = window.OE;
  const cols = OE.colaboradores;

  let totalDone = 0, totalAll = 0, concluidos = 0, emRisco = 0;
  const linhas = cols.map((c) => {
    const prog = OE.progressoColab(done[c.id]);
    const atualIdx = OE.faseAtual(done[c.id]);
    const prox = OE.proximaTarefa(done[c.id]);
    totalDone += prog.done; totalAll += prog.total;
    if (prog.pct === 100) concluidos++;
    // "em risco": início já passou há muito e progresso baixo
    const diasDesdeInicio = Math.round((new Date("2026-06-22") - new Date(c.inicio + "T00:00:00")) / 86400000);
    const risco = diasDesdeInicio > 25 && prog.pct < 55;
    if (risco) emRisco++;
    const cmeta = (meta && meta[c.id]) || {};
    const formCount = OE.PLAYBOOK.filter((f) => (cmeta.form || {})[f.id]).length;
    return { c, prog, atualIdx, prox, risco, diasDesdeInicio, formCount };
  });
  const pctGeral = Math.round((totalDone / totalAll) * 100);

  return (
    <div style={{ display: "flex", flexDirection: "column", gap: 24 }}>
      <div style={{ display: "grid", gridTemplateColumns: "repeat(auto-fit,minmax(190px,1fr))", gap: 16 }}>
        <KPI ring={pctGeral} lab="Execução geral" foot={`${totalDone}/${totalAll} tarefas`} />
        <KPI val={cols.length} lab="Pessoas em onboarding" foot={`${concluidos} concluído(s)`} icon="users" />
        <KPI val={emRisco} lab="Precisam de atenção" foot="Início > 25d e < 55%" icon="alert-triangle" tone={emRisco ? "amber" : "green"} />
        <KPI val={totalAll - totalDone} lab="Tarefas restantes" foot="No total da equipe" icon="list-todo" />
      </div>

      <div>
        <SectionTitle icon="activity" sub="O que a executora de onboarding fez e o que falta, por colaborador.">Acompanhamento da execução</SectionTitle>
        <Card pad={0} style={{ overflow: "hidden" }}>
          <div style={{ overflowX: "auto" }}>
            <table style={{ width: "100%", borderCollapse: "collapse", fontSize: 13.5 }}>
              <thead>
                <tr style={{ background: C.bg }}>
                  {["Colaborador", "Etapa atual", "Progresso", "Próxima ação", "Status", ""].map((h, i) => (
                    <th key={i} style={{ textAlign: i > 1 && i < 4 ? "left" : i >= 4 ? "left" : "left", fontSize: 11, letterSpacing: ".08em", textTransform: "uppercase", color: C.ink3, fontWeight: 800, padding: "13px 18px", borderBottom: `1px solid ${C.line}`, whiteSpace: "nowrap" }}>{h}</th>
                  ))}
                </tr>
              </thead>
              <tbody>
                {linhas.map(({ c, prog, atualIdx, prox, risco, formCount }) => {
                  const completo = prog.pct === 100;
                  const fase = OE.PLAYBOOK[atualIdx];
                  return (
                    <tr key={c.id} style={{ borderBottom: `1px solid ${C.lineSoft}`, cursor: "pointer" }} onClick={() => go("guia", { id: c.id })}>
                      <td style={{ padding: "14px 18px" }}>
                        <div style={{ display: "flex", alignItems: "center", gap: 11 }}>
                          <Avatar nome={c.nome} cor={c.cor} size={36} />
                          <div><div style={{ fontWeight: 800, color: C.ink }}>{c.nome}</div><div style={{ fontSize: 12, color: C.ink3 }}>{c.cargo}</div></div>
                        </div>
                      </td>
                      <td style={{ padding: "14px 18px" }}>
                        {completo ? <Pill tone="green" icon="badge-check">Concluído</Pill> : <Pill tone="cobalt" icon={fase.icon}>{atualIdx + 1}/{OE.N_ETAPAS} · {fase.nome}</Pill>}
                        <div style={{ fontSize: 11, color: C.ink3, marginTop: 6, display: "inline-flex", alignItems: "center", gap: 5 }}><LIcon name="mail-check" size={12} />{formCount}/{OE.N_ETAPAS} formalizadas</div>
                      </td>
                      <td style={{ padding: "14px 18px", minWidth: 160 }}>
                        <div style={{ display: "flex", alignItems: "center", gap: 9 }}>
                          <div style={{ flex: 1 }}><Bar value={prog.pct} color={completo ? C.green : c.cor} /></div>
                          <span style={{ fontWeight: 800, color: C.ink, fontSize: 12.5 }}>{prog.pct}%</span>
                        </div>
                      </td>
                      <td style={{ padding: "14px 18px", color: C.ink2, maxWidth: 230 }}>
                        {prox ? prox.tarefa.titulo : <span style={{ color: C.green, fontWeight: 700 }}>—</span>}
                      </td>
                      <td style={{ padding: "14px 18px" }}>
                        {completo ? <Pill tone="green">Em dia</Pill> : risco ? <Pill tone="amber" icon="alert-triangle">Atenção</Pill> : <Pill tone="cobalt">No fluxo</Pill>}
                      </td>
                      <td style={{ padding: "14px 18px", textAlign: "right" }}><LIcon name="chevron-right" size={18} color={C.ink3} /></td>
                    </tr>
                  );
                })}
              </tbody>
            </table>
          </div>
        </Card>
      </div>
    </div>
  );
}

function KPI({ ring, val, lab, foot, icon, tone }) {
  const toneColor = tone === "amber" ? C.amber : tone === "green" ? C.green : C.cobalt;
  return (
    <Card pad={20}>
      <div style={{ display: "flex", alignItems: "center", gap: 16 }}>
        {ring != null ? <Ring value={ring} size={64} stroke={7} /> : (
          <span style={{ width: 46, height: 46, borderRadius: 13, background: toneColor + "14", color: toneColor, display: "grid", placeItems: "center", flex: "none" }}><LIcon name={icon} size={22} stroke={2.1} /></span>
        )}
        <div>
          {val != null && <div style={{ fontSize: 28, fontWeight: 800, color: C.ink, lineHeight: 1 }}>{val}</div>}
          <div style={{ fontSize: 12.5, color: C.ink2, fontWeight: 700, marginTop: val != null ? 5 : 0 }}>{lab}</div>
          <div style={{ fontSize: 11.5, color: C.ink3, marginTop: 3 }}>{foot}</div>
        </div>
      </div>
    </Card>
  );
}

Object.assign(window, { VisaoGestor });
