/* ============================================================
   WORKSPACE CENTRADO NA PESSOA (RH/ADM) — a navegação principal.
   Esquerda: lista de pessoas. Direita: TUDO da pessoa selecionada
   num lugar (hoje · semana · documentos da etapa · tarefas · acesso).
   Substitui as 5 abas paralelas. Navegar = escolher a pessoa.
   ============================================================ */
function PessoasWorkspace({ done, meta, go, onNovo, toggle }) {
  const OE = window.OE;
  const cols = OE.colaboradores;
  const [selId, setSelId] = React.useState(cols[0] ? cols[0].id : null);

  if (cols.length === 0) {
    return (
      <Card pad={34} style={{ textAlign: "center" }}>
        <div style={{ color: C.cobalt, display: "flex", justifyContent: "center", marginBottom: 12 }}><LIcon name="user-plus" size={34} /></div>
        <div style={{ fontSize: 18, fontWeight: 800, color: C.ink }}>Comece cadastrando a primeira pessoa</div>
        <div style={{ fontSize: 14, color: C.ink2, marginTop: 8, lineHeight: 1.55, maxWidth: 460, margin: "8px auto 0" }}>
          Você cadastra a pessoa, gera o link de acesso dela e pronto: ela aparece aqui na lista e você acompanha tudo — o diário de hoje, o fechamento da semana e os documentos de cada etapa.
        </div>
        <div style={{ marginTop: 18 }}><Btn icon="user-plus" onClick={onNovo}>Cadastrar primeira pessoa</Btn></div>
      </Card>
    );
  }

  const sel = cols.find((c) => c.id === selId) || cols[0];

  const statusDe = (a, s) => {
    if (a.jamaisAcessou || a.alertaManha || a.alertaTarde) return { tone: "amber", label: "Precisa de você" };
    if (a.manha && a.tarde && s.status === "emdia") return { tone: "green", label: "Em dia" };
    return { tone: "cobalt", label: "Em andamento" };
  };

  return (
    <div style={{ display: "flex", gap: 20, alignItems: "flex-start", flexWrap: "wrap" }}>
      {/* ESQUERDA — lista de pessoas */}
      <div style={{ width: 290, flex: "1 1 250px", maxWidth: 330, display: "flex", flexDirection: "column", gap: 12 }}>
        <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", gap: 10 }}>
          <span style={{ fontSize: 12.5, fontWeight: 800, letterSpacing: ".04em", textTransform: "uppercase", color: C.ink3 }}>Pessoas ({cols.length})</span>
          <Btn variant="soft" size="sm" icon="user-plus" onClick={onNovo}>Nova</Btn>
        </div>
        <div style={{ display: "flex", flexDirection: "column", gap: 8 }}>
          {cols.map((c) => {
            const a = OE.atividadeColab(meta[c.id], done[c.id]);
            const s = OE.submissaoColab(meta[c.id], c.inicio);
            const st = statusDe(a, s);
            const dot = st.tone === "green" ? C.green : st.tone === "amber" ? C.amber : C.cobalt;
            const ativo = c.id === sel.id;
            return (
              <button key={c.id} onClick={() => setSelId(c.id)} style={{
                display: "flex", alignItems: "center", gap: 11, textAlign: "left", cursor: "pointer", fontFamily: "inherit",
                background: ativo ? "#fff" : "transparent", border: `1px solid ${ativo ? C.cobalt : C.line}`,
                borderRadius: 13, padding: "11px 13px", boxShadow: ativo ? "0 4px 14px -8px rgba(184,145,42,.5)" : "none",
              }}>
                <Avatar nome={c.nome} cor={c.cor} size={38} />
                <div style={{ minWidth: 0, flex: 1 }}>
                  <div style={{ fontWeight: 800, fontSize: 13.5, color: C.ink, whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis" }}>{c.nome}</div>
                  <div style={{ fontSize: 11.5, color: C.ink3, whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis" }}>{c.cargo || "—"}</div>
                </div>
                <span title={st.label} style={{ width: 9, height: 9, borderRadius: "50%", background: dot, flex: "none" }} />
              </button>
            );
          })}
        </div>
      </div>

      {/* DIREITA — tudo da pessoa */}
      <div style={{ flex: "999 1 420px", minWidth: 320 }}>
        <PessoaDetalhe c={sel} done={done} meta={meta} go={go} toggle={toggle} />
      </div>
    </div>
  );
}

function PessoaDetalhe({ c, done, meta, go, toggle }) {
  const OE = window.OE;
  const doneSet = done[c.id] || new Set();
  const a = OE.atividadeColab(meta[c.id], doneSet);
  const s = OE.submissaoColab(meta[c.id], c.inicio);
  const prog = OE.progressoColab(doneSet);
  const faseIdx = OE.faseAtual(doneSet);
  const fase = OE.PLAYBOOK[faseIdx];
  const completo = prog.pct === 100;
  const [copiado, setCopiado] = React.useState(false);

  const link = window.OS.magicLink(c.token);
  const primeiro = (c.nome || "").split(" ")[0];
  const cobrarHref = `https://wa.me/?text=${encodeURIComponent(`Oi, ${primeiro}! Passando pra lembrar do diário de hoje no onboarding — leva uns 5 min. Qualquer dúvida me chama. 🙏`)}`;
  function copiar() { try { navigator.clipboard.writeText(link); setCopiado(true); setTimeout(() => setCopiado(false), 1600); } catch (e) {} }

  const docs = [];
  fase.tarefas.forEach((t) => { if (t.tpl && !docs.find((d) => d.tpl === t.tpl)) docs.push({ tpl: t.tpl, nome: t.template }); });

  const Mini = ({ icon, children, right }) => (
    <div style={{ display: "flex", alignItems: "center", gap: 9, marginBottom: 12 }}>
      <span style={{ color: C.cobalt }}><LIcon name={icon} size={17} stroke={2.2} /></span>
      <span style={{ fontSize: 14.5, fontWeight: 800, color: C.ink }}>{children}</span>
      {right && <span style={{ marginLeft: "auto" }}>{right}</span>}
    </div>
  );

  const turnoCard = (titulo, icon, ok, alerta, prazo, quando) => {
    const tone = ok ? "green" : alerta ? "amber" : "gray";
    const bg = ok ? C.greenSoft : alerta ? C.amberSoft : C.bg;
    const bd = ok ? "#bfe6cd" : alerta ? "#f3d28a" : C.line;
    return (
      <div style={{ flex: "1 1 200px", background: bg, border: `1px solid ${bd}`, borderRadius: 13, padding: 16 }}>
        <div style={{ display: "flex", alignItems: "center", gap: 8, marginBottom: 8 }}>
          <span style={{ color: ok ? C.green : alerta ? C.amber : C.ink3 }}><LIcon name={icon} size={17} /></span>
          <span style={{ fontSize: 13.5, fontWeight: 800, color: C.ink }}>{titulo}</span>
          <span style={{ fontSize: 11, color: C.ink3, marginLeft: "auto" }}>{quando}</span>
        </div>
        {ok ? <Pill tone="green" icon="check">Preenchido</Pill>
          : alerta ? <Pill tone="amber" icon="alert-triangle">Atrasado (prazo {prazo}h)</Pill>
            : <Pill tone="gray" icon="clock">Aguardando (até {prazo}h)</Pill>}
      </div>
    );
  };

  return (
    <div style={{ display: "flex", flexDirection: "column", gap: 16 }}>
      {/* HEADER da pessoa */}
      <Card pad={0} style={{ overflow: "hidden" }}>
        <div style={{ display: "flex", alignItems: "center", gap: 15, padding: "18px 22px", borderBottom: `1px solid ${C.lineSoft}`, flexWrap: "wrap" }}>
          <Avatar nome={c.nome} cor={c.cor} size={50} />
          <div style={{ minWidth: 0, flex: 1 }}>
            <div style={{ fontSize: 19, fontWeight: 800, color: C.ink, letterSpacing: "-.01em" }}>{c.nome}</div>
            <div style={{ fontSize: 13, color: C.ink3 }}>{c.cargo || "—"}{c.area ? " · " + c.area : ""}</div>
          </div>
          {completo
            ? <Pill tone="green" icon="badge-check">Integração concluída</Pill>
            : <Pill tone="cobalt" icon={fase.icon}>Etapa {faseIdx + 1}/{OE.N_ETAPAS} · {fase.nome}</Pill>}
        </div>
        <div style={{ display: "flex", alignItems: "center", gap: 14, padding: "13px 22px" }}>
          <div style={{ flex: 1 }}>
            <div style={{ display: "flex", justifyContent: "space-between", fontSize: 12, marginBottom: 6 }}>
              <span style={{ color: C.ink3, fontWeight: 600 }}>Progresso da integração</span>
              <span style={{ color: C.ink, fontWeight: 800 }}>{prog.pct}%</span>
            </div>
            <Bar value={prog.pct} color={completo ? C.green : c.cor} />
          </div>
        </div>
      </Card>

      {/* HOJE */}
      <Card>
        <Mini icon="sun" right={(a.alertaManha || a.alertaTarde || a.jamaisAcessou)
          ? <a href={cobrarHref} target="_blank" rel="noopener noreferrer" style={{ display: "inline-flex", alignItems: "center", gap: 7, textDecoration: "none", background: C.amberSoft, color: "#9a6a12", border: "1px solid #f3d28a", fontWeight: 700, fontSize: 12.5, padding: "7px 13px", borderRadius: 10 }}><LIcon name="message-circle" size={15} /> Cobrar no WhatsApp</a>
          : <Pill tone="green" icon="check-check">Diário em dia</Pill>}>Diário de hoje</Mini>
        <div style={{ display: "flex", gap: 12, flexWrap: "wrap" }}>
          {turnoCard("Manhã", "sunrise", a.manha, a.alertaManha, OE.PRAZO_MANHA, "até 14h")}
          {turnoCard("Tarde", "sunset", a.tarde, a.alertaTarde, OE.PRAZO_TARDE, "até 19h")}
        </div>
        {a.jamaisAcessou && <div style={{ marginTop: 12, fontSize: 12.5, color: C.amber, fontWeight: 600, display: "flex", alignItems: "center", gap: 7 }}><LIcon name="link-2-off" size={15} /> Ainda não acessou o link de acesso. Reenvie abaixo.</div>}
      </Card>

      {/* ESTA SEMANA */}
      <Card>
        <Mini icon="calendar-days" right={s.fech ? <Pill tone="green" icon="check">Enviado · nota {s.fech.nota}</Pill> : <Pill tone="amber" icon="clock">Não enviou</Pill>}>Esta semana</Mini>
        <div style={{ display: "flex", gap: 8, flexWrap: "wrap", marginBottom: s.fech ? 14 : 0 }}>
          <Pill tone="cobalt" icon="calendar">Semana {s.semCobrada}</Pill>
          <Pill tone={s.fech && s.entFeitos < s.entTotal ? "amber" : "cobalt"} icon="package-check">{s.fech ? `${s.entFeitos}/${s.entTotal} entregáveis` : "—"}</Pill>
        </div>
        {s.fech ? (
          <div style={{ display: "grid", gridTemplateColumns: "repeat(auto-fit,minmax(240px,1fr))", gap: 12 }}>
            {OE.RELATO_SEMANAL.map((f) => s.fech[f.k] ? (
              <div key={f.k} style={{ background: C.bg, border: `1px solid ${C.lineSoft}`, borderRadius: 11, padding: 14 }}>
                <div style={{ fontSize: 10, fontWeight: 800, letterSpacing: ".08em", textTransform: "uppercase", color: C.cobaltDeep, marginBottom: 6 }}>{f.q}</div>
                <div style={{ fontSize: 12.5, color: C.ink2, lineHeight: 1.5 }}>{s.fech[f.k]}</div>
              </div>
            ) : null)}
          </div>
        ) : (
          <div style={{ fontSize: 12.5, color: C.ink3, marginTop: 4 }}>O fechamento da semana aparece aqui quando a pessoa enviar (toda sexta).</div>
        )}
      </Card>

      {/* DOCUMENTOS DA ETAPA */}
      <Card>
        <Mini icon="folder-open" right={<Btn variant="ghost" size="sm" icon="arrow-right" onClick={() => go("templates")}>Ver todos os modelos</Btn>}>Documentos desta etapa</Mini>
        {docs.length ? (
          <div style={{ display: "flex", gap: 8, flexWrap: "wrap" }}>
            {docs.map((d) => (
              <button key={d.tpl} onClick={() => go("templates", { tplId: OE_TPL.byNum(d.tpl).id })} style={{
                display: "inline-flex", alignItems: "center", gap: 7, background: C.cobaltSoft, border: `1px solid #e6d9b0`, borderRadius: 9,
                padding: "7px 12px", fontSize: 12.5, fontWeight: 700, color: C.cobaltDeep, cursor: "pointer", fontFamily: "inherit",
              }}><LIcon name="file-text" size={14} /> {d.nome}</button>
            ))}
          </div>
        ) : <div style={{ fontSize: 12.5, color: C.ink3 }}>Esta etapa não usa modelo específico.</div>}
      </Card>

      {/* TAREFAS DA ETAPA (checklist) */}
      <Card>
        <Mini icon="list-checks" right={<Btn variant="ghost" size="sm" icon="arrow-right" onClick={() => go("guia", { id: c.id })}>Abrir execução guiada</Btn>}>O que fazer nesta etapa</Mini>
        <div style={{ display: "flex", flexDirection: "column", gap: 2 }}>
          {fase.tarefas.map((t, i) => {
            const key = OE.taskKey(fase.id, i);
            const ok = doneSet.has(key);
            return (
              <div key={key} role="button" tabIndex={0} onClick={() => toggle(c.id, key)} style={{
                display: "flex", alignItems: "center", gap: 12, textAlign: "left", cursor: "pointer", fontFamily: "inherit",
                background: "transparent", border: "none", padding: "11px 4px", borderBottom: i < fase.tarefas.length - 1 ? `1px solid ${C.lineSoft}` : "none",
              }}>
                <span style={{ width: 22, height: 22, borderRadius: 7, flex: "none", display: "grid", placeItems: "center", background: ok ? C.green : "#fff", border: `1.5px solid ${ok ? C.green : C.line}`, color: "#fff" }}>{ok && <LIcon name="check" size={14} stroke={3} />}</span>
                <div style={{ flex: 1, minWidth: 0 }}>
                  <div style={{ fontSize: 13.5, fontWeight: 700, color: ok ? C.ink3 : C.ink, textDecoration: ok ? "line-through" : "none" }}>{t.titulo}</div>
                  <div style={{ fontSize: 11.5, color: C.ink3 }}>{t.resp} · {t.tempo}</div>
                </div>
                {t.tpl && (
                  <button onClick={(e) => { e.stopPropagation(); go("templates", { tplId: OE_TPL.byNum(t.tpl).id }); }} style={{
                    flex: "none", fontSize: 11, fontWeight: 700, color: C.cobaltDeep, background: C.cobaltSoft, border: "none", borderRadius: 999,
                    padding: "5px 10px", cursor: "pointer", fontFamily: "inherit", display: "inline-flex", alignItems: "center", gap: 5,
                  }}><LIcon name="file-text" size={12} /> Abrir modelo</button>
                )}
              </div>
            );
          })}
        </div>
      </Card>

      {/* ACESSO DA PESSOA */}
      <Card>
        <Mini icon="link">Link de acesso (sem senha)</Mini>
        <div style={{ display: "flex", gap: 8, flexWrap: "wrap", alignItems: "center" }}>
          <input readOnly value={link} onFocus={(e) => e.target.select()} style={{ flex: "1 1 240px", minWidth: 200, padding: "10px 12px", border: `1.5px solid #c7d6f7`, borderRadius: 10, fontSize: 12.5, fontFamily: "inherit", color: C.cobaltDeep, background: C.cobaltSoft, outline: "none", boxSizing: "border-box" }} />
          <Btn size="sm" variant="soft" icon={copiado ? "check" : "copy"} onClick={copiar}>{copiado ? "Copiado!" : "Copiar"}</Btn>
          <a href={cobrarHref} target="_blank" rel="noopener noreferrer" style={{ display: "inline-flex", alignItems: "center", gap: 7, textDecoration: "none", background: "#fff", color: C.ink2, border: `1px solid ${C.line}`, fontWeight: 700, fontSize: 13, padding: "8px 13px", borderRadius: 10 }}><LIcon name="message-circle" size={15} /> WhatsApp</a>
        </div>
        <div style={{ fontSize: 11.5, color: C.ink3, marginTop: 9, lineHeight: 1.5 }}>É só copiar e mandar pra ela. O link abre direto na visão dela, sem senha.</div>
      </Card>
    </div>
  );
}

Object.assign(window, { PessoasWorkspace });
