/* Tela dela — Execução guiada de um colaborador */
function GuiaExecucao({ id, doneSet, onToggle, go, meta, onFormalize, onDrive, onParecer }) {
  const OE = window.OE;
  const c = OE.colab(id);
  const atualIdx = OE.faseAtual(doneSet);
  const [selIdx, setSelIdx] = React.useState(atualIdx);
  const [openTask, setOpenTask] = React.useState(null);

  // se a fase atual mudar (concluiu tudo), reposiciona seleção
  React.useEffect(() => { setSelIdx(OE.faseAtual(doneSet)); }, [id]);

  const prog = OE.progressoColab(doneSet);
  const fase = OE.PLAYBOOK[selIdx];
  const fp = OE.faseProgress(doneSet, fase.id);
  const completo = prog.pct === 100;
  const cmeta = (meta && meta[id]) || {};
  const formMap = cmeta.form || {};
  const driveMap = cmeta.drive || {};
  const formCount = OE.PLAYBOOK.filter((f) => formMap[f.id]).length;
  const parecer = cmeta.parecer || {};

  const toggle = (idx) => {
    const key = OE.taskKey(fase.id, idx);
    const wasDone = doneSet.has(key);
    onToggle(key);
    if (!wasDone) setOpenTask(null); // fecha ao concluir
  };

  return (
    <div style={{ display: "flex", flexDirection: "column", gap: 20 }}>
      {/* topo */}
      <button onClick={() => go("dash")} style={{ alignSelf: "flex-start", display: "inline-flex", alignItems: "center", gap: 7, background: "transparent", border: "none", color: C.ink3, fontWeight: 600, fontSize: 13.5, cursor: "pointer", fontFamily: "inherit", padding: 0 }}>
        <LIcon name="arrow-left" size={17} /> Voltar ao meu progresso
      </button>

      {/* header colaborador */}
      <Card pad={22}>
        <div style={{ display: "flex", alignItems: "center", gap: 16, flexWrap: "wrap" }}>
          <Avatar nome={c.nome} cor={c.cor} size={54} />
          <div style={{ flex: 1, minWidth: 200 }}>
            <div style={{ fontSize: 20, fontWeight: 800, color: C.ink, letterSpacing: "-.01em" }}>{c.nome}</div>
            <div style={{ fontSize: 13.5, color: C.ink2, marginTop: 2 }}>{c.cargo} · {c.area}</div>
            <div style={{ display: "flex", gap: 10, marginTop: 10, flexWrap: "wrap" }}>
              <Pill icon="briefcase">{c.modelo}</Pill>
              <Pill icon="layers">{c.area}</Pill>
              <Pill icon="calendar">Início {OE.fmtData(c.inicio)}</Pill>
            </div>
          </div>
          <div style={{ textAlign: "right", minWidth: 180 }}>
            <div style={{ fontSize: 12, color: C.ink3, fontWeight: 700, marginBottom: 6 }}>
              {completo ? "Onboarding concluído" : `Etapa ${atualIdx + 1} de ${OE.N_ETAPAS} · ${OE.PLAYBOOK[atualIdx].nome}`}
            </div>
            <div style={{ display: "flex", alignItems: "center", gap: 10 }}>
              <div style={{ flex: 1 }}><Bar value={prog.pct} color={completo ? C.green : c.cor} h={9} /></div>
              <span style={{ fontSize: 15, fontWeight: 800, color: C.ink }}>{prog.pct}%</span>
            </div>
            <div style={{ fontSize: 11.5, color: C.ink3, marginTop: 5 }}>{prog.done} de {prog.total} tarefas · {formCount}/{OE.N_ETAPAS} etapas formalizadas</div>
          </div>
        </div>
      </Card>

      {/* ENTREVISTA & PARECER DA AGÊNCIA */}
      <ParecerCard parecer={parecer} onParecer={(patch) => onParecer(id, patch)} />


      <div style={{ display: "grid", gridTemplateColumns: "270px 1fr", gap: 18, alignItems: "start" }} className="guiagrid">
        {/* STEPPER de etapas */}
        <Card pad={12}>
          <div style={{ fontSize: 11, fontWeight: 800, letterSpacing: ".1em", textTransform: "uppercase", color: C.ink3, padding: "6px 10px 10px" }}>As {OE.N_ETAPAS} etapas</div>
          <div style={{ display: "flex", flexDirection: "column", gap: 2 }}>
            {OE.PLAYBOOK.map((f, i) => {
              const fdone = OE.faseDone(doneSet, f.id);
              const isCur = i === atualIdx && !completo;
              const sel = i === selIdx;
              const p = OE.faseProgress(doneSet, f.id);
              return (
                <button key={f.id} onClick={() => { setSelIdx(i); setOpenTask(null); }} style={{
                  display: "flex", alignItems: "center", gap: 11, padding: "10px 11px", border: "none", borderRadius: 11,
                  background: sel ? C.cobaltSoft : "transparent", cursor: "pointer", textAlign: "left", fontFamily: "inherit", width: "100%",
                }}>
                  <span style={{
                    width: 26, height: 26, borderRadius: 8, flex: "none", display: "grid", placeItems: "center",
                    background: fdone ? C.green : isCur ? C.cobalt : C.lineSoft, color: fdone || isCur ? "#fff" : C.ink3,
                  }}>
                    {fdone ? <LIcon name="check" size={15} stroke={2.6} /> : <LIcon name={f.icon} size={14} stroke={2.2} />}
                  </span>
                  <span style={{ flex: 1, minWidth: 0 }}>
                    <span style={{ display: "block", fontSize: 13, fontWeight: 700, color: sel ? C.cobaltDeep : C.ink, lineHeight: 1.2 }}>{f.nome}</span>
                    <span style={{ display: "block", fontSize: 11, color: C.ink3, marginTop: 1 }}>{p.done}/{p.total} tarefas</span>
                  </span>
                  {isCur && <span style={{ flex: "none", width: 7, height: 7, borderRadius: "50%", background: C.cobalt }} />}
                </button>
              );
            })}
          </div>
        </Card>

        {/* PAINEL da etapa selecionada */}
        <div style={{ display: "flex", flexDirection: "column", gap: 14 }}>
          <Card pad={20} style={{ borderColor: selIdx === atualIdx && !completo ? C.cobalt : C.line }}>
            <div style={{ display: "flex", alignItems: "center", gap: 12, marginBottom: 6 }}>
              <span style={{ width: 38, height: 38, borderRadius: 11, background: C.cobaltSoft, color: C.cobalt, display: "grid", placeItems: "center", flex: "none" }}><LIcon name={fase.icon} size={20} stroke={2.2} /></span>
              <div>
                <div style={{ fontSize: 12, fontWeight: 700, color: C.ink3, letterSpacing: ".04em" }}>ETAPA {selIdx + 1} DE {OE.N_ETAPAS}</div>
                <div style={{ fontSize: 18, fontWeight: 800, color: C.ink, letterSpacing: "-.01em" }}>{fase.nome}</div>
              </div>
              <span style={{ marginLeft: "auto" }}>
                {fp.done === fp.total ? <Pill tone="green" icon="check-check">Etapa concluída</Pill> : <Pill tone="cobalt">{fp.done}/{fp.total} feitas</Pill>}
              </span>
            </div>
            <div style={{ fontSize: 13.5, color: C.ink2, lineHeight: 1.5, paddingLeft: 50 }}>{fase.objetivo}</div>
          </Card>

          {/* tarefas */}
          {fase.tarefas.map((t, idx) => {
            const key = OE.taskKey(fase.id, idx);
            const isDone = doneSet.has(key);
            const isOpen = openTask === idx;
            return (
              <Card key={idx} pad={0} style={{ overflow: "hidden", borderColor: isDone ? C.greenSoft : isOpen ? C.cobalt : C.line }}>
                <div style={{ display: "flex", alignItems: "flex-start", gap: 14, padding: "16px 18px" }}>
                  <button onClick={() => toggle(idx)} aria-label="concluir" style={{
                    width: 26, height: 26, flex: "none", marginTop: 1, borderRadius: 8, cursor: "pointer",
                    border: `2px solid ${isDone ? C.green : C.line}`, background: isDone ? C.green : "#fff",
                    color: "#fff", display: "grid", placeItems: "center", transition: "all .14s ease",
                  }}>{isDone && <LIcon name="check" size={15} stroke={3} />}</button>
                  <div style={{ flex: 1, minWidth: 0, cursor: "pointer" }} onClick={() => setOpenTask(isOpen ? null : idx)}>
                    <div style={{ display: "flex", alignItems: "center", gap: 10, flexWrap: "wrap" }}>
                      <span style={{ fontSize: 15, fontWeight: 700, color: isDone ? C.ink3 : C.ink, textDecoration: isDone ? "line-through" : "none" }}>{t.titulo}</span>
                      {!isDone && idx === fp.done && <Pill tone="amber" icon="arrow-down">Faça agora</Pill>}
                    </div>
                    <div style={{ display: "flex", gap: 13, marginTop: 7, flexWrap: "wrap" }}>
                      <Meta icon="user" t={t.resp} />
                      <Meta icon="clock" t={t.tempo} />
                      {t.tpl && (
                        <button onClick={(e) => { e.stopPropagation(); go("templates", { tplId: OE_TPL.byNum(t.tpl).id }); }} style={{ fontSize: 12, color: C.cobaltDeep, display: "inline-flex", alignItems: "center", gap: 5, fontWeight: 700, background: C.cobaltSoft, border: "none", borderRadius: 999, padding: "3px 10px", cursor: "pointer", fontFamily: "inherit" }}><LIcon name="file-text" size={13} />{t.template}</button>
                      )}
                    </div>
                  </div>
                  <button onClick={() => setOpenTask(isOpen ? null : idx)} style={{ flex: "none", background: "transparent", border: "none", cursor: "pointer", color: C.ink3, display: "inline-flex", alignItems: "center", gap: 5, fontFamily: "inherit", fontSize: 12.5, fontWeight: 700 }}>
                    {isOpen ? "Fechar" : "Como fazer"} <LIcon name={isOpen ? "chevron-up" : "chevron-down"} size={16} />
                  </button>
                </div>
                {isOpen && (
                  <div style={{ background: C.bg, borderTop: `1px solid ${C.line}`, padding: "18px 20px 20px" }}>
                    <div style={{ fontSize: 11, fontWeight: 800, letterSpacing: ".1em", textTransform: "uppercase", color: C.cobaltDeep, marginBottom: 14 }}>Passo a passo</div>
                    <ol style={{ margin: 0, padding: 0, listStyle: "none", display: "flex", flexDirection: "column", gap: 12 }}>
                      {t.como.map((passo, i) => (
                        <li key={i} style={{ display: "flex", gap: 12, alignItems: "flex-start" }}>
                          <span style={{ flex: "none", width: 22, height: 22, borderRadius: 7, background: C.cobalt, color: "#fff", fontSize: 11.5, fontWeight: 800, display: "grid", placeItems: "center", marginTop: 1 }}>{i + 1}</span>
                          <span style={{ fontSize: 13.5, color: C.ink2, lineHeight: 1.5 }}>{passo}</span>
                        </li>
                      ))}
                    </ol>
                    <div style={{ marginTop: 18, display: "flex", gap: 10 }}>
                      <Btn variant={isDone ? "ghost" : "green"} size="sm" icon={isDone ? "rotate-ccw" : "check"} onClick={() => toggle(idx)}>
                        {isDone ? "Desmarcar" : "Marcar como concluída"}
                      </Btn>
                    </div>
                  </div>
                )}
              </Card>
            );
          })}

          {/* FORMALIZAÇÃO DA ETAPA — e-mail + Drive */}
          <FormalizacaoEtapa
            fase={fase} allDone={fp.done === fp.total} total={fp.total}
            formDate={formMap[fase.id]} driveUrl={driveMap[fase.id]}
            onFormalize={() => onFormalize(id, fase.id)}
            onDrive={(url) => onDrive(id, fase.id, url)}
            isLast={selIdx >= OE.PLAYBOOK.length - 1}
            proxNome={selIdx < OE.PLAYBOOK.length - 1 ? OE.PLAYBOOK[selIdx + 1].nome : null}
            onNext={() => { setSelIdx(selIdx + 1); setOpenTask(null); window.scrollTo(0, 0); }}
          />
          {completo && (
            <Card pad={20} style={{ background: C.greenSoft, borderColor: "#bfe6cd", textAlign: "center" }}>
              <div style={{ color: C.green, display: "flex", justifyContent: "center", marginBottom: 8 }}><LIcon name="badge-check" size={32} /></div>
              <div style={{ fontWeight: 800, color: C.ink, fontSize: 16 }}>Onboarding de {c.nome} 100% concluído 🎉</div>
              <div style={{ fontSize: 13, color: C.ink2, marginTop: 4 }}>Todas as {OE.N_ETAPAS} etapas foram executadas.</div>
            </Card>
          )}
        </div>
      </div>
    </div>
  );
}

