/* ============================================================
   APP RAIZ — boot, detecção de papel e roteamento.
   ?t=<token>  → visão do Colaborador (link mágico, sem login)
   sessão+rh   → painel de execução (Gra)
   sessão+dono → cockpit de supervisão (André)
   ============================================================ */

function syncCols(list) {
  const arr = window.OE.colaboradores;
  arr.length = 0; list.forEach((x) => arr.push(x));
}

function Splash({ msg }) {
  return (
    <div style={{ minHeight: "100vh", display: "grid", placeItems: "center", background: C.bg }}>
      <div style={{ textAlign: "center", color: C.ink3 }}>
        <div style={{ width: 44, height: 44, borderRadius: 13, background: "linear-gradient(150deg,#27406e,#16233F)", display: "grid", placeItems: "center", color: "#fff", margin: "0 auto 14px" }}><LIcon name="rocket" size={22} stroke={2.3} /></div>
        <div style={{ fontSize: 14, fontWeight: 600 }}>{msg || "Carregando…"}</div>
      </div>
    </div>
  );
}

function BadToken() {
  return (
    <div style={{ minHeight: "100vh", display: "grid", placeItems: "center", background: C.bg, padding: 20 }}>
      <Card pad={28} style={{ maxWidth: 420, textAlign: "center" }}>
        <div style={{ color: C.amber, display: "flex", justifyContent: "center", marginBottom: 10 }}><LIcon name="link-2-off" size={32} /></div>
        <div style={{ fontSize: 17, fontWeight: 800, color: C.ink }}>Link inválido ou expirado</div>
        <div style={{ fontSize: 13.5, color: C.ink2, marginTop: 8, lineHeight: 1.5 }}>Esse link de acesso não foi reconhecido. Peça ao RH para reenviar o seu link de integração.</div>
      </Card>
    </div>
  );
}

function Boot() {
  const OPEN = !!window.ONB_CONFIG.OPEN_MODE;
  const [phase, setPhase] = React.useState("loading");
  const [role, setRole] = React.useState(null);
  const [bundle, setBundle] = React.useState(null);
  const [token, setToken] = React.useState(null);
  const [loginErr, setLoginErr] = React.useState("");
  const [openRole, setOpenRole] = React.useState(() => new URLSearchParams(location.search).get("role") === "dono" ? "dono" : "rh");
  const [forceLogin, setForceLogin] = React.useState(false);

  React.useEffect(() => { detect(); }, [forceLogin]);

  async function detect() {
    try {
      const t = new URLSearchParams(location.search).get("t");
      if (t) {
        const b = await window.OS.colabLoad(t);
        if (b && b.ok) { setToken(t); setBundle(b); setPhase("colab"); }
        else setPhase("badtoken");
        return;
      }
      if (OPEN && !forceLogin) { setPhase("operator"); return; }   // modo aberto: sem login
      const r = await window.OS.operatorRole();
      if (r) { setRole(r); setPhase("operator"); return; }
      const s = await window.OS.getSession();
      if (s) await window.OS.signOut();
      setPhase("login");
    } catch (e) { setPhase("login"); }
  }

  async function afterLogin() {
    const r = await window.OS.operatorRole();
    if (r) { setRole(r); setLoginErr(""); setPhase("operator"); }
    else { await window.OS.signOut(); setLoginErr("conta-sem-acesso"); }
  }

  async function logout() {
    if (OPEN && !forceLogin) { setPhase("loading"); setForceLogin(true); return; } // modo aberto -> tela de login
    await window.OS.signOut(); setRole(null); setForceLogin(true); setPhase("login");
  }

  if (phase === "loading") return <Splash />;
  if (phase === "badtoken") return <BadToken />;
  if (phase === "colab") return <ColabView token={token} bundle={bundle} />;
  if (phase === "login") return (
    <>
      <LoginScreen onLogged={afterLogin} />
      {loginErr === "conta-sem-acesso" && (
        <div style={{ position: "fixed", bottom: 22, left: "50%", transform: "translateX(-50%)", background: C.red, color: "#fff", padding: "11px 18px", borderRadius: 12, fontSize: 13.5, fontWeight: 600, zIndex: 60 }}>Essa conta não tem acesso ao painel.</div>
      )}
    </>
  );
  const openActive = OPEN && !forceLogin;
  const effRole = openActive ? { nome: openRole === "dono" ? "André" : "Gra", papel: openRole } : role;
  return <OperatorApp role={effRole} onLogout={logout} openMode={openActive} openRole={openRole} onSwitchRole={setOpenRole} />;
}

