/* ============================================================
   VISÃO DO DONO (André) — cockpit de supervisão, read-only.
   Vê todos os onboardings, status macro e onde trava. Não executa.
   ============================================================ */
function DonoView({ done, meta }) {
  const [tab, setTab] = React.useState("painel");
  const noop = () => {};

  const tabs = [
    { k: "painel", label: "Painel do dia", icon: "radar" },
    { k: "geral", label: "Visão geral", icon: "layout-dashboard" },
    { k: "processo", label: "O processo", icon: "route" },
  ];

  return (
    <div style={{ display: "flex", flexDirection: "column", gap: 22 }}>
      <div style={{ display: "inline-flex", background: C.bgAlt, borderRadius: 12, padding: 3, alignSelf: "flex-start" }}>
        {tabs.map((t) => (
          <button key={t.k} onClick={() => setTab(t.k)} style={{
            display: "inline-flex", alignItems: "center", gap: 8, border: "none", cursor: "pointer", fontFamily: "inherit",
            background: tab === t.k ? "#fff" : "transparent", color: tab === t.k ? C.ink : C.ink2, fontWeight: 700, fontSize: 13.5,
            padding: "8px 15px", borderRadius: 9, boxShadow: tab === t.k ? "0 1px 3px rgba(15,23,42,.13)" : "none",
          }}><LIcon name={t.icon} size={16} /> {t.label}</button>
        ))}
      </div>

      {tab === "painel" && <PainelDono done={done} meta={meta} />}
      {tab === "geral" && <DonoOverview done={done} />}
      {tab === "processo" && <FluxoProcesso go={noop} />}
    </div>
  );
}

