/* ============================================================
   VISÃO DO COLABORADOR — acesso por link mágico (token), sem senha.
   Só o que é dele: boas-vindas, plano, minhas tarefas, diário e
   auto-avaliação de 30 dias. Persiste via RPCs (OS.colab*).
   ============================================================ */
function ColabView({ token, bundle }) {
  const OE = window.OE;
  const c = bundle.colaborador;
  const [done, setDone] = React.useState(() => new Set(bundle.done || []));
  const [diario, setDiario] = React.useState(() => bundle.diario || []);
  const [aval, setAval] = React.useState(() => bundle.avaliacao || {});
  const [toast, setToast] = React.useState("");

  const flash = (m) => { setToast(m); setTimeout(() => setToast(""), 2200); };

  // registra o acesso (p/ o painel do Dono saber quem já entrou)
  React.useEffect(() => { if (c && c.id) window.OS.colabMarkAccess(c.id).catch(() => {}); }, [c && c.id]);

  // tarefas que são DELE (resp Colaborador), agrupadas por etapa
  const minhasEtapas = OE.PLAYBOOK
    .map((f) => ({ f, tarefas: f.tarefas.map((t, i) => ({ t, key: OE.taskKey(f.id, i) })).filter((x) => x.t.resp === "Colaborador") }))
    .filter((g) => g.tarefas.length);
  const minhasKeys = minhasEtapas.flatMap((g) => g.tarefas.map((x) => x.key));
  const feitas = minhasKeys.filter((k) => done.has(k)).length;
  const pct = minhasKeys.length ? Math.round((feitas / minhasKeys.length) * 100) : 0;

  async function toggle(key) {
    const isNow = !done.has(key);
    setDone((prev) => { const n = new Set(prev); if (isNow) n.add(key); else n.delete(key); return n; });
    try { await window.OS.colabToggle(token, key, isNow); } catch (e) { flash("Não consegui salvar. Tente de novo."); }
  }

  const primeiroNome = (c.nome || "").split(" ")[0];

  return (
    <div style={{ minHeight: "100vh", background: C.bg }}>
      {/* topo */}
      <header style={{ position: "sticky", top: 0, zIndex: 40, background: "rgba(255,255,255,.92)", backdropFilter: "blur(10px)", borderBottom: `1px solid ${C.line}` }}>
        <div style={{ maxWidth: 920, margin: "0 auto", padding: "13px 22px", display: "flex", alignItems: "center", gap: 12 }}>
          <div style={{ width: 32, height: 32, borderRadius: 9, background: "linear-gradient(150deg,#27406e,#16233F)", display: "grid", placeItems: "center", color: "#fff" }}><LIcon name="rocket" size={17} stroke={2.3} /></div>
          <div style={{ fontWeight: 800, fontSize: 14.5, color: C.ink }}>Sua integração · ASCEND</div>
          <div style={{ marginLeft: "auto", display: "flex", alignItems: "center", gap: 9 }}>
            <Avatar nome={c.nome} cor={c.cor} size={32} />
            <div style={{ textAlign: "right" }} className="userlbl">
              <div style={{ fontSize: 12.5, fontWeight: 700, color: C.ink, lineHeight: 1.1 }}>{primeiroNome}</div>
              <div style={{ fontSize: 10.5, color: C.ink3 }}>{c.cargo}</div>
            </div>
          </div>
        </div>
      </header>

      <main style={{ maxWidth: 920, margin: "0 auto", padding: "24px 22px 80px", display: "flex", flexDirection: "column", gap: 26 }}>
        {/* HERO */}
        <div style={{ background: "linear-gradient(120deg,#0E1A30,#1b2c4e 52%,#243B66)", borderRadius: 20, padding: "28px 30px", color: "#fff", display: "flex", alignItems: "center", gap: 26, flexWrap: "wrap" }}>
          <Ring value={pct} size={104} 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" }}>Bem-vindo(a) à ASCEND</div>
            <div style={{ fontSize: 25, fontWeight: 800, letterSpacing: "-.02em", margin: "6px 0 6px", lineHeight: 1.15 }}>Olá, {primeiroNome}! 👋</div>
            <div style={{ fontSize: 14.5, color: "#aeb9d0", lineHeight: 1.5 }}>
              Sua missão no 1º mês: <b style={{ color: "#EAD08A" }}>conhecer e mapear sua área</b>, <b style={{ color: "#EAD08A" }}>escrever os processos</b> e entregar um <b style={{ color: "#EAD08A" }}>diagnóstico</b>. Você aprende fazendo — e a gente acompanha de perto.
            </div>
          </div>
        </div>

        {/* PLANO 1ª SEMANA */}
        <section>
          <SectionTitle icon="calendar-check" sub="Os 5 primeiros dias, passo a passo. Sem pressa — um dia de cada vez.">Sua 1ª semana</SectionTitle>
          <div style={{ display: "grid", gridTemplateColumns: "repeat(auto-fit,minmax(220px,1fr))", gap: 14 }}>
            {OE.PLANO_SEMANA1.map((d, i) => (
              <Card key={i} pad={18} style={{ borderTop: `3px solid ${C.cobalt}` }}>
                <div style={{ fontSize: 12, fontWeight: 800, color: C.cobalt, letterSpacing: ".04em" }}>{d.dia}</div>
                <div style={{ fontSize: 15, fontWeight: 800, color: C.ink, margin: "3px 0 12px" }}>{d.foco}</div>
                <ul style={{ margin: 0, padding: 0, listStyle: "none", display: "flex", flexDirection: "column", gap: 9 }}>
                  {d.itens.map((it, j) => (
                    <li key={j} style={{ display: "flex", gap: 8, fontSize: 12.5, color: C.ink2, lineHeight: 1.45 }}>
                      <span style={{ color: C.cobalt, flex: "none", marginTop: 2 }}><LIcon name="check" size={13} stroke={2.6} /></span>{it}
                    </li>
                  ))}
                </ul>
              </Card>
            ))}
          </div>
        </section>

        {/* PLANO 30 DIAS */}
        <section>
          <SectionTitle icon="calendar-range" sub="A visão do mês inteiro — do mapa ao diagnóstico.">Seus primeiros 30 dias</SectionTitle>
          <Card pad={0} style={{ overflow: "hidden" }}>
            {OE.PLANO_30DIAS.map((w, i) => (
              <div key={i} style={{ display: "grid", gridTemplateColumns: "150px 1fr", gap: 16, padding: "16px 20px", borderBottom: i < OE.PLANO_30DIAS.length - 1 ? `1px solid ${C.lineSoft}` : "none", alignItems: "start" }}>
                <div>
                  <div style={{ display: "inline-flex", alignItems: "center", justifyContent: "center", width: 28, height: 28, borderRadius: 9, background: C.cobalt, color: "#fff", fontWeight: 800, fontSize: 13, marginBottom: 6 }}>{i + 1}</div>
                  <div style={{ fontSize: 12, fontWeight: 800, color: C.ink3 }}>{w.semana}</div>
                  <div style={{ fontSize: 14, fontWeight: 800, color: C.ink, marginTop: 2 }}>{w.foco}</div>
                </div>
                <ul style={{ margin: 0, padding: 0, listStyle: "none", display: "flex", flexDirection: "column", gap: 7 }}>
                  {w.itens.map((it, j) => (
                    <li key={j} style={{ display: "flex", gap: 9, fontSize: 13, color: C.ink2, lineHeight: 1.45 }}>
                      <span style={{ color: C.cobalt, flex: "none", marginTop: 2 }}><LIcon name="dot" size={16} stroke={3} /></span>{it}
                    </li>
                  ))}
                </ul>
              </div>
            ))}
          </Card>
        </section>

        {/* MINHAS TAREFAS */}
        <section>
          <SectionTitle icon="list-checks" sub="Marque conforme for concluindo. Isso atualiza o RH automaticamente.">Minhas tarefas</SectionTitle>
          <div style={{ display: "flex", flexDirection: "column", gap: 14 }}>
            {minhasEtapas.map((g) => (
              <Card key={g.f.id} pad={18}>
                <div style={{ display: "flex", alignItems: "center", gap: 9, marginBottom: 12 }}>
                  <span style={{ width: 30, height: 30, borderRadius: 9, background: C.cobaltSoft, color: C.cobalt, display: "grid", placeItems: "center", flex: "none" }}><LIcon name={g.f.icon} size={16} stroke={2.2} /></span>
                  <span style={{ fontSize: 14.5, fontWeight: 800, color: C.ink }}>{g.f.nome}</span>
                </div>
                <div style={{ display: "flex", flexDirection: "column", gap: 9 }}>
                  {g.tarefas.map(({ t, key }) => {
                    const isDone = done.has(key);
                    return (
                      <button key={key} onClick={() => toggle(key)} style={{
                        display: "flex", alignItems: "flex-start", gap: 12, textAlign: "left", cursor: "pointer", fontFamily: "inherit",
                        background: isDone ? C.greenSoft : C.bg, border: `1px solid ${isDone ? "#bfe6cd" : C.line}`, borderRadius: 12, padding: "12px 14px",
                      }}>
                        <span style={{ width: 24, height: 24, flex: "none", marginTop: 1, borderRadius: 7, border: `2px solid ${isDone ? C.green : C.line}`, background: isDone ? C.green : "#fff", color: "#fff", display: "grid", placeItems: "center" }}>{isDone && <LIcon name="check" size={14} stroke={3} />}</span>
                        <span style={{ flex: 1 }}>
                          <span style={{ display: "block", fontSize: 14, fontWeight: 700, color: isDone ? C.ink3 : C.ink, textDecoration: isDone ? "line-through" : "none" }}>{t.titulo}</span>
                          <span style={{ display: "block", fontSize: 12, color: C.ink3, marginTop: 2 }}>{t.tempo}{t.template ? " · " + t.template : ""}</span>
                        </span>
                      </button>
                    );
                  })}
                </div>
              </Card>
            ))}
          </div>
        </section>

        {/* FECHAMENTO DA SEMANA (entregáveis + avaliação semanal) */}
        <FechamentoSemana cid={c.id} inicio={c.inicio} flash={flash} />

        {/* IDEIAS (banco de ideias do colaborador) */}
        <IdeiasBloco cid={c.id} flash={flash} />

        {/* DIÁRIO DE BORDO */}
        <DiarioBordo token={token} cid={c.id} diario={diario} setDiario={setDiario} flash={flash} />

        {/* AUTO-AVALIAÇÃO 30 DIAS */}
        <AutoAvaliacao token={token} aval={aval} setAval={setAval} flash={flash} />
      </main>

      {toast && (
        <div style={{ position: "fixed", bottom: 22, left: "50%", transform: "translateX(-50%)", background: C.ink, color: "#fff", padding: "11px 18px", borderRadius: 12, fontSize: 13.5, fontWeight: 600, boxShadow: "0 10px 30px rgba(0,0,0,.25)", zIndex: 60 }}>{toast}</div>
      )}
    </div>
  );
}