/* ---------- App do operador (RH ou Dono) ---------- */
function OperatorApp({ role, onLogout, openMode, openRole, onSwitchRole }) {
  const [loaded, setLoaded] = React.useState(false);
  const [err, setErr] = React.useState("");
  const [done, setDone] = React.useState({});
  const [meta, setMeta] = React.useState({});
  const [, force] = React.useState(0);
  const [route, setRoute] = React.useState(() => {
    const t = new URLSearchParams(location.search).get("tab");
    return { view: ["equipe", "fluxo", "plano", "templates", "atividades"].includes(t) ? t : "dash" };
  });
  const [novoOpen, setNovoOpen] = React.useState(false);
  const isDono = role.papel === "dono";

  React.useEffect(() => { (async () => {
    try {
      const { colaboradores, done, meta } = await window.OS.loadAll();
      syncCols(colaboradores);
      setDone(done); setMeta(meta); setLoaded(true);
    } catch (e) { setErr(e.message || "Falha ao carregar os dados."); setLoaded(true); }
  })(); }, []);

  const go = React.useCallback((view, params) => { setRoute({ view, ...(params || {}) }); window.scrollTo(0, 0); }, []);

  const toggle = React.useCallback((colabId, key) => {
    let willBe;
    setDone((prev) => {
      const next = { ...prev }; const s = new Set(next[colabId]);
      willBe = !s.has(key);
      if (willBe) s.add(key); else s.delete(key);
      next[colabId] = s; return next;
    });
    window.OS.toggleTask(colabId, key, willBe).catch(() => setErr("Não consegui salvar a tarefa."));
  }, []);

  const patchMeta = React.useCallback((colabId, mutator) => {
    setMeta((prev) => {
      const next = { ...prev };
      const cm = { form: {}, drive: {}, parecer: {}, ...(next[colabId] || {}) };
      const nm = mutator({ form: { ...cm.form }, drive: { ...cm.drive }, parecer: { ...cm.parecer } });
      next[colabId] = nm;
      window.OS.saveMeta(colabId, nm).catch(() => setErr("Não consegui salvar."));
      return next;
    });
  }, []);

  const formalizar = React.useCallback((colabId, faseId) => patchMeta(colabId, (m) => { m.form[faseId] = new Date().toISOString(); return m; }), [patchMeta]);
  const setDrive = React.useCallback((colabId, faseId, url) => patchMeta(colabId, (m) => { if (url) m.drive[faseId] = url; else delete m.drive[faseId]; return m; }), [patchMeta]);
  const setParecer = React.useCallback((colabId, patch) => patchMeta(colabId, (m) => { m.parecer = { ...m.parecer, ...patch }; return m; }), [patchMeta]);

  function onCreated(row) {
    const c = { id: row.id, token: row.token, nome: row.nome, cargo: row.cargo, area: row.area, modelo: row.modelo, lideranca: row.lideranca, inicio: row.inicio, cor: row.cor || "#16233F", email_pessoal: row.email_pessoal, status: row.status };
    syncCols([...window.OE.colaboradores, c]);
    setDone((p) => ({ ...p, [c.id]: new Set() }));
    setMeta((p) => ({ ...p, [c.id]: { form: {}, drive: {}, parecer: {} } }));
    force((n) => n + 1);
  }

  if (!loaded) return <Splash msg="Carregando os dados…" />;

  const tabs = isDono ? [] : [
    { k: "dash", label: "Pessoas", icon: "users" },
    { k: "atividades", label: "Atividades", icon: "list-checks" },
    { k: "templates", label: "Modelos", icon: "library" },
    { k: "fluxo", label: "O processo", icon: "route" },
  ];
  const activeTab = ["atividades", "fluxo", "plano", "templates", "equipe"].includes(route.view) ? route.view : "dash";

  let body;
  if (isDono) body = <DonoView done={done} meta={meta} />;
  else if (route.view === "guia") body = <GuiaExecucao id={route.id} doneSet={done[route.id]} onToggle={(k) => toggle(route.id, k)} go={go} meta={meta} onFormalize={formalizar} onDrive={setDrive} onParecer={setParecer} />;
  else if (route.view === "equipe") body = <PainelEquipe meta={meta} />;
  else if (route.view === "plano") body = <PlanoView go={go} />;
  else if (route.view === "templates") body = <TemplatesView initialId={route.tplId} />;
  else if (route.view === "fluxo") body = <FluxoProcesso go={go} />;
  else if (route.view === "atividades") body = <AtividadesView done={done} meta={meta} go={go} toggle={toggle} />;
  else body = <PessoasWorkspace done={done} meta={meta} go={go} onNovo={() => setNovoOpen(true)} toggle={toggle} />;

  const initialsRole = window.OE.iniciais(role.nome) || (isDono ? "AN" : "GR");

  return (
    <div style={{ minHeight: "100vh", background: C.bg }}>
      <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: 1160, margin: "0 auto", padding: "11px 28px 12px" }}>
          {/* Linha 1 — marca + controles */}
          <div style={{ display: "flex", alignItems: "center", gap: 14, flexWrap: "wrap" }}>
            <div style={{ display: "flex", alignItems: "center", gap: 11 }}>
              <div style={{ width: 34, height: 34, borderRadius: 10, background: "linear-gradient(150deg,#27406e,#16233F)", display: "grid", placeItems: "center", color: "#fff" }}><LIcon name="rocket" size={18} stroke={2.3} /></div>
              <div>
                <div style={{ fontWeight: 800, fontSize: 15.5, color: C.ink, letterSpacing: "-.01em", lineHeight: 1.1 }}>Onboarding ASCEND</div>
                <div style={{ fontSize: 11, color: C.ink3, fontWeight: 600 }}>{isDono ? "Supervisão" : "Execução guiada"}</div>
              </div>
            </div>

            <div style={{ marginLeft: "auto", display: "flex", alignItems: "center", gap: 10, flexWrap: "wrap" }}>
              {openMode && (
                <div style={{ display: "inline-flex", alignItems: "center", background: "#fff7e6", border: "1px solid #f3d28a", borderRadius: 999, padding: "3px 4px 3px 11px", gap: 8 }} title="Modo aberto: sem login durante os testes">
                  <span style={{ fontSize: 10.5, fontWeight: 800, color: C.amber, letterSpacing: ".04em", textTransform: "uppercase" }}>Modo aberto</span>
                  <div style={{ display: "inline-flex", background: C.bgAlt, borderRadius: 999, padding: 2 }}>
                    {[["rh", "RH"], ["dono", "ASCEND"]].map(([k, lab]) => (
                      <button key={k} onClick={() => onSwitchRole(k)} style={{
                        border: "none", cursor: "pointer", fontFamily: "inherit", fontWeight: 700, fontSize: 12, padding: "5px 12px", borderRadius: 999,
                        background: openRole === k ? "#fff" : "transparent", color: openRole === k ? C.ink : C.ink2,
                        boxShadow: openRole === k ? "0 1px 2px rgba(15,23,42,.15)" : "none",
                      }}>{lab}</button>
                    ))}
                  </div>
                </div>
              )}
              {!isDono && <Btn variant="soft" size="sm" icon="user-plus" onClick={() => setNovoOpen(true)}>Novo colaborador</Btn>}
              <div style={{ textAlign: "right" }} className="userlbl">
                <div style={{ fontSize: 12.5, fontWeight: 700, color: C.ink, lineHeight: 1.1 }}>{role.nome} · {isDono ? "Supervisão" : "RH"}</div>
                <div style={{ fontSize: 10.5, color: C.ink3 }}>{isDono ? "ASCEND" : "Executora de onboarding"}</div>
              </div>
              <div style={{ width: 34, height: 34, borderRadius: "50%", background: C.cobaltSoft, color: C.cobaltDeep, display: "grid", placeItems: "center", fontWeight: 800, fontSize: 11.5 }}>{initialsRole}</div>
              <button onClick={onLogout} title={openMode ? "Ir para a tela de login" : "Sair"} style={{ background: "transparent", border: "none", cursor: "pointer", color: C.ink3, display: "grid", placeItems: "center", padding: 4 }}><LIcon name={openMode ? "log-in" : "log-out"} size={18} /></button>
            </div>
          </div>

          {/* Linha 2 — abas (rola no horizontal se faltar espaço) */}
          {!isDono && (
            <div style={{ marginTop: 11, overflowX: "auto" }}>
              <div style={{ display: "inline-flex", background: C.bgAlt, borderRadius: 12, padding: 3 }}>
                {tabs.map((t) => (
                  <button key={t.k} onClick={() => go(t.k)} style={{
                    display: "inline-flex", alignItems: "center", gap: 8, border: "none", cursor: "pointer", fontFamily: "inherit", whiteSpace: "nowrap",
                    background: activeTab === t.k ? "#fff" : "transparent", color: activeTab === t.k ? C.ink : C.ink2,
                    fontWeight: 700, fontSize: 13.5, padding: "8px 15px", borderRadius: 9,
                    boxShadow: activeTab === t.k ? "0 1px 3px rgba(15,23,42,.13)" : "none",
                  }}><LIcon name={t.icon} size={16} /> {t.label}</button>
                ))}
              </div>
            </div>
          )}
        </div>
      </header>

      <main style={{ maxWidth: 1160, margin: "0 auto", padding: "26px 28px 70px" }}>
        {err && <div style={{ marginBottom: 16, background: C.redSoft, color: C.red, border: `1px solid ${C.red}33`, borderRadius: 12, padding: "10px 14px", fontSize: 13, fontWeight: 600 }}>{err}</div>}
        <div style={{ marginBottom: 22 }}>
          {(!isDono && route.view === "guia") ? null : (
            <>
              <h1 style={{ margin: 0, fontSize: 24, fontWeight: 800, letterSpacing: "-.02em", color: C.ink }}>
                {isDono ? `Olá, ${(role.nome || "André").split(" ")[0]} 👋`
                  : activeTab === "equipe" ? "O que a equipe está enviando"
                  : activeTab === "plano" ? "Plano & Acompanhamento"
                  : activeTab === "atividades" ? "Atividades do processo"
                  : activeTab === "templates" ? "Modelos oficiais"
                  : activeTab === "fluxo" ? "O processo de onboarding"
                  : `Pessoas em integração`}
              </h1>
              <p style={{ margin: "6px 0 0", fontSize: 14.5, color: C.ink2 }}>
                {isDono ? "A supervisão de todas as integrações em um lugar — e onde cada uma está travando."
                  : activeTab === "equipe" ? "Cada pessoa em integração, o que já submeteu esta semana e como está o ritmo."
                  : activeTab === "plano" ? "O que você entrega ao colaborador no Dia 1: plano e modelo de acompanhamento."
                  : activeTab === "atividades" ? "Todas as tarefas do onboarding, por etapa. Marque o que já foi feito — escolha a pessoa no topo."
                  : activeTab === "templates" ? "O pacote de 9 ferramentas que estrutura o mapeamento, a documentação e o diagnóstico."
                  : activeTab === "fluxo" ? "As etapas explicadas: o que fazer, quanto leva e onde costuma travar."
                  : "Escolha uma pessoa na lista para resolver tudo dela num lugar: diário de hoje, semana e documentos."}
              </p>
            </>
          )}
        </div>
        {body}
      </main>

      {novoOpen && <NovoColabModal onClose={() => setNovoOpen(false)} onCreated={onCreated} />}
    </div>
  );
}