/* ---------- PAINEL DO DONO: acessos + dados do dia + alertas de prazo ---------- */
function PainelDono({ done, meta }) {
  const OE = window.OE;
  const cols = OE.colaboradores;
  const [, tick] = React.useState(0);
  const [editing, setEditing] = React.useState(null);

  const linhas = cols.map((c) => ({ c, a: OE.atividadeColab(meta[c.id], done[c.id]) }));
  const acessaramHoje = linhas.filter((l) => l.a.acessouHoje).length;
  const totalAlertas = linhas.reduce((n, l) => n + l.a.alertas.length, 0);
  const dadosHoje = linhas.reduce((n, l) => n + l.a.dadosInseridos, 0);
  const comAlerta = linhas.filter((l) => l.a.alertas.length);

  const fmtAcesso = (iso) => {
    if (!iso) return "—";
    const d = new Date(iso); const hoje = new Date().toISOString().slice(0, 10);
    const hm = d.toTimeString().slice(0, 5);
    return iso.slice(0, 10) === hoje ? `hoje ${hm}` : `${OE.fmtData(iso.slice(0, 10))} ${hm}`;
  };
  const etapaCell = (ok, alerta, prazo) =>
    ok ? <Pill tone="green" icon="check">Preenchida</Pill>
      : alerta ? <Pill tone="amber" icon="alert-triangle">Atrasada (até {prazo}h)</Pill>
        : <Pill tone="gray" icon="clock">Aguardando (até {prazo}h)</Pill>;

  function salvarEdicao(id, patch) {
    const c = cols.find((x) => x.id === id);
    window.OS.updateColaborador(id, patch)
      .then(() => { if (c) Object.assign(c, { ...patch, inicio: patch.inicio || null }); tick((n) => n + 1); setEditing(null); })
      .catch((e) => { alert("Não consegui salvar a edição: " + (e.message || e)); });
  }

  return (
    <div style={{ display: "flex", flexDirection: "column", gap: 24 }}>
      {/* ALERTAS DE PRAZO */}
      {totalAlertas > 0 && (
        <Card pad={0} style={{ overflow: "hidden", borderColor: "#f3d28a" }}>
          <div style={{ display: "flex", alignItems: "center", gap: 10, padding: "13px 18px", background: C.amberSoft, borderBottom: `1px solid #f3d28a` }}>
            <span style={{ color: C.amber }}><LIcon name="bell-ring" size={18} /></span>
            <span style={{ fontSize: 14, fontWeight: 800, color: C.ink }}>{totalAlertas} alerta(s) de prazo</span>
            <span style={{ fontSize: 12.5, color: C.ink3 }}>· 1ª etapa até 14h · 2ª etapa até 19h</span>
          </div>
          <div style={{ display: "flex", flexDirection: "column" }}>
            {comAlerta.map(({ c, a }) => (
              <div key={c.id} style={{ display: "flex", alignItems: "center", gap: 11, padding: "12px 18px", borderBottom: `1px solid ${C.lineSoft}` }}>
                <Avatar nome={c.nome} cor={c.cor} size={32} />
                <div style={{ fontWeight: 700, color: C.ink, minWidth: 140 }}>{c.nome}</div>
                <div style={{ display: "flex", gap: 7, flexWrap: "wrap" }}>{a.alertas.map((al, i) => <Pill key={i} tone="amber" icon="alert-triangle">{al.txt}</Pill>)}</div>
              </div>
            ))}
          </div>
        </Card>
      )}

      {/* KPIs do Dono */}
      <div style={{ display: "grid", gridTemplateColumns: "repeat(auto-fit,minmax(195px,1fr))", gap: 16 }}>
        <KPI val={cols.length} lab="Pessoas em integração" foot="No processo agora" icon="users" />
        <KPI val={`${acessaramHoje}/${cols.length}`} lab="Acessaram hoje" foot="Abriram o link hoje" icon="log-in" tone={acessaramHoje === cols.length ? "green" : "amber"} />
        <KPI val={totalAlertas} lab="Alertas de prazo" foot="1ª até 14h · 2ª até 19h" icon="bell-ring" tone={totalAlertas ? "amber" : "green"} />
        <KPI val={dadosHoje} lab="Dados inseridos" foot="Tarefas + diário + envios" icon="database" />
      </div>

      {/* ATIVIDADE: acessos + preenchimento do dia */}
      <div>
        <SectionTitle icon="activity" sub="Quem já acessou, quem inseriu os dados e o preenchimento de hoje — com o prazo de cada etapa.">Acessos & preenchimento do dia</SectionTitle>
        <Card pad={0} style={{ overflow: "hidden" }}>
          <div style={{ overflowX: "auto" }}>
            <table style={{ width: "100%", borderCollapse: "collapse", fontSize: 13.5 }}>
              <thead>
                <tr style={{ background: C.bg }}>
                  {["Colaborador", "Último acesso", "1ª etapa (14h)", "2ª etapa (19h)", "Dados inseridos", ""].map((h, i) => (
                    <th key={i} style={{ textAlign: "left", fontSize: 11, letterSpacing: ".08em", textTransform: "uppercase", color: C.ink3, fontWeight: 800, padding: "13px 16px", borderBottom: `1px solid ${C.line}`, whiteSpace: "nowrap" }}>{h}</th>
                  ))}
                </tr>
              </thead>
              <tbody>
                {linhas.map(({ c, a }) => (
                  <tr key={c.id} style={{ borderBottom: `1px solid ${C.lineSoft}` }}>
                    <td style={{ padding: "14px 16px" }}>
                      <div style={{ display: "flex", alignItems: "center", gap: 11 }}>
                        <Avatar nome={c.nome} cor={c.cor} size={36} />
                        <div><div style={{ fontWeight: 800, color: C.ink }}>{c.nome}</div><div style={{ fontSize: 11.5, color: C.ink3 }}>{c.cargo}</div></div>
                      </div>
                    </td>
                    <td style={{ padding: "14px 16px" }}>
                      {a.jamaisAcessou ? <Pill tone="amber" icon="link-2-off">Nunca acessou</Pill>
                        : <span style={{ color: C.ink2 }}><span style={{ display: "inline-flex", alignItems: "center", gap: 6 }}><LIcon name="log-in" size={13} />{fmtAcesso(a.acesso.ultimo)}</span><div style={{ fontSize: 11, color: C.ink3, marginTop: 2 }}>{a.acesso.total || 0} acesso(s)</div></span>}
                    </td>
                    <td style={{ padding: "14px 16px" }}>{etapaCell(a.manha, a.alertaManha, OE.PRAZO_MANHA)}</td>
                    <td style={{ padding: "14px 16px" }}>{etapaCell(a.tarde, a.alertaTarde, OE.PRAZO_TARDE)}</td>
                    <td style={{ padding: "14px 16px" }}>
                      <div style={{ display: "flex", gap: 8, flexWrap: "wrap", fontSize: 11.5, color: C.ink2 }}>
                        <span style={{ display: "inline-flex", alignItems: "center", gap: 4 }} title="Tarefas concluídas"><LIcon name="check-square" size={13} />{a.tarefas}</span>
                        <span style={{ display: "inline-flex", alignItems: "center", gap: 4 }} title="Turnos de diário"><LIcon name="notebook-pen" size={13} />{a.turnos}</span>
                        <span style={{ display: "inline-flex", alignItems: "center", gap: 4 }} title="Fechamentos semanais"><LIcon name="send" size={13} />{a.fechamentos}</span>
                        <span style={{ display: "inline-flex", alignItems: "center", gap: 4 }} title="Ideias"><LIcon name="lightbulb" size={13} />{a.ideias}</span>
                      </div>
                    </td>
                    <td style={{ padding: "14px 16px", textAlign: "right" }}>
                      <Btn variant="ghost" size="sm" icon="pencil" onClick={() => setEditing(c)}>Editar</Btn>
                    </td>
                  </tr>
                ))}
                {linhas.length === 0 && <tr><td colSpan={6} style={{ padding: "26px 16px", textAlign: "center", color: C.ink3 }}>Nenhum colaborador em integração ainda.</td></tr>}
              </tbody>
            </table>
          </div>
        </Card>
      </div>

      {editing && <EditColabModal c={editing} onClose={() => setEditing(null)} onSave={salvarEdicao} />}
    </div>
  );
}

