/* Tela dela — "Meu progresso" (visão de execução prioritária) */
function MeuProgresso({ done, go }) {
  const OE = window.OE;
  const cols = OE.colaboradores;

  // progresso geral (todas as tarefas das 4 pessoas)
  let totalDone = 0, totalAll = 0, concluidos = 0;
  cols.forEach((c) => {
    const p = OE.progressoColab(done[c.id]);
    totalDone += p.done; totalAll += p.total;
    if (p.pct === 100) concluidos++;
  });
  const pctGeral = Math.round((totalDone / totalAll) * 100);

  // próxima ação: colaborador com menor progresso que ainda tem pendência
  const comPendencia = cols
    .map((c) => ({ c, prog: OE.progressoColab(done[c.id]), prox: OE.proximaTarefa(done[c.id]) }))
    .filter((x) => x.prox);
  comPendencia.sort((a, b) => a.prog.pct - b.prog.pct);
  const foco = comPendencia[0];

  // avanço por etapa (quantos dos 4 concluíram cada etapa)
  const porEtapa = OE.PLAYBOOK.map((f) => {
    const n = cols.filter((c) => OE.faseDone(done[c.id], f.id)).length;
    return { f, n, total: cols.length };
  });

  return (
    <div style={{ display: "flex", flexDirection: "column", gap: 26 }}>
      {/* HERO progresso geral */}
      <div style={{
        background: "linear-gradient(120deg,#0E1A30,#1b2c4e 52%,#243B66)", borderRadius: 20, padding: "28px 30px",
        color: "#fff", display: "flex", alignItems: "center", gap: 30, flexWrap: "wrap",
      }}>
        <Ring value={pctGeral} size={108} stroke={11} color="#fff" textColor="#fff" trackColor="rgba(255,255,255,.22)" />
        <div style={{ flex: 1, minWidth: 240 }}>
          <div style={{ fontSize: 12, fontWeight: 700, letterSpacing: ".12em", textTransform: "uppercase", color: "#EAD08A" }}>Seu progresso geral</div>
          <div style={{ fontSize: 26, fontWeight: 800, letterSpacing: "-.02em", margin: "6px 0 4px", lineHeight: 1.15 }}>
            Você já concluiu {totalDone} de {totalAll} tarefas
          </div>
          <div style={{ fontSize: 14.5, color: "#aeb9d0", lineHeight: 1.5 }}>
            {concluidos > 0 ? `${concluidos} onboarding concluído · ` : ""}{cols.length - concluidos} em andamento. Continue de onde parou — uma tarefa por vez.
          </div>
        </div>
        <div style={{ display: "flex", gap: 22 }}>
          <Stat n={cols.length} l="Pessoas" />
          <Stat n={concluidos} l="Concluídos" />
          <Stat n={totalAll - totalDone} l="Tarefas restantes" />
        </div>
      </div>

      {/* PRÓXIMA AÇÃO */}
      {foco && (
        <div>
          <SectionTitle icon="circle-play" sub="O próximo passo mais importante agora. Faça este — depois o sistema te mostra o seguinte.">Sua próxima ação</SectionTitle>
          <Card pad={0} style={{ overflow: "hidden", borderColor: C.cobalt }}>
            <div style={{ display: "flex", flexWrap: "wrap" }}>
              <div style={{ flex: 1, minWidth: 280, padding: "24px 26px" }}>
                <div style={{ display: "flex", alignItems: "center", gap: 10, marginBottom: 14 }}>
                  <Avatar nome={foco.c.nome} cor={foco.c.cor} size={32} />
                  <div>
                    <div style={{ fontWeight: 700, fontSize: 13.5, color: C.ink }}>{foco.c.nome}</div>
                    <div style={{ fontSize: 12, color: C.ink3 }}>{foco.c.cargo}</div>
                  </div>
                  <span style={{ marginLeft: "auto" }}><Pill tone="cobalt" icon={foco.prox.fase.icon}>Etapa: {foco.prox.fase.nome}</Pill></span>
                </div>
                <div style={{ fontSize: 20, fontWeight: 800, color: C.ink, letterSpacing: "-.01em", marginBottom: 8 }}>{foco.prox.tarefa.titulo}</div>
                <div style={{ display: "flex", gap: 14, marginBottom: 16, flexWrap: "wrap" }}>
                  <span style={{ fontSize: 12.5, color: C.ink2, display: "inline-flex", alignItems: "center", gap: 6 }}><LIcon name="user" size={14} />{foco.prox.tarefa.resp}</span>
                  <span style={{ fontSize: 12.5, color: C.ink2, display: "inline-flex", alignItems: "center", gap: 6 }}><LIcon name="clock" size={14} />{foco.prox.tarefa.tempo}</span>
                  {foco.prox.tarefa.template && <span style={{ fontSize: 12.5, color: C.cobalt, display: "inline-flex", alignItems: "center", gap: 6 }}><LIcon name="file" size={14} />{foco.prox.tarefa.template}</span>}
                </div>
                <Btn icon="arrow-right" onClick={() => go("guia", { id: foco.c.id })}>Fazer agora</Btn>
              </div>
              <div style={{ width: 320, background: C.cobaltSoft, padding: "22px 24px", borderLeft: `1px solid ${C.line}` }} className="proxcomo">
                <div style={{ fontSize: 11, fontWeight: 800, letterSpacing: ".1em", textTransform: "uppercase", color: C.cobaltDeep, marginBottom: 12 }}>Como fazer</div>
                <ol style={{ margin: 0, paddingLeft: 0, listStyle: "none", display: "flex", flexDirection: "column", gap: 9 }}>
                  {foco.prox.tarefa.como.map((passo, i) => (
                    <li key={i} style={{ display: "flex", gap: 10, fontSize: 13, color: C.ink2, lineHeight: 1.45 }}>
                      <span style={{ flex: "none", width: 19, height: 19, borderRadius: 6, background: C.cobalt, color: "#fff", fontSize: 11, fontWeight: 800, display: "grid", placeItems: "center" }}>{i + 1}</span>
                      <span>{passo}</span>
                    </li>
                  ))}
                </ol>
              </div>
            </div>
          </Card>
        </div>
      )}

      {/* COLABORADORES */}
      <div>
        <SectionTitle icon="users" sub="Onde cada pessoa está na jornada. Clique para continuar a execução.">Seus colaboradores</SectionTitle>
        <div style={{ display: "grid", gridTemplateColumns: "repeat(auto-fill,minmax(290px,1fr))", gap: 16 }}>
          {cols.map((c) => {
            const prog = OE.progressoColab(done[c.id]);
            const atualIdx = OE.faseAtual(done[c.id]);
            const fase = OE.PLAYBOOK[atualIdx];
            const prox = OE.proximaTarefa(done[c.id]);
            const completo = prog.pct === 100;
            return (
              <Card key={c.id} pad={20} style={{ cursor: "pointer", transition: "box-shadow .15s ease" }} >
                <div onClick={() => go("guia", { id: c.id })} style={{ display: "flex", flexDirection: "column", gap: 14, height: "100%" }}>
                  <div style={{ display: "flex", alignItems: "center", gap: 12 }}>
                    <Avatar nome={c.nome} cor={c.cor} size={44} />
                    <div style={{ minWidth: 0 }}>
                      <div style={{ fontWeight: 800, fontSize: 15, color: C.ink, lineHeight: 1.2 }}>{c.nome}</div>
                      <div style={{ fontSize: 12.5, color: C.ink3, whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis" }}>{c.cargo}</div>
                    </div>
                  </div>
                  <div>
                    {completo
                      ? <Pill tone="green" icon="badge-check">Onboarding concluído</Pill>
                      : <Pill tone="cobalt" icon={fase.icon}>Etapa {atualIdx + 1}/{OE.N_ETAPAS} · {fase.nome}</Pill>}
                  </div>
                  <div style={{ marginTop: "auto" }}>
                    <div style={{ display: "flex", justifyContent: "space-between", fontSize: 12, marginBottom: 7 }}>
                      <span style={{ color: C.ink3, fontWeight: 600 }}>Progresso</span>
                      <span style={{ color: C.ink, fontWeight: 800 }}>{prog.pct}%</span>
                    </div>
                    <Bar value={prog.pct} color={completo ? C.green : c.cor} />
                    <div style={{ marginTop: 12, fontSize: 12.5, color: C.ink2, display: "flex", alignItems: "center", gap: 7, minHeight: 18 }}>
                      {prox
                        ? <><LIcon name="corner-down-right" size={14} color={C.ink3} /><span style={{ overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }}>A seguir: <b style={{ color: C.ink }}>{prox.tarefa.titulo}</b></span></>
                        : <><LIcon name="check-check" size={14} color={C.green} /><span>Tudo feito.</span></>}
                    </div>
                  </div>
                  <Btn variant={completo ? "ghost" : "soft"} size="sm" icon={completo ? "eye" : "arrow-right"} style={{ width: "100%" }}>
                    {completo ? "Ver execução" : "Continuar"}
                  </Btn>
                </div>
              </Card>
            );
          })}
        </div>
      </div>

      {/* AVANÇO POR ETAPA */}
      <div>
        <SectionTitle icon="bar-chart-3" sub="Em quantas pessoas cada etapa já foi concluída. Veja onde está o gargalo.">Avanço por etapa</SectionTitle>
        <Card>
          <div style={{ display: "flex", flexDirection: "column", gap: 2 }}>
            {porEtapa.map(({ f, n, total }, i) => {
              const pct = Math.round((n / total) * 100);
              const cor = pct === 100 ? C.green : pct === 0 ? C.ink3 : C.cobalt;
              return (
                <div key={f.id} style={{ display: "grid", gridTemplateColumns: "28px 150px 1fr 70px", gap: 14, alignItems: "center", padding: "10px 0", borderBottom: i < porEtapa.length - 1 ? `1px solid ${C.lineSoft}` : "none" }}>
                  <span style={{ width: 26, height: 26, borderRadius: 8, background: cor + "1a", color: cor, display: "grid", placeItems: "center" }}><LIcon name={f.icon} size={14} stroke={2.2} /></span>
                  <span style={{ fontSize: 13, fontWeight: 700, color: C.ink }}>{i + 1}. {f.nome}</span>
                  <Bar value={pct} color={cor} h={9} />
                  <span style={{ fontSize: 12.5, fontWeight: 700, color: C.ink2, textAlign: "right" }}>{n}/{total} pessoas</span>
                </div>
              );
            })}
          </div>
        </Card>
      </div>
    </div>
  );
}

function Stat({ n, l }) {
  return (
    <div style={{ textAlign: "center" }}>
      <div style={{ fontSize: 28, fontWeight: 800, lineHeight: 1 }}>{n}</div>
      <div style={{ fontSize: 11, color: "#EAD08A", fontWeight: 700, marginTop: 5, letterSpacing: ".03em" }}>{l}</div>
    </div>
  );
}

Object.assign(window, { MeuProgresso });