/* ---------- Modal: cadastrar colaborador + gerar link mágico ---------- */
function NovoColabModal({ onClose, onCreated }) {
  const [f, setF] = React.useState({ nome: "", cargo: "", area: "", modelo: "CLT", lideranca: false, inicio: "", email_pessoal: "" });
  const [saving, setSaving] = React.useState(false);
  const [erro, setErro] = React.useState("");
  const [criado, setCriado] = React.useState(null);
  const [copiado, setCopiado] = React.useState(false);
  const set = (k, v) => setF((p) => ({ ...p, [k]: v }));

  async function salvar() {
    if (!f.nome.trim()) { setErro("Informe o nome do colaborador."); return; }
    setErro(""); setSaving(true);
    try {
      const row = await window.OS.createColaborador(f);
      onCreated(row);
      setCriado({ row, link: window.OS.magicLink(row.token) });
    } catch (e) { setErro(e.message || "Não consegui cadastrar."); }
    setSaving(false);
  }
  function copiar() {
    try { navigator.clipboard.writeText(criado.link); setCopiado(true); setTimeout(() => setCopiado(false), 1800); } catch (e) {}
  }

  const inputStyle = { 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" };
  const label = { fontSize: 12, fontWeight: 700, color: C.ink2, display: "block", marginBottom: 5 };

  return (
    <div onClick={onClose} style={{ position: "fixed", inset: 0, background: "rgba(8,15,40,.5)", backdropFilter: "blur(3px)", display: "grid", placeItems: "center", zIndex: 80, padding: 20 }}>
      <div onClick={(e) => e.stopPropagation()} style={{ width: "100%", maxWidth: 520, background: "#fff", borderRadius: 18, overflow: "hidden", maxHeight: "90vh", overflowY: "auto" }}>
        <div style={{ padding: "18px 22px", borderBottom: `1px solid ${C.line}`, display: "flex", alignItems: "center", gap: 10 }}>
          <span style={{ width: 36, height: 36, borderRadius: 10, background: C.cobaltSoft, color: C.cobalt, display: "grid", placeItems: "center" }}><LIcon name="user-plus" size={19} /></span>
          <div style={{ flex: 1 }}>
            <div style={{ fontSize: 16, fontWeight: 800, color: C.ink }}>{criado ? "Colaborador cadastrado" : "Novo colaborador"}</div>
            <div style={{ fontSize: 12.5, color: C.ink3 }}>{criado ? "Envie o link de acesso para ele(a)." : "Abra a integração e gere o link de acesso."}</div>
          </div>
          <button onClick={onClose} style={{ background: "transparent", border: "none", cursor: "pointer", color: C.ink3, padding: 4 }}><LIcon name="x" size={20} /></button>
        </div>

        {!criado ? (
          <div style={{ padding: 22, display: "flex", flexDirection: "column", gap: 14 }}>
            <div><span style={label}>Nome completo</span><input style={inputStyle} value={f.nome} onChange={(e) => set("nome", e.target.value)} placeholder="Ex.: Maria Silva" /></div>
            <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 12 }}>
              <div><span style={label}>Cargo</span><input style={inputStyle} value={f.cargo} onChange={(e) => set("cargo", e.target.value)} placeholder="Ex.: Analista Financeiro" /></div>
              <div><span style={label}>Área</span><input style={inputStyle} value={f.area} onChange={(e) => set("area", e.target.value)} placeholder="Ex.: Financeiro" /></div>
            </div>
            <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 12 }}>
              <div><span style={label}>Contratação</span>
                <select style={inputStyle} value={f.modelo} onChange={(e) => set("modelo", e.target.value)}>
                  <option value="CLT">CLT</option><option value="PJ">PJ</option>
                </select>
              </div>
              <div><span style={label}>Início previsto</span><input type="date" style={inputStyle} value={f.inicio} onChange={(e) => set("inicio", e.target.value)} /></div>
            </div>
            <div><span style={label}>E-mail pessoal</span><input style={inputStyle} value={f.email_pessoal} onChange={(e) => set("email_pessoal", e.target.value)} placeholder="maria@email.com" /></div>
            {erro && <div style={{ fontSize: 12.5, color: C.red, fontWeight: 600 }}>{erro}</div>}
            <div style={{ display: "flex", gap: 10, justifyContent: "flex-end", marginTop: 4 }}>
              <Btn variant="ghost" size="sm" onClick={onClose}>Cancelar</Btn>
              <Btn icon="check" size="sm" onClick={salvar} disabled={saving}>{saving ? "Cadastrando…" : "Cadastrar e gerar link"}</Btn>
            </div>
          </div>
        ) : (
          <div style={{ padding: 22, display: "flex", flexDirection: "column", gap: 16 }}>
            <Card pad={16} style={{ background: C.greenSoft, borderColor: "#bfe6cd", display: "flex", alignItems: "center", gap: 11 }}>
              <Avatar nome={criado.row.nome} cor={criado.row.cor} size={40} />
              <div><div style={{ fontWeight: 800, color: C.ink }}>{criado.row.nome}</div><div style={{ fontSize: 12.5, color: C.ink2 }}>{criado.row.cargo || "—"}{criado.row.area ? " · " + criado.row.area : ""}</div></div>
            </Card>
            <div>
              <span style={label}>Link de acesso do colaborador (sem senha)</span>
              <div style={{ display: "flex", gap: 8, flexWrap: "wrap" }}>
                <input readOnly value={criado.link} onFocus={(e) => e.target.select()} style={{ ...inputStyle, flex: 1, minWidth: 220, fontSize: 12.5, color: C.cobaltDeep, background: C.cobaltSoft, borderColor: "#c7d6f7" }} />
                <Btn size="sm" icon={copiado ? "check" : "copy"} onClick={copiar}>{copiado ? "Copiado!" : "Copiar"}</Btn>
              </div>
              <div style={{ fontSize: 11.5, color: C.ink3, marginTop: 8, lineHeight: 1.5 }}>Dispare com a mensagem já pronta — sai do seu próprio e-mail/WhatsApp e entra direto na visão dele(a), sem senha.</div>
            </div>

            {(() => {
              const primeiro = (criado.row.nome || "").split(" ")[0];
              const to = criado.row.email_pessoal || "";
              const assunto = "Bem-vindo(a)! Sua integração começa aqui";
              const corpo = `Olá, ${primeiro}!\n\nQue bom ter você com a gente. Preparamos um espaço para te guiar nos primeiros dias.\n\nAcesse pelo link abaixo (sem senha):\n${criado.link}\n\nLá você encontra seu plano dos primeiros 30 dias, suas tarefas e onde registrar o seu dia a dia (manhã e tarde).\n\nQualquer dúvida, é só responder este e-mail. Boas-vindas!`;
              const mailHref = `mailto:${encodeURIComponent(to)}?subject=${encodeURIComponent(assunto)}&body=${encodeURIComponent(corpo)}`;
              const waHref = `https://wa.me/?text=${encodeURIComponent(`Olá, ${primeiro}! Sua integração já está pronta. Acesse (sem senha): ${criado.link}`)}`;
              const aBase = { display: "inline-flex", alignItems: "center", justifyContent: "center", gap: 8, fontFamily: "inherit", fontWeight: 700, fontSize: 14, padding: "11px 18px", borderRadius: 11, textDecoration: "none", flex: 1, minWidth: 170 };
              return (
                <div>
                  {!to && <div style={{ fontSize: 11.5, color: C.amber, fontWeight: 600, marginBottom: 8 }}>Sem e-mail pessoal cadastrado — o botão de e-mail abre em branco para você preencher o destinatário.</div>}
                  <div style={{ display: "flex", gap: 10, flexWrap: "wrap" }}>
                    <a href={mailHref} style={{ ...aBase, background: "linear-gradient(150deg,#CFA63E,#B8912A 70%,#9c7a22)", color: "#fff", boxShadow: "0 8px 18px -6px rgba(184,145,42,.55)" }}><LIcon name="mail" size={17} stroke={2.2} /> Enviar por e-mail</a>
                    <a href={waHref} target="_blank" rel="noopener noreferrer" style={{ ...aBase, background: "#fff", color: C.ink2, border: `1px solid ${C.line}` }}><LIcon name="message-circle" size={17} stroke={2.2} /> Enviar por WhatsApp</a>
                  </div>
                </div>
              );
            })()}

            <div style={{ display: "flex", justifyContent: "flex-end" }}><Btn size="sm" icon="check" onClick={onClose}>Concluir</Btn></div>
          </div>
        )}
      </div>
    </div>
  );
}

ReactDOM.createRoot(document.getElementById("root")).render(<Boot />);