function todayISO() { return new Date().toISOString().slice(0, 10); }

function DiarioBordo({ token, cid, diario, setDiario, flash }) {
  const M = window.OE.MODELO_ACOMP.diario;
  const [data, setData] = React.useState(todayISO());
  const [turno, setTurno] = React.useState("manha");
  const campos = (turno === "manha" ? M.manha : M.tarde).campos;

  const existente = diario.find((e) => e.data === data && e.turno === turno);
  const [vals, setVals] = React.useState({});
  React.useEffect(() => { setVals((existente && existente.conteudo) || {}); }, [data, turno, diario.length]);

  const [saving, setSaving] = React.useState(false);
  async function salvar() {
    setSaving(true);
    try {
      await window.OS.colabDiarioSave(token, data, turno, vals);
      if (cid) { try { await window.OS.colabDiarioMark(cid, data, turno); } catch (e) {} } // espelha p/ o painel do RH
      setDiario((prev) => {
        const others = prev.filter((e) => !(e.data === data && e.turno === turno));
        return [...others, { data, turno, conteudo: vals }].sort((a, b) => (a.data + a.turno).localeCompare(b.data + b.turno));
      });
      flash("Diário salvo ✓");
    } catch (e) { flash("Não consegui salvar o diário."); }
    setSaving(false);
  }

  return (
    <section>
      <SectionTitle icon="notebook-pen" sub="Registre manhã e tarde — leva ~10 min por turno. É a base do seu relatório semanal.">Diário de Bordo</SectionTitle>
      <Card pad={20}>
        <div style={{ display: "flex", gap: 12, flexWrap: "wrap", alignItems: "center", marginBottom: 18 }}>
          <input type="date" value={data} onChange={(e) => setData(e.target.value)}
            style={{ padding: "9px 12px", border: `1.5px solid ${C.line}`, borderRadius: 10, fontSize: 13.5, fontFamily: "inherit", color: C.ink, outline: "none" }} />
          <div style={{ display: "inline-flex", background: C.bgAlt, borderRadius: 11, padding: 3 }}>
            {[["manha", "Manhã", "sunrise"], ["tarde", "Tarde", "sunset"]].map(([k, lab, ic]) => (
              <button key={k} onClick={() => setTurno(k)} style={{
                display: "inline-flex", alignItems: "center", gap: 7, border: "none", cursor: "pointer", fontFamily: "inherit",
                background: turno === k ? "#fff" : "transparent", color: turno === k ? C.ink : C.ink2, fontWeight: 700, fontSize: 13.5,
                padding: "8px 15px", borderRadius: 9, boxShadow: turno === k ? "0 1px 3px rgba(15,23,42,.13)" : "none",
              }}><LIcon name={ic} size={15} /> {lab}</button>
            ))}
          </div>
          {existente && <Pill tone="green" icon="check">Já preenchido</Pill>}
        </div>

        <div style={{ display: "flex", flexDirection: "column", gap: 14 }}>
          {campos.map((campo, i) => (
            <div key={i}>
              <label style={{ fontSize: 12.5, fontWeight: 700, color: C.ink, display: "block", marginBottom: 6 }}>{campo}</label>
              <textarea value={vals[i] || ""} onChange={(e) => setVals((v) => ({ ...v, [i]: e.target.value }))}
                rows={2} placeholder="Escreva aqui…"
                style={{ width: "100%", resize: "vertical", padding: "10px 12px", 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>
        <div style={{ marginTop: 16 }}>
          <Btn icon="save" onClick={salvar} disabled={saving}>{saving ? "Salvando…" : "Salvar diário"}</Btn>
        </div>
      </Card>
    </section>
  );
}

function AutoAvaliacao({ token, aval, setAval, flash }) {
  const campos = window.OE.AUTOAVAL_30;
  const [vals, setVals] = React.useState(() => ({ ...aval }));
  const [saving, setSaving] = React.useState(false);
  const notas = campos.map((c) => Number(vals[c.k + "_nota"])).filter((n) => !isNaN(n));
  const media = notas.length ? (notas.reduce((a, b) => a + b, 0) / notas.length) : null;

  async function salvar() {
    setSaving(true);
    try {
      await window.OS.colabAvaliacaoSave(token, vals, media);
      setAval({ ...vals });
      flash("Auto-avaliação enviada ✓");
    } catch (e) { flash("Não consegui enviar a avaliação."); }
    setSaving(false);
  }

  return (
    <section>
      <SectionTitle icon="clipboard-check" sub="No fim do 1º mês, conte como foi. Notas de 0 a 10 e um comentário em cada ponto.">Auto-avaliação de 30 dias</SectionTitle>
      <Card pad={20}>
        <div style={{ display: "flex", flexDirection: "column", gap: 20 }}>
          {campos.map((c) => (
            <div key={c.k}>
              <div style={{ display: "flex", alignItems: "center", gap: 10, marginBottom: 8, flexWrap: "wrap" }}>
                <span style={{ fontSize: 13.5, fontWeight: 700, color: C.ink, flex: 1, minWidth: 200 }}>{c.q}</span>
                <div style={{ display: "flex", gap: 4 }}>
                  {[0,1,2,3,4,5,6,7,8,9,10].map((n) => {
                    const on = Number(vals[c.k + "_nota"]) === n;
                    return (
                      <button key={n} onClick={() => setVals((v) => ({ ...v, [c.k + "_nota"]: n }))} style={{
                        width: 28, height: 30, borderRadius: 7, cursor: "pointer", fontFamily: "inherit", fontWeight: 700, fontSize: 12.5,
                        border: `1.5px solid ${on ? C.cobalt : C.line}`, background: on ? C.cobalt : "#fff", color: on ? "#fff" : C.ink2,
                      }}>{n}</button>
                    );
                  })}
                </div>
              </div>
              <textarea value={vals[c.k + "_obs"] || ""} onChange={(e) => setVals((v) => ({ ...v, [c.k + "_obs"]: e.target.value }))}
                rows={2} placeholder="Comentário (opcional)…"
                style={{ width: "100%", resize: "vertical", padding: "9px 12px", border: `1.5px solid ${C.line}`, borderRadius: 10, fontSize: 13, fontFamily: "inherit", color: C.ink, outline: "none", lineHeight: 1.5, boxSizing: "border-box" }} />
            </div>
          ))}
        </div>
        <div style={{ marginTop: 18, display: "flex", alignItems: "center", gap: 14, flexWrap: "wrap" }}>
          <Btn icon="send" onClick={salvar} disabled={saving}>{saving ? "Enviando…" : "Enviar auto-avaliação"}</Btn>
          {media != null && <span style={{ fontSize: 13.5, color: C.ink2, fontWeight: 600 }}>Sua média: <b style={{ color: C.ink }}>{media.toFixed(1)}</b></span>}
        </div>
      </Card>
    </section>
  );
}

function FechamentoSemana({ cid, inicio, flash }) {
  const OE = window.OE;
  const semAtual = OE.semanaDoColab(inicio);
  const [semana, setSemana] = React.useState(semAtual);
  const [vals, setVals] = React.useState({});       // q's + relato
  const [ent, setEnt] = React.useState({});         // entregáveis marcados
  const [saving, setSaving] = React.useState(false);
  const [enviadas, setEnviadas] = React.useState({});

  React.useEffect(() => { (async () => {
    if (!cid) return;
    try { const form = await window.OS.colabMetaLoad(cid); setEnviadas(form.semanais || {}); } catch (e) {}
  })(); }, [cid]);
  React.useEffect(() => {
    const s = enviadas[semana] || {};
    setVals(s); setEnt(s.entregaveis || {});
  }, [semana, enviadas]);

  const plano = OE.ENTREGAVEIS_SEMANA[semana - 1] || { foco: "", itens: [] };
  const notas = OE.AUTOAVAL_SEMANAL.map((q) => Number(vals[q.k])).filter((n) => !isNaN(n));
  const media = notas.length ? (notas.reduce((a, b) => a + b, 0) / notas.length) : null;
  const feitos = plano.itens.filter((_, i) => ent[i]).length;

  async function enviar() {
    setSaving(true);
    try {
      const dados = { ...vals, entregaveis: ent, nota: media != null ? Math.round(media * 10) / 10 : null };
      await window.OS.colabSemanaSave(cid, semana, dados);
      setEnviadas((p) => ({ ...p, [semana]: { ...dados, enviado_em: new Date().toISOString() } }));
      flash("Fechamento da semana enviado ✓");
    } catch (e) { flash("Não consegui enviar o fechamento."); }
    setSaving(false);
  }

  return (
    <section>
      <div style={{ display: "flex", alignItems: "center", gap: 12, flexWrap: "wrap", marginBottom: 16 }}>
        <div style={{ flex: 1, minWidth: 200 }}>
          <SectionTitle icon="calendar-check" sub="Toda sexta: marque o que entregou e responda como foi. O RH recebe na hora.">Fechamento da semana</SectionTitle>
        </div>
        <div style={{ display: "inline-flex", background: C.bgAlt, borderRadius: 11, padding: 3 }}>
          {[1, 2, 3, 4].map((w) => (
            <button key={w} onClick={() => setSemana(w)} style={{
              border: "none", cursor: "pointer", fontFamily: "inherit", fontWeight: 700, fontSize: 12.5, padding: "7px 13px", borderRadius: 8,
              background: semana === w ? C.cobalt : "transparent", color: semana === w ? "#fff" : C.ink2,
            }}>S{w}{enviadas[w] ? " ✓" : ""}</button>
          ))}
        </div>
      </div>

      {/* ENTREGÁVEIS */}
      <Card pad={20} style={{ marginBottom: 14 }}>
        <div style={{ display: "flex", alignItems: "center", gap: 10, marginBottom: 12 }}>
          <span style={{ width: 30, height: 30, borderRadius: 9, background: C.cobaltSoft, color: C.cobalt, display: "grid", placeItems: "center", flex: "none" }}><LIcon name="package-check" size={16} /></span>
          <span style={{ fontSize: 14.5, fontWeight: 800, color: C.ink, flex: 1 }}>Entregáveis · {plano.foco}</span>
          <Pill tone={feitos === plano.itens.length ? "green" : "cobalt"} icon="check">{feitos} de {plano.itens.length}</Pill>
        </div>
        <div style={{ display: "flex", flexDirection: "column", gap: 8 }}>
          {plano.itens.map((it, i) => {
            const on = !!ent[i];
            return (
              <button key={i} onClick={() => setEnt((p) => ({ ...p, [i]: !p[i] }))} style={{
                display: "flex", alignItems: "flex-start", gap: 12, textAlign: "left", cursor: "pointer", fontFamily: "inherit",
                background: on ? C.greenSoft : C.bg, border: `1px solid ${on ? "#bfe6cd" : C.line}`, borderRadius: 12, padding: "12px 14px",
              }}>
                <span style={{ width: 22, height: 22, flex: "none", marginTop: 1, borderRadius: 7, border: `2px solid ${on ? C.green : C.line}`, background: on ? C.green : "#fff", color: "#fff", display: "grid", placeItems: "center" }}>{on && <LIcon name="check" size={13} stroke={3} />}</span>
                <span style={{ flex: 1, fontSize: 13.5, color: on ? C.ink3 : C.ink2, lineHeight: 1.45, textDecoration: on ? "line-through" : "none" }}>{it}</span>
              </button>
            );
          })}
        </div>
      </Card>

      {/* AVALIAÇÃO SEMANAL */}
      <Card pad={20} style={{ marginBottom: 14 }}>
        <div style={{ display: "flex", flexDirection: "column", gap: 16 }}>
          {OE.AUTOAVAL_SEMANAL.map((q) => (
            <div key={q.k} style={{ display: "flex", alignItems: "center", gap: 10, flexWrap: "wrap" }}>
              <span style={{ fontSize: 13.5, fontWeight: 700, color: C.ink, flex: 1, minWidth: 200 }}>{q.q}</span>
              <div style={{ display: "flex", gap: 4, flexWrap: "wrap" }}>
                {[0,1,2,3,4,5,6,7,8,9,10].map((n) => {
                  const on = Number(vals[q.k]) === n;
                  return <button key={n} onClick={() => setVals((v) => ({ ...v, [q.k]: n }))} style={{
                    width: 28, height: 30, borderRadius: 7, cursor: "pointer", fontFamily: "inherit", fontWeight: 700, fontSize: 12.5,
                    border: `1.5px solid ${on ? C.cobalt : C.line}`, background: on ? C.cobalt : "#fff", color: on ? "#fff" : C.ink2,
                  }}>{n}</button>;
                })}
              </div>
            </div>
          ))}
        </div>
      </Card>

      {/* RELATÓRIO SEMANAL */}
      <Card pad={20}>
        <div style={{ display: "flex", flexDirection: "column", gap: 14 }}>
          {OE.RELATO_SEMANAL.map((f) => (
            <div key={f.k}>
              <label style={{ fontSize: 12.5, fontWeight: 700, color: C.ink, display: "block", marginBottom: 6 }}>{f.q}</label>
              <textarea value={vals[f.k] || ""} onChange={(e) => setVals((v) => ({ ...v, [f.k]: e.target.value }))} rows={2} placeholder="Escreva aqui…"
                style={{ width: "100%", resize: "vertical", padding: "10px 12px", 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>
        <div style={{ marginTop: 16, display: "flex", alignItems: "center", gap: 14, flexWrap: "wrap" }}>
          <Btn icon="send" onClick={enviar} disabled={saving}>{saving ? "Enviando…" : "Enviar fechamento da semana"}</Btn>
          {media != null && <span style={{ fontSize: 13, color: C.ink2, fontWeight: 600 }}>Média da semana: <b style={{ color: C.ink }}>{media.toFixed(1)}</b> · o RH recebe na hora</span>}
        </div>
      </Card>
    </section>
  );
}

const IDEIA_CAMPOS = [
  { k: "oque", lab: "O quê", ph: "Ex.: Refazer o site institucional", area: false },
  { k: "porque", lab: "Por quê", ph: "Ex.: O site atual está desatualizado e não gera contatos", area: true },
  { k: "como", lab: "Como", ph: "Ex.: Briefing + uma landing page nova com formulário", area: true },
  { k: "resultado", lab: "Resultado esperado", ph: "Ex.: Mais pedidos de orçamento entrando pelo site", area: true },
];
const IDEIA_PRIORIDADES = ["Alta", "Média", "Baixa"];
const ideiaVazia = () => ({ oque: "", porque: "", como: "", prioridade: "Média", resultado: "" });
const prioTone = (p) => (p === "Alta" ? "amber" : p === "Baixa" ? "gray" : "cobalt");

function IdeiasBloco({ cid, flash }) {
  const [ideias, setIdeias] = React.useState([]);
  const [draft, setDraft] = React.useState(ideiaVazia());
  const [saving, setSaving] = React.useState(false);

  React.useEffect(() => { (async () => {
    if (!cid) return;
    try { const form = await window.OS.colabMetaLoad(cid); setIdeias(form.ideias || []); } catch (e) {}
  })(); }, [cid]);

  async function persist(lista) {
    setSaving(true);
    try { await window.OS.colabIdeiasSave(cid, lista); setIdeias(lista); }
    catch (e) { flash("Não consegui salvar a ideia."); }
    setSaving(false);
  }
  async function adicionar() {
    if (!draft.oque.trim()) { flash("Escreva ao menos 'O quê' da ideia."); return; }
    const nova = { ...draft, criado_em: new Date().toISOString() };
    await persist([nova, ...ideias]);
    setDraft(ideiaVazia());
    flash("Ideia registrada ✓");
  }
  async function remover(i) { await persist(ideias.filter((_, j) => j !== i)); }

  const set = (k, v) => setDraft((d) => ({ ...d, [k]: v }));
  const inp = { width: "100%", padding: "10px 12px", border: `1.5px solid ${C.line}`, borderRadius: 10, fontSize: 13.5, fontFamily: "inherit", color: C.ink, outline: "none", boxSizing: "border-box", lineHeight: 1.5 };
  const lbl = { fontSize: 11.5, fontWeight: 800, letterSpacing: ".04em", textTransform: "uppercase", color: C.cobaltDeep, display: "block", marginBottom: 6 };

  return (
    <section>
      <SectionTitle icon="lightbulb" sub="Teve uma ideia para melhorar a empresa? Registre aqui. O RH/ADM enxerga todas.">Banco de ideias</SectionTitle>

      {/* FORMULÁRIO DE NOVA IDEIA */}
      <Card pad={20} style={{ marginBottom: 14 }}>
        <div style={{ display: "flex", flexDirection: "column", gap: 14 }}>
          <div><span style={lbl}>O quê</span><input style={inp} value={draft.oque} onChange={(e) => set("oque", e.target.value)} placeholder={IDEIA_CAMPOS[0].ph} /></div>
          <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 12 }}>
            <div><span style={lbl}>Por quê</span><textarea rows={2} style={inp} value={draft.porque} onChange={(e) => set("porque", e.target.value)} placeholder={IDEIA_CAMPOS[1].ph} /></div>
            <div><span style={lbl}>Como</span><textarea rows={2} style={inp} value={draft.como} onChange={(e) => set("como", e.target.value)} placeholder={IDEIA_CAMPOS[2].ph} /></div>
          </div>
          <div style={{ display: "grid", gridTemplateColumns: "180px 1fr", gap: 12 }}>
            <div><span style={lbl}>Prioridade</span>
              <select style={inp} value={draft.prioridade} onChange={(e) => set("prioridade", e.target.value)}>
                {IDEIA_PRIORIDADES.map((p) => <option key={p} value={p}>{p}</option>)}
              </select>
            </div>
            <div><span style={lbl}>Resultado esperado</span><input style={inp} value={draft.resultado} onChange={(e) => set("resultado", e.target.value)} placeholder={IDEIA_CAMPOS[3].ph} /></div>
          </div>
          <div><Btn icon="plus" onClick={adicionar} disabled={saving}>Adicionar ideia</Btn></div>
        </div>
      </Card>

      {/* LISTA DE IDEIAS */}
      {ideias.length === 0 ? (
        <Card pad={18} style={{ background: C.bg, display: "flex", alignItems: "center", gap: 10 }}>
          <span style={{ color: C.cobalt }}><LIcon name="lightbulb" size={18} /></span>
          <span style={{ fontSize: 13, color: C.ink3 }}>Nenhuma ideia registrada ainda. Use o campo acima — o exemplo do site é só pra te guiar.</span>
        </Card>
      ) : (
        <div style={{ display: "flex", flexDirection: "column", gap: 12 }}>
          {ideias.map((it, i) => (
            <Card key={i} pad={18}>
              <div style={{ display: "flex", alignItems: "center", gap: 10, marginBottom: 10 }}>
                <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, flex: 1 }}>{it.oque}</span>
                <Pill tone={prioTone(it.prioridade)} icon="flag">{it.prioridade}</Pill>
                <button onClick={() => remover(i)} title="Remover" style={{ background: "transparent", border: "none", cursor: "pointer", color: C.ink3, padding: 3 }}><LIcon name="trash-2" size={16} /></button>
              </div>
              <div style={{ display: "grid", gridTemplateColumns: "repeat(auto-fit,minmax(200px,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.5, fontWeight: 800, letterSpacing: ".04em", textTransform: "uppercase", color: C.ink3, marginBottom: 3 }}>{t}</div>
                    <div style={{ fontSize: 13, color: C.ink2, lineHeight: 1.5 }}>{v}</div>
                  </div>
                ) : null)}
              </div>
            </Card>
          ))}
        </div>
      )}
    </section>
  );
}

Object.assign(window, { ColabView });
