/* ============================================================
   PAINEL DA EQUIPE (RH/ADM) — o que cada pessoa está enviando.
   Lê o que o colaborador submeteu (meta.form.semanais + .diario)
   e mostra fechamento semanal, entregáveis, diário e status.
   ============================================================ */
function PainelEquipe({ meta }) {
  const OE = window.OE;
  const cols = OE.colaboradores;
  const [sel, setSel] = React.useState(cols[0] ? cols[0].id : null);

  const linhas = cols.map((c) => ({ c, s: OE.submissaoColab(meta[c.id], c.inicio) }));

  // KPIs
  const fecharam = linhas.filter((l) => l.s.fech).length;
  const atrasados = linhas.filter((l) => l.s.status === "atrasado").length;
  const turnosTot = linhas.reduce((n, l) => n + l.s.preench, 0);
  const turnosPoss = Math.max(1, linhas.length * 10);
  const pctDiario = Math.round((turnosTot / turnosPoss) * 100);
  const notas = linhas.map((l) => l.s.fech && l.s.fech.nota).filter((n) => typeof n === "number");
  const mediaSem = notas.length ? (notas.reduce((a, b) => a + b, 0) / notas.length).toFixed(1) : "—";

  const selRow = linhas.find((l) => l.c.id === sel);

  const statusPill = (st) =>
    st === "emdia" ? <Pill tone="green">Em dia</Pill>
      : st === "parcial" ? <Pill tone="cobalt">Parcial</Pill>
        : <Pill tone="amber" icon="alert-triangle">Atrasado</Pill>;

  const wd = ["S", "T", "Q", "Q", "S"];

  return (
    <div style={{ display: "flex", flexDirection: "column", gap: 24 }}>
      {/* KPIs */}
      <div style={{ display: "grid", gridTemplateColumns: "repeat(auto-fit,minmax(195px,1fr))", gap: 16 }}>
        <KPI val={`${fecharam}/${cols.length}`} lab="Fecharam a semana" foot="Enviaram a avaliação" icon="send" tone="green" />
        <KPI val={pctDiario + "%"} lab="Diários preenchidos" foot="Turnos da semana" icon="notebook-pen" />
        <KPI val={atrasados} lab="Atrasados no envio" foot="Sem fechamento/diário" icon="alert-triangle" tone={atrasados ? "amber" : "green"} />
        <KPI val={mediaSem} lab="Média auto-avaliação" foot="Última semana enviada" icon="gauge" />
      </div>

      {/* TABELA DE SUBMISSÕES */}
      <div>
        <SectionTitle icon="radar" sub="Diário da semana (5 turnos úteis), fechamento semanal, entregáveis e última atividade.">Submissões da semana</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", "Diário (semana)", "Fechamento semanal", "Entregáveis", "Última atividade", "Status"].map((h, i) => (
                    <th key={i} style={{ textAlign: "left", fontSize: 11, letterSpacing: ".08em", textTransform: "uppercase", color: C.ink3, fontWeight: 800, padding: "13px 16px", borderBottom: `1px solid ${C.line}`, whiteSpace: "nowrap" }}>{h}</th>
                  ))}
                </tr>
              </thead>
              <tbody>
                {linhas.map(({ c, s }) => (
                  <tr key={c.id} onClick={() => setSel(c.id)} style={{ borderBottom: `1px solid ${C.lineSoft}`, cursor: "pointer", background: sel === c.id ? C.bg : "transparent" }}>
                    <td style={{ padding: "14px 16px" }}>
                      <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: 11.5, color: C.ink3 }}>{c.cargo}</div></div>
                      </div>
                    </td>
                    <td style={{ padding: "14px 16px" }}>
                      <div style={{ display: "inline-flex", gap: 4 }}>
                        {s.turnos.map((t, i) => {
                          const k = t.manha && t.tarde ? "full" : (t.manha || t.tarde) ? "half" : "none";
                          const bg = k === "full" ? C.green : k === "half" ? C.gold : C.bgAlt;
                          const fg = k === "none" ? C.ink3 : "#fff";
                          return <span key={i} title={t.d} style={{ width: 16, height: 16, borderRadius: 5, background: bg, color: fg, display: "grid", placeItems: "center", fontSize: 8.5, fontWeight: 800, boxShadow: k === "none" ? `inset 0 0 0 1px ${C.line}` : "none" }}>{wd[i]}</span>;
                        })}
                      </div>
                    </td>
                    <td style={{ padding: "14px 16px" }}>
                      {s.fech ? <Pill tone="green" icon="check">Enviado · nota {s.fech.nota}</Pill> : <Pill tone="amber" icon="clock">Não enviou</Pill>}
                    </td>
                    <td style={{ padding: "14px 16px" }}>
                      <span style={{ fontWeight: 700, color: s.fech && s.entFeitos < s.entTotal ? C.amber : C.ink }}>{s.fech ? `${s.entFeitos}/${s.entTotal}` : "—"}</span>
                    </td>
                    <td style={{ padding: "14px 16px", color: C.ink2 }}>{s.ultima ? OE.fmtData(String(s.ultima).slice(0, 10)) : "—"}</td>
                    <td style={{ padding: "14px 16px" }}>{statusPill(s.status)}</td>
                  </tr>
                ))}
                {linhas.length === 0 && (
                  <tr><td colSpan={6} style={{ padding: "26px 16px", textAlign: "center", color: C.ink3 }}>Nenhum colaborador em integração ainda.</td></tr>
                )}
              </tbody>
            </table>
          </div>
        </Card>
      </div>

      {/* DRILL-IN: o que a pessoa escreveu */}
      {selRow && (selRow.s.fech || (meta[selRow.c.id] && (meta[selRow.c.id].form || {}).ideias || []).length) && (
        <div>
          <SectionTitle icon="file-search" sub="O conteúdo que a pessoa submeteu — clique numa linha acima para abrir.">Último envio · {selRow.c.nome}</SectionTitle>
          {selRow.s.fech && (
            <Card pad={20} style={{ marginBottom: 14 }}>
              <div style={{ display: "flex", gap: 8, flexWrap: "wrap", marginBottom: 16 }}>
                <Pill tone="cobalt" icon="calendar">Semana {selRow.s.semCobrada}</Pill>
                <Pill tone="green" icon="gauge">Média {selRow.s.fech.nota}</Pill>
                <Pill tone="cobalt" icon="package-check">{selRow.s.entFeitos}/{selRow.s.entTotal} entregáveis</Pill>
              </div>
              <div style={{ display: "grid", gridTemplateColumns: "repeat(auto-fit,minmax(260px,1fr))", gap: 14 }}>
                {OE.RELATO_SEMANAL.map((f) => (
                  selRow.s.fech[f.k] ? (
                    <div key={f.k} style={{ background: C.bg, border: `1px solid ${C.lineSoft}`, borderRadius: 12, padding: 16 }}>
                      <div style={{ fontSize: 10.5, fontWeight: 800, letterSpacing: ".1em", textTransform: "uppercase", color: C.cobaltDeep, marginBottom: 8 }}>{f.q}</div>
                      <div style={{ fontSize: 13, color: C.ink2, lineHeight: 1.55 }}>{selRow.s.fech[f.k]}</div>
                    </div>
                  ) : null
                ))}
              </div>
            </Card>
          )}
          {(() => {
            const ideias = (meta[selRow.c.id] && (meta[selRow.c.id].form || {}).ideias) || [];
            if (!ideias.length) return null;
            const tone = (p) => (p === "Alta" ? "amber" : p === "Baixa" ? "gray" : "cobalt");
            return (
              <Card pad={20}>
                <div style={{ display: "flex", alignItems: "center", gap: 9, marginBottom: 14 }}>
                  <span style={{ width: 30, height: 30, borderRadius: 9, background: C.cobaltSoft, color: C.cobalt, display: "grid", placeItems: "center", flex: "none" }}><LIcon name="lightbulb" size={16} /></span>
                  <span style={{ fontSize: 14.5, fontWeight: 800, color: C.ink }}>Ideias registradas ({ideias.length})</span>
                </div>
                <div style={{ display: "flex", flexDirection: "column", gap: 12 }}>
                  {ideias.map((it, i) => (
                    <div key={i} style={{ background: C.bg, border: `1px solid ${C.lineSoft}`, borderRadius: 12, padding: 16 }}>
                      <div style={{ display: "flex", alignItems: "center", gap: 10, marginBottom: 8 }}>
                        <span style={{ fontSize: 14, fontWeight: 800, color: C.ink, flex: 1 }}>{it.oque}</span>
                        <Pill tone={tone(it.prioridade)} icon="flag">{it.prioridade}</Pill>
                      </div>
                      <div style={{ display: "grid", gridTemplateColumns: "repeat(auto-fit,minmax(190px,1fr))", gap: 10 }}>
                        {[["Por quê", it.porque], ["Como", it.como], ["Resultado esperado", it.resultado]].map(([t, v]) => v ? (
                          <div key={t}>
                            <div style={{ fontSize: 10, fontWeight: 800, letterSpacing: ".04em", textTransform: "uppercase", color: C.ink3, marginBottom: 3 }}>{t}</div>
                            <div style={{ fontSize: 12.5, color: C.ink2, lineHeight: 1.5 }}>{v}</div>
                          </div>
                        ) : null)}
                      </div>
                    </div>
                  ))}
                </div>
              </Card>
            );
          })()}
        </div>
      )}
    </div>
  );
}

Object.assign(window, { PainelEquipe });