function Meta({ icon, t }) {
  return <span style={{ fontSize: 12, color: C.ink2, display: "inline-flex", alignItems: "center", gap: 5 }}><LIcon name={icon} size={13} color={C.ink3} />{t}</span>;
}

function fmtDateTime(iso) {
  try { return new Date(iso).toLocaleString("pt-BR", { day: "2-digit", month: "short", hour: "2-digit", minute: "2-digit" }); }
  catch (e) { return ""; }
}

function FormalizacaoEtapa({ fase, allDone, total, formDate, driveUrl, onFormalize, onDrive, isLast, proxNome, onNext }) {
  return (
    <Card pad={0} style={{ overflow: "hidden", borderColor: allDone ? "#bfe6cd" : C.line }}>
      <div style={{ padding: "16px 20px", background: allDone ? C.greenSoft : C.bg, borderBottom: `1px solid ${C.line}`, display: "flex", alignItems: "center", gap: 10 }}>
        <span style={{ color: allDone ? C.green : C.ink3 }}><LIcon name="shield-check" size={19} stroke={2.2} /></span>
        <div style={{ flex: 1 }}>
          <div style={{ fontSize: 14.5, fontWeight: 800, color: C.ink }}>Formalizar a etapa</div>
          <div style={{ fontSize: 12.5, color: C.ink2 }}>
            {allDone ? "Todas as tarefas feitas. Registre o e-mail e guarde os documentos." : `Conclua as ${total} tarefas para liberar a formalização por e-mail.`}
          </div>
        </div>
      </div>

      <div style={{ padding: "18px 20px", display: "flex", flexDirection: "column", gap: 16 }}>
        {/* E-MAIL */}
        <div style={{ display: "flex", alignItems: "center", gap: 13, flexWrap: "wrap" }}>
          <span style={{ width: 38, height: 38, borderRadius: 11, flex: "none", background: C.cobaltSoft, color: C.cobalt, display: "grid", placeItems: "center" }}><LIcon name="mail" size={19} stroke={2.1} /></span>
          <div style={{ flex: 1, minWidth: 180 }}>
            <div style={{ fontSize: 13.5, fontWeight: 700, color: C.ink }}>Formalização por e-mail</div>
            {formDate
              ? <div style={{ fontSize: 12.5, color: C.green, fontWeight: 700, display: "inline-flex", alignItems: "center", gap: 6, marginTop: 2 }}><LIcon name="check-circle-2" size={14} />Enviado em {fmtDateTime(formDate)}</div>
              : <div style={{ fontSize: 12.5, color: C.ink3, marginTop: 2 }}>Envia o registro da etapa ao colaborador.</div>}
          </div>
          {formDate
            ? <Btn variant="ghost" size="sm" icon="rotate-ccw" onClick={onFormalize}>Reenviar</Btn>
            : <Btn variant={allDone ? "primary" : "ghost"} size="sm" icon="send" disabled={!allDone} onClick={allDone ? onFormalize : undefined}>Formalizar por e-mail</Btn>}
        </div>

        {/* DRIVE */}
        {fase.drive && (
          <div style={{ borderTop: `1px solid ${C.lineSoft}`, paddingTop: 16, display: "flex", alignItems: "center", gap: 13, flexWrap: "wrap" }}>
            <span style={{ width: 38, height: 38, borderRadius: 11, flex: "none", background: "#eaf6ee", color: C.green, display: "grid", placeItems: "center" }}><LIcon name="folder" size={19} stroke={2.1} /></span>
            <div style={{ flex: 1, minWidth: 180 }}>
              <div style={{ fontSize: 13.5, fontWeight: 700, color: C.ink }}>Documentos no Drive</div>
              <DriveField driveUrl={driveUrl} onDrive={onDrive} />
            </div>
          </div>
        )}
      </div>

      {/* AVANÇAR */}
      {allDone && !isLast && (
        <div style={{ padding: "14px 20px", background: C.greenSoft, borderTop: "1px solid #bfe6cd", display: "flex", alignItems: "center", gap: 12 }}>
          <span style={{ color: C.green }}><LIcon name="party-popper" size={20} /></span>
          <div style={{ flex: 1, fontSize: 13.5, color: C.ink2 }}>Etapa <b style={{ color: C.ink }}>"{fase.nome}"</b> pronta. Avance para: {proxNome}.</div>
          <Btn variant="green" size="sm" icon="arrow-right" onClick={onNext}>Próxima etapa</Btn>
        </div>
      )}
    </Card>
  );
}