function EditColabModal({ c, onClose, onSave }) {
  const [f, setF] = React.useState({ nome: c.nome || "", cargo: c.cargo || "", area: c.area || "", inicio: c.inicio || "", email_pessoal: c.email_pessoal || "", modelo: c.modelo || "CLT" });
  const set = (k, v) => setF((p) => ({ ...p, [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" };
  const lbl = { 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" }}>
        <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="pencil" size={18} /></span>
          <div style={{ flex: 1 }}><div style={{ fontSize: 16, fontWeight: 800, color: C.ink }}>Editar colaborador</div><div style={{ fontSize: 12.5, color: C.ink3 }}>Ajuste os dados se precisar.</div></div>
          <button onClick={onClose} style={{ background: "transparent", border: "none", cursor: "pointer", color: C.ink3, padding: 4 }}><LIcon name="x" size={20} /></button>
        </div>
        <div style={{ padding: 22, display: "flex", flexDirection: "column", gap: 14 }}>
          <div><span style={lbl}>Nome completo</span><input style={inp} value={f.nome} onChange={(e) => set("nome", e.target.value)} /></div>
          <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 12 }}>
            <div><span style={lbl}>Cargo</span><input style={inp} value={f.cargo} onChange={(e) => set("cargo", e.target.value)} /></div>
            <div><span style={lbl}>Área</span><input style={inp} value={f.area} onChange={(e) => set("area", e.target.value)} /></div>
          </div>
          <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 12 }}>
            <div><span style={lbl}>Início</span><input type="date" style={inp} value={f.inicio || ""} onChange={(e) => set("inicio", e.target.value)} /></div>
            <div><span style={lbl}>Contratação</span><select style={inp} value={f.modelo} onChange={(e) => set("modelo", e.target.value)}><option value="CLT">CLT</option><option value="PJ">PJ</option></select></div>
          </div>
          <div><span style={lbl}>E-mail pessoal</span><input style={inp} value={f.email_pessoal} onChange={(e) => set("email_pessoal", e.target.value)} /></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={() => onSave(c.id, f)}>Salvar</Btn>
          </div>
        </div>
      </div>
    </div>
  );
}