function DriveField({ driveUrl, onDrive }) {
  const [editing, setEditing] = React.useState(false);
  const [val, setVal] = React.useState(driveUrl || "");
  React.useEffect(() => { setVal(driveUrl || ""); }, [driveUrl]);

  if (driveUrl && !editing) {
    return (
      <div style={{ display: "flex", alignItems: "center", gap: 8, marginTop: 4, flexWrap: "wrap" }}>
        <a href={driveUrl} target="_blank" rel="noreferrer" style={{ display: "inline-flex", alignItems: "center", gap: 6, fontSize: 12.5, fontWeight: 700, color: C.cobalt, background: C.cobaltSoft, padding: "5px 11px", borderRadius: 999, maxWidth: 320, overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }}>
          <LIcon name="link" size={13} />Abrir pasta no Drive
        </a>
        <button onClick={() => setEditing(true)} style={{ background: "transparent", border: "none", color: C.ink3, cursor: "pointer", fontSize: 12, fontWeight: 700, fontFamily: "inherit" }}>Trocar</button>
      </div>
    );
  }
  return (
    <div style={{ display: "flex", gap: 8, marginTop: 6, flexWrap: "wrap" }}>
      <input value={val} onChange={(e) => setVal(e.target.value)} placeholder="Cole o link da pasta do Google Drive..."
        style={{ flex: 1, minWidth: 200, padding: "8px 12px", border: `1px solid ${C.line}`, borderRadius: 9, fontSize: 13, fontFamily: "inherit", color: C.ink, outline: "none" }} />
      <Btn variant="soft" size="sm" icon="save" onClick={() => { onDrive(val.trim()); setEditing(false); }}>Salvar</Btn>
    </div>
  );
}