function DonoOverview({ done }) {
  const OE = window.OE;
  const cols = OE.colaboradores;

  let totalDone = 0, totalAll = 0, concluidos = 0;
  const atencao = [];
  cols.forEach((c) => {
    const p = OE.progressoColab(done[c.id] || new Set());
    totalDone += p.done; totalAll += p.total;
    if (p.pct === 100) concluidos++;
    const dias = c.inicio ? Math.round((new Date() - new Date(c.inicio + "T00:00:00")) / 86400000) : 0;
    if (dias > 25 && p.pct < 55) atencao.push({ c, p, dias });
  });
  const pctGeral = totalAll ? Math.round((totalDone / totalAll) * 100) : 0;

  const porEtapa = OE.PLAYBOOK.map((f) => {
    const n = cols.filter((c) => OE.faseDone(done[c.id] || new Set(), f.id)).length;
    return { f, n, total: cols.length };
  });

  return (
    <div style={{ display: "flex", flexDirection: "column", gap: 24 }}>
      {/* HERO */}
      <div style={{ background: "linear-gradient(120deg,#0E1A30,#1b2c4e 52%,#243B66)", borderRadius: 20, padding: "26px 30px", color: "#fff", display: "flex", alignItems: "center", gap: 28, flexWrap: "wrap" }}>
        <Ring value={pctGeral} size={100} 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" }}>Supervisão da integração</div>
          <div style={{ fontSize: 24, fontWeight: 800, letterSpacing: "-.02em", margin: "6px 0 4px" }}>{cols.length} pessoa(s) em integração</div>
          <div style={{ fontSize: 14, color: "#aeb9d0" }}>{concluidos} concluída(s) · {atencao.length} precisa(m) de atenção · {totalAll - totalDone} tarefas restantes</div>
        </div>
      </div>

      {/* PRECISAM DE ATENÇÃO */}
      <div>
        <SectionTitle icon="alert-triangle" sub="Início há mais de 25 dias e progresso abaixo de 55%. Onde a integração está travando.">Precisam de atenção</SectionTitle>
        {atencao.length === 0 ? (
          <Card pad={20} style={{ background: C.greenSoft, borderColor: "#bfe6cd", display: "flex", alignItems: "center", gap: 10 }}>
            <span style={{ color: C.green }}><LIcon name="check-check" size={20} /></span>
            <span style={{ fontSize: 13.5, color: C.ink2, fontWeight: 600 }}>Nenhuma integração em risco no momento.</span>
          </Card>
        ) : (
          <div style={{ display: "grid", gridTemplateColumns: "repeat(auto-fill,minmax(280px,1fr))", gap: 14 }}>
            {atencao.map(({ c, p, dias }) => (
              <Card key={c.id} pad={18} style={{ borderColor: C.amberSoft }}>
                <div style={{ display: "flex", alignItems: "center", gap: 11, marginBottom: 12 }}>
                  <Avatar nome={c.nome} cor={c.cor} size={38} />
                  <div><div style={{ fontWeight: 800, color: C.ink, fontSize: 14 }}>{c.nome}</div><div style={{ fontSize: 12, color: C.ink3 }}>{c.cargo}</div></div>
                  <span style={{ marginLeft: "auto" }}><Pill tone="amber" icon="clock">{dias}d</Pill></span>
                </div>
                <div style={{ display: "flex", alignItems: "center", gap: 9 }}>
                  <div style={{ flex: 1 }}><Bar value={p.pct} color={C.amber} /></div>
                  <span style={{ fontWeight: 800, color: C.ink, fontSize: 12.5 }}>{p.pct}%</span>
                </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 = total ? Math.round((n / total) * 100) : 0;
              const cor = pct === 100 ? C.green : pct === 0 ? C.ink3 : C.cobalt;
              return (
                <div key={f.id} style={{ display: "grid", gridTemplateColumns: "28px 1fr 90px 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}</span>
                </div>
              );
            })}
          </div>
        </Card>
      </div>
    </div>
  );
}

Object.assign(window, { DonoView });