/* Card de entrevista + parecer da agência (preenchido por candidato, persistido) */
function ParecerCard({ parecer, onParecer }) {
  const [open, setOpen] = React.useState(false);
  const [pontos, setPontos] = React.useState(parecer.pontos || "");
  const [laudo, setLaudo] = React.useState(parecer.laudo || "");
  const rec = parecer.rec || null;
  React.useEffect(() => { setPontos(parecer.pontos || ""); setLaudo(parecer.laudo || ""); }, [parecer.pontos, parecer.laudo]);

  const preenchido = !!(parecer.pontos || parecer.laudo || parecer.rec);
  const recMap = {
    avancar: ["Avançar", "green", "thumbs-up"],
    atencao: ["Com ressalvas", "amber", "alert-triangle"],
    reprovar: ["Não recomendado", "red", "thumbs-down"],
  };

  return (
    <Card pad={0} style={{ overflow: "hidden", borderColor: preenchido ? "#c7d6f7" : C.line }}>
      <button onClick={() => setOpen((o) => !o)} style={{ width: "100%", padding: "16px 20px", background: preenchido ? C.cobaltSoft : C.bg, border: "none", borderBottom: open ? `1px solid ${C.line}` : "none", display: "flex", alignItems: "center", gap: 11, cursor: "pointer", fontFamily: "inherit", textAlign: "left" }}>
        <span style={{ width: 38, height: 38, borderRadius: 11, flex: "none", background: "#fff", color: C.cobalt, display: "grid", placeItems: "center", border: `1px solid ${C.line}` }}><LIcon name="clipboard-pen-line" size={19} stroke={2.1} /></span>
        <div style={{ flex: 1 }}>
          <div style={{ fontSize: 14.5, fontWeight: 800, color: C.ink }}>Entrevista & parecer da agência</div>
          <div style={{ fontSize: 12.5, color: C.ink2 }}>{preenchido ? "Avaliação registrada — clique para ver/editar." : "Registre os pontos da entrevista e o parecer técnico do candidato."}</div>
        </div>
        {rec && recMap[rec] && <Pill tone={recMap[rec][1]} icon={recMap[rec][2]}>{recMap[rec][0]}</Pill>}
        <LIcon name={open ? "chevron-up" : "chevron-down"} size={18} color={C.ink3} />
      </button>
      {open && (
        <div style={{ padding: "20px", display: "flex", flexDirection: "column", gap: 18 }}>
          <div>
            <label style={{ fontSize: 12.5, fontWeight: 700, color: C.ink, display: "block", marginBottom: 7 }}>Pontos da entrevista</label>
            <textarea value={pontos} onChange={(e) => setPontos(e.target.value)} onBlur={() => onParecer({ pontos: pontos.trim() })}
              placeholder="Destaques, competências, fit cultural, pontos de atenção observados na conversa..."
              style={{ width: "100%", minHeight: 84, resize: "vertical", padding: "11px 13px", border: `1.5px solid ${C.line}`, borderRadius: 10, fontSize: 13.5, fontFamily: "inherit", color: C.ink, outline: "none", lineHeight: 1.5, boxSizing: "border-box" }} />
          </div>
          <div>
            <label style={{ fontSize: 12.5, fontWeight: 700, color: C.ink, display: "block", marginBottom: 7 }}>Parecer técnico da agência</label>
            <textarea value={laudo} onChange={(e) => setLaudo(e.target.value)} onBlur={() => onParecer({ laudo: laudo.trim() })}
              placeholder="Avaliação consolidada da agência sobre o candidato para esta vaga..."
              style={{ width: "100%", minHeight: 84, resize: "vertical", padding: "11px 13px", border: `1.5px solid ${C.line}`, borderRadius: 10, fontSize: 13.5, fontFamily: "inherit", color: C.ink, outline: "none", lineHeight: 1.5, boxSizing: "border-box" }} />
          </div>
          <div>
            <label style={{ fontSize: 12.5, fontWeight: 700, color: C.ink, display: "block", marginBottom: 8 }}>Recomendação</label>
            <div style={{ display: "flex", gap: 9, flexWrap: "wrap" }}>
              {Object.keys(recMap).map((k) => {
                const [lab, tone, ic] = recMap[k];
                const on = rec === k;
                const colr = tone === "green" ? C.green : tone === "amber" ? C.amber : C.red;
                return (
                  <button key={k} onClick={() => onParecer({ rec: on ? null : k })} style={{
                    display: "inline-flex", alignItems: "center", gap: 7, padding: "9px 15px", borderRadius: 10, cursor: "pointer", fontFamily: "inherit", fontWeight: 700, fontSize: 13,
                    border: `1.5px solid ${on ? colr : C.line}`, background: on ? colr + "14" : "#fff", color: on ? colr : C.ink2,
                  }}>
                    <LIcon name={ic} size={15} />{lab}
                  </button>
                );
              })}
            </div>
          </div>
        </div>
      )}
    </Card>
  );
}

Object.assign(window, { GuiaExecucao });
