// Sistema Final v3, wireframe de apresentação
// + Banner/Stamp/Callouts (wireframe-feel)
// + Drag de frente entre obras (killer interaction)
// + Parâmetros globais (tela nova)

const { useState: useSF, useMemo: useMSF } = React;

// Datas relativas
function dataRelativa(iso) {
  if (!iso) return "—";
  const d = new Date(iso + "T00:00:00");
  const hoje = new Date("2026-05-07");
  const dias = Math.round((hoje - d) / 86400000);
  if (dias === 0) return "hoje";
  if (dias === 1) return "ontem";
  if (dias < 30) return `há ${dias} dias`;
  if (dias < 60) return "há 1 mês";
  return `há ${Math.floor(dias / 30)} meses`;
}

function fmtSF(v, d = 0) {
  return v == null || isNaN(v)
    ? "—"
    : Number(v).toLocaleString("pt-BR", {
        minimumFractionDigits: d,
        maximumFractionDigits: d,
      });
}
function brlSF(v) {
  return "R$ " + fmtSF(v);
}
function brlSFk(v) {
  if (v == null) return "—";
  const a = Math.abs(v);
  if (a >= 1_000_000)
    return (
      "R$ " +
      (v / 1_000_000).toLocaleString("pt-BR", { maximumFractionDigits: 2 }) +
      " M"
    );
  if (a >= 1_000)
    return (
      "R$ " +
      (v / 1_000).toLocaleString("pt-BR", { maximumFractionDigits: 0 }) +
      " k"
    );
  return brlSF(v);
}

/* ============================ APP RAIZ ============================ */
function SistemaFinalApp() {
  const [, forceRefresh] = React.useReducer((x) => x + 1, 0);
  const data = window.DESTACA_DATA;
  const [tela, setTela] = useSF("home");
  const [projetoId, setProjetoId] = useSF("P-2026-014");
  const [obraId, setObraId] = useSF("O-1");
  const [frenteId, setFrenteId] = useSF("F-1");
  const [v2View, setV2View] = useSF("frente");
  const [calloutsVisible, setCalloutsVisible] = useSF(true);

  const projeto =
    data.projetos.find((p) => p.id === projetoId) || data.projetos[0];
  const obra = projeto?.obras.find((o) => o.id === obraId) || projeto?.obras[0];
  const frente =
    obra?.frentes.find((f) => f.id === frenteId) || obra?.frentes?.[0];

  const navTo = (t, ids = {}) => {
    setTela(t);
    if (ids.projeto) setProjetoId(ids.projeto);
    if (ids.obra) setObraId(ids.obra);
    if (ids.frente) setFrenteId(ids.frente);
    if (ids.v2View) setV2View(ids.v2View);
  };

  const ctxValue = React.useMemo(
    () => ({ visible: calloutsVisible }),
    [calloutsVisible],
  );

  return (
    <DUI.CalloutsContext.Provider value={ctxValue}>
      <div
        data-screen-label="Sistema Final v3"
        style={{
          display: "flex",
          flexDirection: "column",
          height: "100%",
          minHeight: 800,
          background: "var(--d-bg)",
        }}
      >
        <DUI.Banner />
        <div style={{ display: "flex", flex: 1, minHeight: 0 }}>
          <SidebarFinal
            tela={tela}
            navTo={navTo}
            projeto={projeto}
            v2View={v2View}
          />
          <div
            style={{
              flex: 1,
              display: "flex",
              flexDirection: "column",
              minWidth: 0,
            }}
          >
            <TopbarFinal
              projeto={projeto}
              obra={obra}
              frente={frente}
              tela={tela}
              v2View={v2View}
              navTo={navTo}
              calloutsVisible={calloutsVisible}
              setCalloutsVisible={setCalloutsVisible}
            />
            <div
              style={{
                flex: 1,
                overflow: "auto",
                padding: 24,
                position: "relative",
              }}
              className="scroll"
            >
              {tela === "home" && <HomeExecutiva navTo={navTo} data={data} />}
              {tela === "projetos" && (
                <ListaProjetos navTo={navTo} data={data} />
              )}
              {tela === "projeto" && (
                <DetalheProjetoV3
                  projeto={projeto}
                  navTo={navTo}
                  forceRefresh={forceRefresh}
                />
              )}
              {tela === "obra" && (
                <DetalheObra projeto={projeto} obra={obra} navTo={navTo} />
              )}
              {tela === "frente" && (
                <EditorFrenteV2
                  projeto={projeto}
                  frente={frente}
                  onUpdateFrente={forceRefresh}
                />
              )}
              {tela === "v2-frente" && (
                <EditorFrenteV2
                  projeto={projeto}
                  frente={frente}
                  onUpdateFrente={forceRefresh}
                />
              )}
              {tela === "v2-margem" && (
                <MargemFrenteCallout>
                  <MargemValorVenda />
                </MargemFrenteCallout>
              )}
              {tela === "v2-timeline" && <TimelineGantt />}
              {tela === "v2-versoes" && <VersoesMultiusuario />}
              {tela === "relatorios" && <Relatorios data={data} />}
              {tela === "base" && <BaseConhecimentoV2 />}
              {tela === "glossario" && <Glossario />}
              {tela === "resumo" && <ResumoClienteFinal projeto={projeto} />}
              {tela === "parametros" &&
                window.ParametrosGlobais &&
                React.createElement(window.ParametrosGlobais, { forceRefresh })}
            </div>
          </div>
        </div>
        <DUI.Stamp />
      </div>
    </DUI.CalloutsContext.Provider>
  );
}

/* ============================ SIDEBAR ============================ */
function SidebarFinal({ tela, navTo, projeto, v2View }) {
  const projetoTelas = [
    "v2-frente",
    "v2-margem",
    "v2-timeline",
    "v2-versoes",
    "frente",
    "obra",
    "projeto",
    "resumo",
  ];
  const inProj = projetoTelas.includes(tela);

  return (
    <aside
      style={{
        width: 244,
        flexShrink: 0,
        background: "white",
        borderRight: "1px solid var(--d-border)",
        display: "flex",
        flexDirection: "column",
      }}
    >
      <div
        style={{
          padding: "16px 14px",
          borderBottom: "1px solid var(--d-border)",
          display: "flex",
          alignItems: "center",
          gap: 6,
        }}
      >
        <DUI.Logo small />
        <span className="wf-version-badge" title="Wireframe, apresentação">
          protótipo
        </span>
      </div>
      <div
        style={{ padding: "14px 8px", flex: 1, overflow: "auto" }}
        className="scroll"
      >
        <SBLabel>Geral</SBLabel>
        <DUI.NavItem
          icon="home"
          label="Início"
          active={tela === "home"}
          onClick={() => navTo("home")}
        />
        <DUI.NavItem
          icon="folder"
          label="Orçamentos"
          badge="14"
          active={tela === "projetos"}
          onClick={() => navTo("projetos")}
        />
        <DUI.NavItem
          icon="chart"
          label="Relatórios"
          active={tela === "relatorios"}
          onClick={() => navTo("relatorios")}
        />

        {inProj && projeto && (
          <>
            <SBLabel>Orçamento atual</SBLabel>
            <div style={{ padding: "4px 12px 10px" }}>
              <div
                className="d-mono"
                style={{
                  font: "500 10.5px/1 JetBrains Mono",
                  color: "var(--d-text-3)",
                }}
              >
                {projeto.id}
              </div>
              <div
                style={{
                  font: "600 12.5px/1.3 Inter",
                  color: "var(--d-text)",
                  marginTop: 3,
                }}
              >
                {projeto.nome.length > 30
                  ? projeto.nome.slice(0, 30) + "…"
                  : projeto.nome}
              </div>
            </div>
            <DUI.NavItem
              icon="layers"
              label="Estrutura"
              indent
              active={tela === "projeto"}
              onClick={() => navTo("projeto")}
            />
            <DUI.NavItem
              icon="pile"
              label="Editor de Frente"
              indent
              active={tela === "v2-frente"}
              onClick={() => navTo("v2-frente")}
            />
            <DUI.NavItem
              icon="money"
              label="Margem & Venda"
              indent
              active={tela === "v2-margem"}
              onClick={() => navTo("v2-margem")}
            />
            <DUI.NavItem
              icon="clock"
              label="Cronograma"
              indent
              active={tela === "v2-timeline"}
              onClick={() => navTo("v2-timeline")}
            />
            <DUI.NavItem
              icon="layers"
              label="Versões"
              indent
              active={tela === "v2-versoes"}
              onClick={() => navTo("v2-versoes")}
            />
            <DUI.NavItem
              icon="eye"
              label="Visão do cliente"
              indent
              active={tela === "resumo"}
              onClick={() => navTo("resumo")}
            />
          </>
        )}

        <SBLabel>Sistema</SBLabel>
        <DUI.NavItem
          icon="book"
          label="Base de conhecimento"
          active={tela === "base"}
          onClick={() => navTo("base")}
        />
        <DUI.NavItem
          icon="set"
          label="Parâmetros globais"
          active={tela === "parametros"}
          onClick={() => navTo("parametros")}
        />
        <DUI.NavItem
          icon="info"
          label="Glossário"
          active={tela === "glossario"}
          onClick={() => navTo("glossario")}
        />
      </div>
      <div
        style={{
          padding: "12px 14px",
          borderTop: "1px solid var(--d-border)",
          display: "flex",
          alignItems: "center",
          gap: 10,
        }}
      >
        <div
          style={{
            width: 28,
            height: 28,
            borderRadius: 100,
            background: "#22A94A",
            color: "white",
            display: "flex",
            alignItems: "center",
            justifyContent: "center",
            font: "600 12px/1 Inter",
          }}
        >
          AN
        </div>
        <div style={{ minWidth: 0, flex: 1 }}>
          <div style={{ font: "600 12.5px/1.2 Inter" }}>Ana</div>
          <div style={{ font: "500 11px/1.2 Inter", color: "var(--d-text-3)" }}>
            Planejamento
          </div>
        </div>
        <DUI.Icon name="set" size={15} style={{ color: "var(--d-text-3)" }} />
      </div>
    </aside>
  );
}
function SBLabel({ children }) {
  return (
    <div
      style={{
        font: "600 10.5px/1 Inter",
        letterSpacing: "0.08em",
        color: "var(--d-text-3)",
        textTransform: "uppercase",
        padding: "14px 12px 6px",
      }}
    >
      {children}
    </div>
  );
}

/* ============================ TOPBAR ============================ */
function TopbarFinal({
  projeto,
  obra,
  frente,
  tela,
  navTo,
  calloutsVisible,
  setCalloutsVisible,
}) {
  const titulos = {
    home: ["Início", "Painel executivo da Destaca"],
    projetos: ["Orçamentos", "Pipeline de orçamentos"],
    relatorios: [
      "Relatórios",
      "Análises financeiras, operacionais e de performance",
    ],
    base: ["Base de Conhecimento", "Cadastros, reajustes e alertas de impacto"],
    parametros: [
      "Parâmetros globais",
      "Insumos, mão de obra e BDI, propagação a todos os projetos",
    ],
    glossario: ["Glossário do domínio", "Termos validados pela operação"],
    projeto: [projeto?.nome, "Estrutura do orçamento · " + projeto?.id],
    "v2-frente": [
      "Editor de Frente",
      "Permanência mês a mês, custos por categoria",
    ],
    "v2-margem": [
      "Margem & Valor de Venda",
      "Rentabilidade por frente, obra e projeto",
    ],
    "v2-timeline": ["Cronograma", "Movimentação de frentes entre obras"],
    "v2-versoes": ["Versões e equipe", "Controle de revisões e usuários"],
    resumo: ["Visão do cliente", "Documento final do orçamento"],
  };
  const [t1, t2] = titulos[tela] || ["", ""];
  return (
    <header
      style={{
        minHeight: 60,
        background: "white",
        borderBottom: "1px solid var(--d-border)",
        display: "flex",
        alignItems: "center",
        padding: "0 22px",
        gap: 14,
      }}
    >
      <div style={{ flex: 1, minWidth: 0 }}>
        <div
          style={{
            font: "600 16px/1.1 Inter",
            color: "var(--d-text)",
            whiteSpace: "nowrap",
            overflow: "hidden",
            textOverflow: "ellipsis",
          }}
        >
          {t1}
        </div>
        <div
          style={{
            font: "500 12px/1 Inter",
            color: "var(--d-text-3)",
            marginTop: 4,
            whiteSpace: "nowrap",
            overflow: "hidden",
            textOverflow: "ellipsis",
          }}
        >
          {t2}
        </div>
      </div>
      <DUI.MockArea inline>
        <div
          style={{
            position: "relative",
            flex: "0 1 260px",
            minWidth: 160,
            display: "inline-block",
          }}
        >
          <DUI.Icon
            name="search"
            size={14}
            style={{
              position: "absolute",
              left: 10,
              top: 9,
              color: "var(--d-text-3)",
            }}
          />
          <input
            className="inp"
            style={{
              width: 240,
              paddingLeft: 30,
              height: 28,
              background: "transparent",
              border: "none",
              cursor: "not-allowed",
            }}
            placeholder="Buscar orçamento, cliente, frente…"
            disabled
          />
          <span
            style={{
              position: "absolute",
              right: 8,
              top: 6,
              font: "500 10.5px/1 JetBrains Mono",
              color: "var(--d-text-4)",
              background: "var(--d-bg-2)",
              padding: "3px 5px",
              borderRadius: 3,
            }}
          >
            ⌘K
          </span>
        </div>
      </DUI.MockArea>
      <button
        className="btn btn-sm"
        onClick={() => setCalloutsVisible((v) => !v)}
        style={{
          background: calloutsVisible ? "var(--d-callout-bg)" : "transparent",
          borderColor: calloutsVisible
            ? "var(--d-callout-border)"
            : "var(--d-border-strong)",
        }}
      >
        <DUI.Icon name="sparkle" size={13} />
        {calloutsVisible ? "Ocultar anotações" : "Anotações"}
      </button>
      <DUI.MockArea inline>
        <button
          className="btn"
          disabled
          style={{
            cursor: "not-allowed",
            background: "transparent",
            border: "none",
          }}
        >
          <DUI.Icon name="bell" size={14} />
        </button>
      </DUI.MockArea>
      {tela.startsWith("v2-") || tela === "resumo" || tela === "projeto" ? (
        <>
          <span className="chip chip-warn">
            <span
              style={{
                display: "inline-block",
                width: 6,
                height: 6,
                borderRadius: 100,
                background: "#d97706",
                marginRight: 4,
              }}
            />
            RASCUNHO · v3
          </span>
          <button className="btn btn-primary btn-sm">
            <DUI.Icon name="check" size={13} />
            Salvar revisão
          </button>
        </>
      ) : (
        <DUI.MockArea inline>
          <button
            className="btn btn-sm"
            disabled
            style={{
              cursor: "not-allowed",
              background: "transparent",
              border: "none",
            }}
          >
            <DUI.Icon name="plus" size={13} />
            Novo orçamento
          </button>
        </DUI.MockArea>
      )}
    </header>
  );
}

/* ============================ HOME EXECUTIVA ============================ */
function HomeExecutiva({ navTo, data }) {
  const totalAberto = data.projetos
    .filter((p) => p.status !== "aprovado" && p.status !== "perdido")
    .reduce((s, p) => s + p.valor, 0);
  const totalAprovado = data.projetos
    .filter((p) => p.status === "aprovado")
    .reduce((s, p) => s + p.valor, 0);
  const totalPipeline = data.projetos.reduce((s, p) => s + p.valor, 0);

  return (
    <div style={{ maxWidth: 1380, position: "relative" }}>
      <DUI.Callout num="①" anchor="left" top={170} left={-12} width={200}>
        Painel executivo: pipeline em tempo real, alertas de impacto e atividade
        da equipe num só lugar.
      </DUI.Callout>
      {/* Saudação + ações rápidas */}
      <div
        style={{
          display: "grid",
          gridTemplateColumns: "1.5fr 1fr",
          gap: 18,
          marginBottom: 18,
        }}
      >
        <div
          className="card"
          style={{
            padding: 22,
            background: "linear-gradient(135deg, #0E2A47 0%, #16395f 100%)",
            color: "white",
            position: "relative",
            overflow: "hidden",
          }}
        >
          <div
            style={{
              position: "absolute",
              top: -40,
              right: -40,
              width: 240,
              height: 240,
              borderRadius: "50%",
              background: "rgba(34,169,74,0.12)",
            }}
          />
          <div style={{ position: "relative" }}>
            <div
              style={{
                font: "500 12.5px/1 Inter",
                color: "rgba(255,255,255,0.65)",
              }}
            >
              Quarta, 6 de maio de 2026
            </div>
            <h1
              style={{
                margin: "8px 0 0",
                font: "700 26px/1.15 Inter",
                letterSpacing: "-0.01em",
              }}
            >
              Bom dia, Ana.
            </h1>
            <div
              style={{
                font: "500 13.5px/1.5 Inter",
                color: "rgba(255,255,255,0.85)",
                marginTop: 8,
                maxWidth: 600,
              }}
            >
              Você tem{" "}
              <strong style={{ color: "#22A94A" }}>
                2 orçamentos aguardando revisão
              </strong>{" "}
              e <strong style={{ color: "#22A94A" }}>3 alertas</strong> de
              impacto de preço pendentes.
            </div>
            <div style={{ display: "flex", gap: 10, marginTop: 18 }}>
              <button
                className="btn"
                style={{
                  background: "rgba(255,255,255,0.1)",
                  color: "white",
                  borderColor: "rgba(255,255,255,0.2)",
                }}
                onClick={() => navTo("projetos")}
              >
                <DUI.Icon name="folder" size={13} />
                Ver pipeline
              </button>
              <button
                className="btn"
                style={{
                  background: "rgba(255,255,255,0.1)",
                  color: "white",
                  borderColor: "rgba(255,255,255,0.2)",
                }}
                onClick={() => navTo("relatorios")}
              >
                <DUI.Icon name="chart" size={13} />
                Relatórios
              </button>
            </div>
          </div>
        </div>

        {/* Tarefas pendentes da Ana */}
        <div className="card" style={{ padding: 0 }}>
          <div
            style={{
              padding: "14px 18px",
              borderBottom: "1px solid var(--d-border)",
              display: "flex",
              alignItems: "center",
            }}
          >
            <h3 style={{ margin: 0, font: "600 14px/1 Inter" }}>
              Sua caixa de entrada
            </h3>
            <span
              className="chip chip-warn"
              style={{ marginLeft: 8, height: 18, fontSize: 10 }}
            >
              5
            </span>
          </div>
          <div style={{ padding: "4px 0" }}>
            {[
              {
                tipo: "aprovacao",
                txt: "Aprovar revisão v3 do P-2026-014",
                sub: "Solicitado por Carla · 2h",
                cor: "#d97706",
              },
              {
                tipo: "alerta",
                txt: "Diesel subiu 4,9%, 7 projetos afetados",
                sub: "Aplicado automaticamente · ontem",
                cor: "#c8302a",
              },
              {
                tipo: "comentario",
                txt: "Wanderlei comentou na Frente F-3",
                sub: '"Pode reduzir margem? Cliente apertou"',
                cor: "#2363b8",
              },
              {
                tipo: "agendado",
                txt: "Dissídio agendado para outubro/26",
                sub: "Reajuste de +5% · em 5 meses",
                cor: "#7c8597",
              },
            ].map((t, i) => (
              <div
                key={i}
                style={{
                  padding: "10px 18px",
                  borderTop: i > 0 ? "1px solid var(--d-border)" : "none",
                  display: "flex",
                  gap: 10,
                  cursor: "pointer",
                }}
              >
                <div
                  style={{
                    width: 6,
                    height: 6,
                    borderRadius: 100,
                    background: t.cor,
                    marginTop: 7,
                    flex: "none",
                  }}
                />
                <div style={{ flex: 1, minWidth: 0 }}>
                  <div
                    style={{
                      font: "500 12.5px/1.4 Inter",
                      color: "var(--d-text)",
                    }}
                  >
                    {t.txt}
                  </div>
                  <div
                    style={{
                      font: "500 11px/1.3 Inter",
                      color: "var(--d-text-3)",
                      marginTop: 2,
                    }}
                  >
                    {t.sub}
                  </div>
                </div>
              </div>
            ))}
          </div>
        </div>
      </div>

      {/* KPIs */}
      <div
        className="card"
        style={{
          display: "grid",
          gridTemplateColumns: "repeat(5, 1fr)",
          marginBottom: 18,
        }}
      >
        <DUI.Kpi
          label="Pipeline total"
          value={brlSFk(totalPipeline)}
          sub={`${data.projetos.length} orçamentos`}
        />
        <DUI.Kpi
          label="Aprovado em 2026"
          value={brlSFk(totalAprovado)}
          accent="#22A94A"
          sub="↑ 23% vs 2025"
        />
        <DUI.Kpi
          label="Em aberto"
          value={brlSFk(totalAberto)}
          sub="aguardando cliente"
        />
        <DUI.Kpi
          label="Taxa de conversão"
          value="42%"
          sub="↑ 6 p.p. vs trimestre"
        />
        <DUI.Kpi
          label="Margem média"
          value="34,2%"
          accent="#22A94A"
          sub="meta 30%"
        />
      </div>

      {/* Pipeline + Atividade */}
      <div
        style={{
          display: "grid",
          gridTemplateColumns: "2fr 1fr",
          gap: 18,
          marginBottom: 18,
        }}
      >
        <div className="card" style={{ padding: 0 }}>
          <div
            style={{
              padding: "14px 18px",
              borderBottom: "1px solid var(--d-border)",
              display: "flex",
              alignItems: "center",
            }}
          >
            <h3 style={{ margin: 0, font: "600 14px/1 Inter" }}>
              Pipeline em foco
            </h3>
            <button
              className="btn btn-ghost btn-sm"
              style={{ marginLeft: "auto" }}
              onClick={() => navTo("projetos")}
            >
              Ver todos →
            </button>
          </div>
          <table className="tbl">
            <thead>
              <tr>
                <th>Projeto</th>
                <th>Cliente</th>
                <th>Status</th>
                <th className="num">Valor</th>
                <th>Próximo passo</th>
              </tr>
            </thead>
            <tbody>
              {data.projetos.slice(0, 5).map((p) => {
                const proximo =
                  p.status === "em-revisao"
                    ? "aguardando aprovação interna"
                    : p.status === "rascunho"
                      ? "completar 2 frentes"
                      : p.status === "enviado"
                        ? "cliente analisando"
                        : p.status === "aprovado"
                          ? "em execução"
                          : "arquivado";
                return (
                  <tr
                    key={p.id}
                    style={{ cursor: "pointer" }}
                    onClick={() => navTo("projeto", { projeto: p.id })}
                  >
                    <td>
                      <div
                        className="d-mono"
                        style={{
                          font: "500 10.5px/1 JetBrains Mono",
                          color: "var(--d-text-3)",
                          marginBottom: 3,
                        }}
                      >
                        {p.id}
                      </div>
                      <div style={{ font: "600 12.5px/1.3 Inter" }}>
                        {p.nome}
                      </div>
                    </td>
                    <td style={{ color: "var(--d-text-2)" }}>
                      {p.cliente}
                      <div
                        style={{
                          font: "500 11px/1.2 Inter",
                          color: "var(--d-text-3)",
                        }}
                      >
                        {p.local}
                      </div>
                    </td>
                    <td>
                      <DUI.StatusPill status={p.status} />
                    </td>
                    <td className="num" style={{ fontWeight: 600 }}>
                      {brlSFk(p.valor)}
                    </td>
                    <td
                      style={{
                        font: "500 11.5px/1.4 Inter",
                        color: "var(--d-text-2)",
                      }}
                    >
                      {proximo}
                    </td>
                  </tr>
                );
              })}
            </tbody>
          </table>
        </div>

        <div className="card" style={{ padding: 18 }}>
          <h3 style={{ margin: 0, font: "600 14px/1 Inter", marginBottom: 14 }}>
            Atividade da equipe
          </h3>
          <div style={{ display: "flex", flexDirection: "column", gap: 14 }}>
            {[
              {
                who: "Carla",
                act: "cotou 3 equipamentos para",
                proj: "Cais Norte",
                t: "12min",
                icon: "truck",
                color: "#22A94A",
              },
              {
                who: "Você",
                act: "editou Frente F-1 em",
                proj: "Cais Norte",
                t: "2h",
                icon: "edit",
                color: "#2363b8",
              },
              {
                who: "Wanderlei",
                act: "aprovou margem de",
                proj: "Ponte Rio Pardo",
                t: "4h",
                icon: "check",
                color: "#22A94A",
              },
              {
                who: "Sistema",
                act: "recalculou 7 projetos por mudança no diesel",
                proj: "",
                t: "ontem",
                icon: "calc",
                color: "#d97706",
              },
              {
                who: "Marcos",
                act: "atualizou preço do eletrodo",
                proj: "",
                t: "ontem",
                icon: "pkg",
                color: "#7c8597",
              },
              {
                who: "Júlia",
                act: "enviou para o cliente",
                proj: "Subestação CTEEP",
                t: "2 dias",
                icon: "share",
                color: "#0E2A47",
              },
            ].map((a, i) => (
              <div
                key={i}
                style={{ display: "flex", gap: 10, alignItems: "flex-start" }}
              >
                <div
                  style={{
                    width: 28,
                    height: 28,
                    borderRadius: 100,
                    background: a.color + "15",
                    color: a.color,
                    display: "flex",
                    alignItems: "center",
                    justifyContent: "center",
                    flex: "none",
                  }}
                >
                  <DUI.Icon name={a.icon} size={13} />
                </div>
                <div style={{ minWidth: 0, flex: 1 }}>
                  <div
                    style={{
                      font: "500 12px/1.4 Inter",
                      color: "var(--d-text-2)",
                    }}
                  >
                    <span style={{ fontWeight: 600, color: "var(--d-text)" }}>
                      {a.who}
                    </span>{" "}
                    {a.act}{" "}
                    {a.proj && (
                      <span style={{ fontWeight: 600, color: "var(--d-text)" }}>
                        {a.proj}
                      </span>
                    )}
                  </div>
                  <div
                    style={{
                      font: "500 10.5px/1 Inter",
                      color: "var(--d-text-4)",
                      marginTop: 3,
                    }}
                  >
                    {a.t} atrás
                  </div>
                </div>
              </div>
            ))}
          </div>
        </div>
      </div>

      {/* Linha inferior: alertas + obras em execução */}
      <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 18 }}>
        <div className="card" style={{ padding: 0 }}>
          <div
            style={{
              padding: "14px 18px",
              borderBottom: "1px solid var(--d-border)",
              display: "flex",
              alignItems: "center",
            }}
          >
            <DUI.Icon
              name="bell"
              size={14}
              style={{ color: "#d97706", marginRight: 8 }}
            />
            <h3 style={{ margin: 0, font: "600 14px/1 Inter" }}>
              Alertas de impacto
            </h3>
            <button
              className="btn btn-ghost btn-sm"
              style={{ marginLeft: "auto" }}
              onClick={() => navTo("base")}
            >
              Ver tudo →
            </button>
          </div>
          {[
            {
              item: "Diesel S10",
              de: "R$ 6,15",
              para: "R$ 6,45",
              proj: 7,
              dt: "aplicado 28/04",
              cor: "#22A94A",
            },
            {
              item: "Aluguel Guindaste 100t",
              de: "R$ 92k",
              para: "R$ 95k",
              proj: 3,
              dt: "aguardando",
              cor: "#d97706",
            },
            {
              item: "Salário Soldador (dissídio)",
              de: "R$ 4,5k",
              para: "R$ 4,72k",
              proj: 12,
              dt: "agendado out/26",
              cor: "#2363b8",
            },
          ].map((a, i) => (
            <div
              key={i}
              style={{
                padding: "12px 18px",
                borderTop: "1px solid var(--d-border)",
                display: "flex",
                alignItems: "center",
                gap: 10,
              }}
            >
              <div style={{ flex: 1 }}>
                <div style={{ font: "600 12.5px/1.2 Inter" }}>{a.item}</div>
                <div
                  style={{
                    font: "500 11.5px/1.4 Inter",
                    color: "var(--d-text-3)",
                    marginTop: 3,
                  }}
                >
                  <span className="d-mono">{a.de}</span> →{" "}
                  <span className="d-mono" style={{ color: "#d97706" }}>
                    {a.para}
                  </span>{" "}
                  · {a.proj} projetos
                </div>
              </div>
              <span
                className="chip"
                style={{
                  background: a.cor + "22",
                  color: a.cor,
                  height: 18,
                  fontSize: 10,
                }}
              >
                {a.dt.toUpperCase()}
              </span>
            </div>
          ))}
        </div>

        <div className="card" style={{ padding: 0 }}>
          <div
            style={{
              padding: "14px 18px",
              borderBottom: "1px solid var(--d-border)",
            }}
          >
            <h3 style={{ margin: 0, font: "600 14px/1 Inter" }}>
              Obras em execução
            </h3>
            <div
              style={{
                font: "500 11.5px/1 Inter",
                color: "var(--d-text-3)",
                marginTop: 3,
              }}
            >
              Real vs orçado · 4 obras ativas
            </div>
          </div>
          {[
            {
              obra: "Ponte Rio Pardo · Pilar P5-P12",
              prog: 78,
              prazo: "no prazo",
              dias: 12,
              cor: "#22A94A",
            },
            {
              obra: "Cais Itaqui · Frente A",
              prog: 64,
              prazo: "no prazo",
              dias: 24,
              cor: "#22A94A",
            },
            {
              obra: "Galpão Logus II · Cravação",
              prog: 42,
              prazo: "2d atrasada",
              dias: 38,
              cor: "#d97706",
            },
            {
              obra: "Subest. CTEEP · Torres",
              prog: 91,
              prazo: "adiantada 4d",
              dias: 8,
              cor: "#22A94A",
            },
          ].map((o, i) => (
            <div
              key={i}
              style={{
                padding: "12px 18px",
                borderTop: "1px solid var(--d-border)",
              }}
            >
              <div
                style={{
                  display: "flex",
                  alignItems: "center",
                  gap: 8,
                  marginBottom: 6,
                }}
              >
                <span style={{ font: "600 12px/1.3 Inter", flex: 1 }}>
                  {o.obra}
                </span>
                <span style={{ font: "500 11px/1 Inter", color: o.cor }}>
                  {o.prazo}
                </span>
              </div>
              <div style={{ display: "flex", alignItems: "center", gap: 10 }}>
                <div
                  style={{
                    flex: 1,
                    height: 5,
                    background: "var(--d-bg-2)",
                    borderRadius: 100,
                  }}
                >
                  <div
                    style={{
                      height: "100%",
                      width: o.prog + "%",
                      background: o.cor,
                      borderRadius: 100,
                    }}
                  />
                </div>
                <span
                  className="d-mono"
                  style={{
                    font: "600 11.5px/1 JetBrains Mono",
                    color: "var(--d-text-2)",
                    width: 30,
                    textAlign: "right",
                  }}
                >
                  {o.prog}%
                </span>
                <span
                  style={{
                    font: "500 11px/1 Inter",
                    color: "var(--d-text-3)",
                    width: 56,
                    textAlign: "right",
                  }}
                >
                  {o.dias}d rest
                </span>
              </div>
            </div>
          ))}
        </div>
      </div>
    </div>
  );
}

/* ============================ RELATÓRIOS ============================ */
function Relatorios({ data }) {
  const [aba, setAba] = useSF("financeiro");
  const abas = [
    { id: "financeiro", label: "Financeiro", icon: "money" },
    { id: "operacional", label: "Operacional", icon: "pile" },
    { id: "comercial", label: "Comercial", icon: "chart" },
    { id: "custos", label: "Custos & insumos", icon: "pkg" },
  ];

  return (
    <div style={{ maxWidth: 1380 }}>
      {/* Filtros */}
      <div
        className="card"
        style={{
          padding: "12px 18px",
          marginBottom: 16,
          display: "flex",
          alignItems: "center",
          gap: 12,
        }}
      >
        <span
          style={{
            font: "600 11.5px/1 Inter",
            color: "var(--d-text-3)",
            textTransform: "uppercase",
            letterSpacing: "0.05em",
          }}
        >
          Período
        </span>
        <div
          style={{
            display: "flex",
            gap: 4,
            background: "var(--d-bg-2)",
            padding: 3,
            borderRadius: 6,
          }}
        >
          {["7d", "30d", "90d", "YTD", "12m", "tudo"].map((p) => (
            <button
              key={p}
              className="btn btn-sm"
              style={{
                background: p === "YTD" ? "white" : "transparent",
                boxShadow: p === "YTD" ? "0 1px 2px rgba(0,0,0,0.06)" : "none",
                borderColor: "transparent",
                font: p === "YTD" ? "600 11.5px/1 Inter" : "500 11.5px/1 Inter",
              }}
            >
              {p}
            </button>
          ))}
        </div>
        <div style={{ flex: 1 }} />
        <select className="inp" style={{ height: 32, width: 160 }}>
          <option>Todos os clientes</option>
        </select>
        <select className="inp" style={{ height: 32, width: 160 }}>
          <option>Todos os tipos</option>
        </select>
        <button className="btn">
          <DUI.Icon name="excel" size={13} />
          Exportar
        </button>
        <button className="btn">
          <DUI.Icon name="download" size={13} />
          PDF
        </button>
      </div>

      {/* Tabs */}
      <div
        style={{
          display: "flex",
          gap: 4,
          borderBottom: "1px solid var(--d-border)",
          marginBottom: 16,
        }}
      >
        {abas.map((a) => (
          <button
            key={a.id}
            onClick={() => setAba(a.id)}
            style={{
              background: "none",
              border: "none",
              cursor: "pointer",
              padding: "10px 14px",
              font: "500 13px/1 Inter",
              color: aba === a.id ? "var(--d-text)" : "var(--d-text-3)",
              borderBottom: "2px solid",
              borderColor: aba === a.id ? "#22A94A" : "transparent",
              display: "flex",
              alignItems: "center",
              gap: 7,
              marginBottom: -1,
            }}
          >
            <DUI.Icon name={a.icon} size={14} />
            {a.label}
          </button>
        ))}
      </div>

      {aba === "financeiro" && <RelFinanceiro />}
      {aba === "operacional" && <RelOperacional />}
      {aba === "comercial" && <RelComercial data={data} />}
      {aba === "custos" && <RelCustos />}
    </div>
  );
}

function RelFinanceiro() {
  const meses = [
    "Jan",
    "Fev",
    "Mar",
    "Abr",
    "Mai",
    "Jun",
    "Jul",
    "Ago",
    "Set",
    "Out",
    "Nov",
    "Dez",
  ];
  const orcado = [3.2, 2.8, 4.5, 5.2, 4.8, 0, 0, 0, 0, 0, 0, 0];
  const aprovado = [2.1, 2.4, 3.8, 4.2, 0, 0, 0, 0, 0, 0, 0, 0];
  const max = Math.max(...orcado);

  return (
    <>
      <div
        className="card"
        style={{
          display: "grid",
          gridTemplateColumns: "repeat(4, 1fr)",
          marginBottom: 16,
        }}
      >
        <DUI.Kpi
          label="Faturamento YTD"
          value="R$ 12,5 M"
          accent="#22A94A"
          sub="↑ 18% vs 2025"
        />
        <DUI.Kpi label="Margem média" value="34,2%" sub="meta 30%" />
        <DUI.Kpi
          label="Custo MO direta"
          value="R$ 4,2 M"
          sub="33,6% do faturamento"
        />
        <DUI.Kpi
          label="Custo equipamentos"
          value="R$ 3,1 M"
          sub="24,8% do faturamento"
        />
      </div>

      <div className="card" style={{ padding: 18, marginBottom: 16 }}>
        <div
          style={{ display: "flex", alignItems: "center", marginBottom: 16 }}
        >
          <h3 style={{ margin: 0, font: "600 14px/1 Inter" }}>
            Orçado vs aprovado por mês
          </h3>
          <div
            style={{
              marginLeft: "auto",
              display: "flex",
              gap: 14,
              font: "500 11.5px/1 Inter",
              color: "var(--d-text-3)",
            }}
          >
            <span>
              <span
                style={{
                  display: "inline-block",
                  width: 10,
                  height: 10,
                  background: "#0E2A47",
                  borderRadius: 2,
                  marginRight: 6,
                }}
              />
              Orçado
            </span>
            <span>
              <span
                style={{
                  display: "inline-block",
                  width: 10,
                  height: 10,
                  background: "#22A94A",
                  borderRadius: 2,
                  marginRight: 6,
                }}
              />
              Aprovado
            </span>
          </div>
        </div>
        <div
          style={{
            display: "flex",
            alignItems: "flex-end",
            gap: 6,
            height: 180,
            paddingTop: 16,
          }}
        >
          {meses.map((m, i) => (
            <div
              key={i}
              style={{
                flex: 1,
                display: "flex",
                flexDirection: "column",
                alignItems: "center",
                gap: 4,
              }}
            >
              <div
                style={{
                  display: "flex",
                  alignItems: "flex-end",
                  gap: 3,
                  height: 150,
                  width: "100%",
                  justifyContent: "center",
                }}
              >
                <div
                  style={{
                    width: 14,
                    height: (orcado[i] / max) * 150 + "px",
                    background: "#0E2A47",
                    borderRadius: "3px 3px 0 0",
                    minHeight: orcado[i] > 0 ? 2 : 0,
                  }}
                />
                <div
                  style={{
                    width: 14,
                    height: (aprovado[i] / max) * 150 + "px",
                    background: "#22A94A",
                    borderRadius: "3px 3px 0 0",
                    minHeight: aprovado[i] > 0 ? 2 : 0,
                  }}
                />
              </div>
              <div
                style={{ font: "500 10px/1 Inter", color: "var(--d-text-3)" }}
              >
                {m}
              </div>
              {orcado[i] > 0 && (
                <div
                  className="d-mono"
                  style={{
                    font: "600 9.5px/1 JetBrains Mono",
                    color: "var(--d-text-2)",
                  }}
                >
                  {orcado[i].toFixed(1)}M
                </div>
              )}
            </div>
          ))}
        </div>
      </div>

      <div style={{ display: "grid", gridTemplateColumns: "2fr 1fr", gap: 16 }}>
        <div className="card" style={{ padding: 0 }}>
          <div
            style={{
              padding: "14px 18px",
              borderBottom: "1px solid var(--d-border)",
            }}
          >
            <h3 style={{ margin: 0, font: "600 14px/1 Inter" }}>
              Top 10 projetos por valor
            </h3>
          </div>
          <table className="tbl">
            <thead>
              <tr>
                <th>Projeto</th>
                <th>Cliente</th>
                <th className="num">Custo</th>
                <th className="num">Venda</th>
                <th className="num">Margem</th>
              </tr>
            </thead>
            <tbody>
              {[
                ["Terminal Portuário Sul", "PortoSul", 18.2, 24.8, 36.3],
                ["Cais Itaqui Norte", "Porto MA", 14.1, 19.2, 36.2],
                ["Subestação CTEEP", "CTEEP", 2.8, 3.65, 30.4],
                ["Ponte Rio Pardo", "DER-SP", 6.2, 8.42, 35.8],
                ["Galpão Logus", "Logus", 0.94, 1.28, 36.2],
              ].map((r, i) => (
                <tr key={i}>
                  <td style={{ fontWeight: 600 }}>{r[0]}</td>
                  <td style={{ color: "var(--d-text-2)" }}>{r[1]}</td>
                  <td className="num">R$ {r[2]} M</td>
                  <td
                    className="num"
                    style={{ color: "#22A94A", fontWeight: 600 }}
                  >
                    R$ {r[3]} M
                  </td>
                  <td className="num">
                    <span
                      className="chip"
                      style={{
                        background: "#e6f5ea",
                        color: "#1a8a3c",
                        height: 18,
                        fontSize: 10,
                      }}
                    >
                      {r[4]}%
                    </span>
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>

        <div className="card" style={{ padding: 18 }}>
          <h3 style={{ margin: "0 0 12px", font: "600 14px/1 Inter" }}>
            Composição do custo
          </h3>
          {[
            ["Mão de obra direta", 33.6, "#0E2A47"],
            ["Equipamentos", 24.8, "#22A94A"],
            ["Materiais", 18.2, "#d97706"],
            ["Indiretos (alim/aloj)", 9.4, "#7c8597"],
            ["Mobilização", 4.2, "#2363b8"],
            ["BDI", 9.8, "#c8302a"],
          ].map((r, i) => (
            <div key={i} style={{ marginBottom: 12 }}>
              <div style={{ display: "flex", alignItems: "baseline", gap: 8 }}>
                <span style={{ font: "500 12px/1 Inter", flex: 1 }}>
                  {r[0]}
                </span>
                <span
                  className="d-mono"
                  style={{ font: "600 12.5px/1 JetBrains Mono" }}
                >
                  {r[1]}%
                </span>
              </div>
              <div
                style={{
                  height: 5,
                  background: "var(--d-bg-2)",
                  borderRadius: 100,
                  marginTop: 5,
                }}
              >
                <div
                  style={{
                    height: "100%",
                    width: (r[1] / 40) * 100 + "%",
                    background: r[2],
                    borderRadius: 100,
                  }}
                />
              </div>
            </div>
          ))}
        </div>
      </div>
    </>
  );
}

function RelOperacional() {
  return (
    <>
      <div
        className="card"
        style={{
          display: "grid",
          gridTemplateColumns: "repeat(4, 1fr)",
          marginBottom: 16,
        }}
      >
        <DUI.Kpi label="Estacas em obra" value="2.184" sub="6 frentes ativas" />
        <DUI.Kpi
          label="Produtividade média"
          value="0,42 e/dia·equipe"
          sub="meta 0,40"
        />
        <DUI.Kpi label="Equipes alocadas" value="14" sub="74 colaboradores" />
        <DUI.Kpi
          label="Equipamentos em uso"
          value="32"
          sub="8 alugados · 24 próprios"
        />
      </div>

      <div
        style={{
          display: "grid",
          gridTemplateColumns: "1fr 1fr",
          gap: 16,
          marginBottom: 16,
        }}
      >
        <div className="card" style={{ padding: 0 }}>
          <div
            style={{
              padding: "14px 18px",
              borderBottom: "1px solid var(--d-border)",
            }}
          >
            <h3 style={{ margin: 0, font: "600 14px/1 Inter" }}>
              Produtividade por tipo de solo
            </h3>
            <div
              style={{
                font: "500 11.5px/1 Inter",
                color: "var(--d-text-3)",
                marginTop: 3,
              }}
            >
              Real (12 meses) vs orçado
            </div>
          </div>
          <table className="tbl">
            <thead>
              <tr>
                <th>Solo</th>
                <th className="num">Orçado</th>
                <th className="num">Real</th>
                <th className="num">Δ</th>
              </tr>
            </thead>
            <tbody>
              {[
                ["Argila mole", 0.85, 0.91, +7.1],
                ["Solo arenoso", 0.62, 0.58, -6.5],
                ["Solo misto", 0.45, 0.43, -4.4],
                ["Rocha alterada", 0.31, 0.28, -9.7],
                ["Rocha sã", 0.18, 0.16, -11.1],
              ].map((r, i) => (
                <tr key={i}>
                  <td style={{ fontWeight: 500 }}>{r[0]}</td>
                  <td className="num d-mono">{r[1].toFixed(2)}</td>
                  <td className="num d-mono" style={{ fontWeight: 600 }}>
                    {r[2].toFixed(2)}
                  </td>
                  <td className="num">
                    <span
                      style={{
                        color: r[3] > 0 ? "#22A94A" : "#c8302a",
                        fontWeight: 600,
                        font: "600 12px/1 JetBrains Mono",
                      }}
                    >
                      {r[3] > 0 ? "+" : ""}
                      {r[3].toFixed(1)}%
                    </span>
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>

        <div className="card" style={{ padding: 0 }}>
          <div
            style={{
              padding: "14px 18px",
              borderBottom: "1px solid var(--d-border)",
            }}
          >
            <h3 style={{ margin: 0, font: "600 14px/1 Inter" }}>
              Utilização de equipamentos
            </h3>
            <div
              style={{
                font: "500 11.5px/1 Inter",
                color: "var(--d-text-3)",
                marginTop: 3,
              }}
            >
              Equipamentos próprios · YTD
            </div>
          </div>
          <table className="tbl">
            <thead>
              <tr>
                <th>Equipamento</th>
                <th className="num">Util.</th>
                <th>Status</th>
              </tr>
            </thead>
            <tbody>
              {[
                ["Guindaste 100t #1", 92, "em uso"],
                ["Guindaste 100t #2", 78, "em uso"],
                ["Perfuratriz Wirth #1", 88, "em uso"],
                ["Perfuratriz Wirth #2", 12, "manutenção"],
                ["Martelo perc. 9-14t", 64, "em uso"],
                ["Martelo vibratório", 71, "em uso"],
              ].map((r, i) => (
                <tr key={i}>
                  <td style={{ fontWeight: 500 }}>{r[0]}</td>
                  <td className="num">
                    <div
                      style={{
                        display: "flex",
                        alignItems: "center",
                        gap: 8,
                        justifyContent: "flex-end",
                      }}
                    >
                      <div
                        style={{
                          width: 50,
                          height: 4,
                          background: "var(--d-bg-2)",
                          borderRadius: 100,
                        }}
                      >
                        <div
                          style={{
                            height: "100%",
                            width: r[1] + "%",
                            background:
                              r[1] > 80
                                ? "#22A94A"
                                : r[1] > 40
                                  ? "#d97706"
                                  : "#c8302a",
                            borderRadius: 100,
                          }}
                        />
                      </div>
                      <span
                        className="d-mono"
                        style={{ font: "600 12px/1 JetBrains Mono", width: 36 }}
                      >
                        {r[1]}%
                      </span>
                    </div>
                  </td>
                  <td>
                    <span
                      className="chip"
                      style={{
                        background: r[2] === "em uso" ? "#e6f5ea" : "#fef3e6",
                        color: r[2] === "em uso" ? "#1a8a3c" : "#a46a02",
                        height: 18,
                        fontSize: 10,
                      }}
                    >
                      {r[2].toUpperCase()}
                    </span>
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      </div>

      <div className="card" style={{ padding: 0 }}>
        <div
          style={{
            padding: "14px 18px",
            borderBottom: "1px solid var(--d-border)",
          }}
        >
          <h3 style={{ margin: 0, font: "600 14px/1 Inter" }}>
            Aderência ao prazo · obras concluídas
          </h3>
        </div>
        <table className="tbl">
          <thead>
            <tr>
              <th>Obra</th>
              <th>Cliente</th>
              <th>Conclusão</th>
              <th className="num">Prazo</th>
              <th className="num">Real</th>
              <th className="num">Desvio</th>
            </tr>
          </thead>
          <tbody>
            {[
              ["Cais Pecém F1", "Porto CE", "Mar/26", 8, 8.2, +2.5],
              ["Subest. Itu", "CTEEP", "Fev/26", 4, 3.8, -5.0],
              ["Galpão Vix", "Logus", "Jan/26", 6, 7.1, +18.3],
              ["Pier Itaqui F2", "Porto MA", "Dez/25", 10, 9.5, -5.0],
              ["Ponte SP-330", "DER-SP", "Nov/25", 5, 5.3, +6.0],
            ].map((r, i) => (
              <tr key={i}>
                <td style={{ fontWeight: 500 }}>{r[0]}</td>
                <td style={{ color: "var(--d-text-2)" }}>{r[1]}</td>
                <td className="d-mono" style={{ color: "var(--d-text-2)" }}>
                  {r[2]}
                </td>
                <td className="num d-mono">{r[3]}m</td>
                <td className="num d-mono" style={{ fontWeight: 600 }}>
                  {r[4]}m
                </td>
                <td className="num">
                  <span
                    style={{
                      color:
                        r[5] <= 0
                          ? "#22A94A"
                          : Math.abs(r[5]) < 10
                            ? "#d97706"
                            : "#c8302a",
                      fontWeight: 600,
                      font: "600 12px/1 JetBrains Mono",
                    }}
                  >
                    {r[5] > 0 ? "+" : ""}
                    {r[5].toFixed(1)}%
                  </span>
                </td>
              </tr>
            ))}
          </tbody>
        </table>
      </div>
    </>
  );
}

function RelComercial({ data }) {
  return (
    <>
      <div
        className="card"
        style={{
          display: "grid",
          gridTemplateColumns: "repeat(4, 1fr)",
          marginBottom: 16,
        }}
      >
        <DUI.Kpi
          label="Taxa de conversão"
          value="42%"
          accent="#22A94A"
          sub="↑ 6 p.p."
        />
        <DUI.Kpi
          label="Tempo médio até resposta"
          value="14 dias"
          sub="meta 21 dias"
        />
        <DUI.Kpi label="Ticket médio" value="R$ 8,7 M" sub="↑ 12% vs 2025" />
        <DUI.Kpi
          label="Pipeline ponderado"
          value="R$ 18,4 M"
          sub="por probabilidade"
        />
      </div>

      <div
        style={{
          display: "grid",
          gridTemplateColumns: "1fr 1fr",
          gap: 16,
          marginBottom: 16,
        }}
      >
        <div className="card" style={{ padding: 0 }}>
          <div
            style={{
              padding: "14px 18px",
              borderBottom: "1px solid var(--d-border)",
            }}
          >
            <h3 style={{ margin: 0, font: "600 14px/1 Inter" }}>
              Funil de orçamentos
            </h3>
          </div>
          <div style={{ padding: 18 }}>
            {[
              ["Rascunho", 4, 6.4, "#7c8597"],
              ["Em revisão", 3, 41.2, "#d97706"],
              ["Enviado ao cliente", 5, 28.8, "#2363b8"],
              ["Aprovado", 8, 12.4, "#22A94A"],
              ["Perdido", 2, 5.18, "#c8302a"],
            ].map((r, i, arr) => {
              const w = (r[1] / Math.max(...arr.map((x) => x[1]))) * 100;
              return (
                <div key={i} style={{ marginBottom: 14 }}>
                  <div
                    style={{
                      display: "flex",
                      alignItems: "baseline",
                      gap: 8,
                      marginBottom: 4,
                    }}
                  >
                    <span style={{ font: "500 12.5px/1 Inter", flex: 1 }}>
                      {r[0]}
                    </span>
                    <span
                      className="d-mono"
                      style={{
                        font: "600 12px/1 JetBrains Mono",
                        color: "var(--d-text-3)",
                      }}
                    >
                      {r[1]} orçamentos
                    </span>
                    <span
                      className="d-mono"
                      style={{
                        font: "700 13px/1 JetBrains Mono",
                        color: r[3],
                        width: 80,
                        textAlign: "right",
                      }}
                    >
                      R$ {r[2].toFixed(1)} M
                    </span>
                  </div>
                  <div
                    style={{
                      height: 22,
                      background: "var(--d-bg-2)",
                      borderRadius: 4,
                      overflow: "hidden",
                    }}
                  >
                    <div
                      style={{
                        height: "100%",
                        width: w + "%",
                        background: r[3] + "30",
                        borderLeft: "3px solid " + r[3],
                      }}
                    />
                  </div>
                </div>
              );
            })}
          </div>
        </div>

        <div className="card" style={{ padding: 0 }}>
          <div
            style={{
              padding: "14px 18px",
              borderBottom: "1px solid var(--d-border)",
            }}
          >
            <h3 style={{ margin: 0, font: "600 14px/1 Inter" }}>
              Top 10 clientes
            </h3>
          </div>
          <table className="tbl">
            <thead>
              <tr>
                <th>Cliente</th>
                <th className="num">Faturado</th>
                <th className="num">Conv.</th>
              </tr>
            </thead>
            <tbody>
              {[
                ["PortoSul Logística", 24.85, "67%"],
                ["DER-SP", 14.2, "50%"],
                ["CTEEP", 8.65, "40%"],
                ["Porto Itaqui", 12.4, "60%"],
                ["Logus Empreendimentos", 1.28, "33%"],
                ["Vale S.A.", 6.8, "50%"],
              ].map((r, i) => (
                <tr key={i}>
                  <td style={{ fontWeight: 500 }}>{r[0]}</td>
                  <td className="num d-mono">R$ {r[1].toFixed(2)} M</td>
                  <td className="num">
                    <span
                      style={{
                        color:
                          parseInt(r[2]) > 50 ? "#22A94A" : "var(--d-text-2)",
                        fontWeight: 600,
                      }}
                    >
                      {r[2]}
                    </span>
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      </div>

      <div className="card" style={{ padding: 18 }}>
        <h3 style={{ margin: "0 0 14px", font: "600 14px/1 Inter" }}>
          Conversão por orçamentista
        </h3>
        <div
          style={{
            display: "grid",
            gridTemplateColumns: "repeat(3, 1fr)",
            gap: 14,
          }}
        >
          {[
            { nome: "Ana", proj: 12, conv: 58, valor: 28.4, cor: "#22A94A" },
            {
              nome: "Carlos Mendes",
              proj: 9,
              conv: 44,
              valor: 18.6,
              cor: "#0E2A47",
            },
            {
              nome: "Júlia Penna",
              proj: 7,
              conv: 28,
              valor: 9.2,
              cor: "#d97706",
            },
          ].map((p, i) => (
            <div
              key={i}
              className="card"
              style={{
                padding: 14,
                boxShadow: "none",
                borderLeft: "3px solid " + p.cor,
              }}
            >
              <div
                style={{
                  display: "flex",
                  alignItems: "center",
                  gap: 8,
                  marginBottom: 10,
                }}
              >
                <div
                  style={{
                    width: 32,
                    height: 32,
                    borderRadius: 100,
                    background: p.cor,
                    color: "white",
                    display: "flex",
                    alignItems: "center",
                    justifyContent: "center",
                    font: "600 13px/1 Inter",
                  }}
                >
                  {p.nome[0]}
                </div>
                <div style={{ font: "600 13.5px/1.2 Inter" }}>{p.nome}</div>
              </div>
              <div
                style={{
                  display: "flex",
                  justifyContent: "space-between",
                  marginBottom: 8,
                }}
              >
                <div>
                  <div
                    style={{
                      font: "500 10.5px/1 Inter",
                      color: "var(--d-text-3)",
                      textTransform: "uppercase",
                    }}
                  >
                    Orçamentos
                  </div>
                  <div
                    className="d-mono"
                    style={{ font: "700 18px/1 JetBrains Mono", marginTop: 4 }}
                  >
                    {p.proj}
                  </div>
                </div>
                <div>
                  <div
                    style={{
                      font: "500 10.5px/1 Inter",
                      color: "var(--d-text-3)",
                      textTransform: "uppercase",
                    }}
                  >
                    Conversão
                  </div>
                  <div
                    className="d-mono"
                    style={{
                      font: "700 18px/1 JetBrains Mono",
                      marginTop: 4,
                      color: p.cor,
                    }}
                  >
                    {p.conv}%
                  </div>
                </div>
                <div>
                  <div
                    style={{
                      font: "500 10.5px/1 Inter",
                      color: "var(--d-text-3)",
                      textTransform: "uppercase",
                    }}
                  >
                    Faturado
                  </div>
                  <div
                    className="d-mono"
                    style={{ font: "700 18px/1 JetBrains Mono", marginTop: 4 }}
                  >
                    R$ {p.valor}M
                  </div>
                </div>
              </div>
            </div>
          ))}
        </div>
      </div>
    </>
  );
}

function RelCustos() {
  return (
    <>
      <div
        className="card"
        style={{
          display: "grid",
          gridTemplateColumns: "repeat(4, 1fr)",
          marginBottom: 16,
        }}
      >
        <DUI.Kpi
          label="Diesel consumido"
          value="142.000 L"
          sub="↑ 8% vs 2025"
        />
        <DUI.Kpi
          label="Custo médio /estaca"
          value="R$ 24.840"
          sub="média ponderada"
        />
        <DUI.Kpi
          label="Eletrodo consumido"
          value="98.400 kg"
          sub="média 1,5 kg/m"
        />
        <DUI.Kpi
          label="HE pagas"
          value="R$ 380 k"
          accent="#d97706"
          sub="↑ 22%, investigar"
        />
      </div>

      <div className="card" style={{ padding: 0, marginBottom: 16 }}>
        <div
          style={{
            padding: "14px 18px",
            borderBottom: "1px solid var(--d-border)",
          }}
        >
          <h3 style={{ margin: 0, font: "600 14px/1 Inter" }}>
            Variação de preços de insumos · 12 meses
          </h3>
        </div>
        <table className="tbl">
          <thead>
            <tr>
              <th>Insumo</th>
              <th className="num">Mai/25</th>
              <th className="num">Mai/26</th>
              <th className="num">Variação</th>
              <th>Próximo reajuste</th>
            </tr>
          </thead>
          <tbody>
            {[
              ["Diesel S10", "5,82", "6,45", +10.8, "—"],
              ["Eletrodo E7018", "28,40", "32,50", +14.4, "+R$ 1,50 em 15/05"],
              ["Aço CA-50 Ø 12,5mm", "7,20", "8,90", +23.6, "—"],
              ["Cimento CP-V", "34,80", "38,50", +10.6, "—"],
              [
                "Aluguel Guindaste 100t",
                "88.000",
                "92.000",
                +4.5,
                "+3,3% em 01/06",
              ],
              [
                "Salário Soldador",
                "4.200",
                "4.500",
                +7.1,
                "+5% em out/26 (dissídio)",
              ],
            ].map((r, i) => (
              <tr key={i}>
                <td style={{ fontWeight: 500 }}>{r[0]}</td>
                <td className="num d-mono" style={{ color: "var(--d-text-3)" }}>
                  {r[1]}
                </td>
                <td className="num d-mono" style={{ fontWeight: 600 }}>
                  {r[2]}
                </td>
                <td className="num">
                  <span
                    style={{
                      color:
                        r[3] > 15
                          ? "#c8302a"
                          : r[3] > 10
                            ? "#d97706"
                            : "#22A94A",
                      fontWeight: 600,
                      font: "600 12px/1 JetBrains Mono",
                    }}
                  >
                    +{r[3].toFixed(1)}%
                  </span>
                </td>
                <td
                  style={{
                    font: "500 11.5px/1.4 Inter",
                    color: "var(--d-text-2)",
                  }}
                >
                  {r[4]}
                </td>
              </tr>
            ))}
          </tbody>
        </table>
      </div>

      <div className="card" style={{ padding: 18 }}>
        <h3 style={{ margin: "0 0 12px", font: "600 14px/1 Inter" }}>
          Encargos & adicionais, análise de impacto
        </h3>
        <div
          style={{
            font: "500 12.5px/1.5 Inter",
            color: "var(--d-text-2)",
            marginBottom: 14,
          }}
        >
          Em 12 meses, periculosidade representou <strong>R$ 540 k</strong> e
          horas extras <strong>R$ 380 k</strong>. Obras embarcadas pagam +30%
          peric. para todos os cargos diretos, peso significativo no custo.
        </div>
        <div
          style={{
            display: "grid",
            gridTemplateColumns: "repeat(4, 1fr)",
            gap: 12,
          }}
        >
          {[
            ["Periculosidade (30%)", "R$ 540 k", "8 obras", "#d97706"],
            ["Insalubridade (20%)", "R$ 124 k", "3 obras", "#7c8597"],
            ["Hora extra", "R$ 380 k", "↑ 22%", "#c8302a"],
            ["Dissídio acumulado", "+12,5%", "2 ciclos", "#2363b8"],
          ].map((r, i) => (
            <div
              key={i}
              style={{
                padding: 12,
                background: "var(--d-bg)",
                borderRadius: 6,
                borderLeft: "3px solid " + r[3],
              }}
            >
              <div
                style={{
                  font: "600 11px/1 Inter",
                  color: r[3],
                  textTransform: "uppercase",
                  letterSpacing: "0.05em",
                  marginBottom: 6,
                }}
              >
                {r[0]}
              </div>
              <div
                className="d-mono"
                style={{
                  font: "700 18px/1 JetBrains Mono",
                  color: "var(--d-text)",
                }}
              >
                {r[1]}
              </div>
              <div
                style={{
                  font: "500 11px/1.3 Inter",
                  color: "var(--d-text-3)",
                  marginTop: 4,
                }}
              >
                {r[2]}
              </div>
            </div>
          ))}
        </div>
      </div>
    </>
  );
}

/* ============================ RESUMO CLIENTE FINAL ============================ */
function ResumoClienteFinal({ projeto }) {
  if (!projeto) return null;
  const totalEstacas = projeto.obras.reduce((s, o) => s + o.estacas, 0);
  const totalFrentes = projeto.obras.reduce((s, o) => s + o.frentes.length, 0);

  return (
    <div style={{ maxWidth: 920, margin: "0 auto" }}>
      {/* Banner com ações */}
      <div
        className="card"
        style={{
          padding: "12px 18px",
          marginBottom: 16,
          background: "var(--d-green-soft)",
          display: "flex",
          alignItems: "center",
          gap: 12,
        }}
      >
        <DUI.Icon name="eye" size={16} style={{ color: "#1a8a3c" }} />
        <div
          style={{ flex: 1, font: "500 12.5px/1.4 Inter", color: "#1a8a3c" }}
        >
          <strong>Pré-visualização da proposta</strong>, assim o cliente vê.
          Ações disponíveis: gerar PDF, enviar por email, ou criar link
          compartilhável.
        </div>
        <button className="btn btn-sm">
          <DUI.Icon name="share" size={12} />
          Link compartilhável
        </button>
        <button className="btn btn-sm">
          <DUI.Icon name="download" size={12} />
          PDF
        </button>
        <button className="btn btn-sm btn-primary">
          <DUI.Icon name="share" size={12} />
          Enviar ao cliente
        </button>
      </div>

      {/* Documento */}
      <div className="card" style={{ padding: 0, overflow: "hidden" }}>
        {/* Cabeçalho da proposta */}
        <div
          style={{
            padding: "34px 40px 26px",
            background: "linear-gradient(135deg, #0E2A47 0%, #16395f 100%)",
            color: "white",
            position: "relative",
            overflow: "hidden",
          }}
        >
          <div
            style={{
              position: "absolute",
              bottom: -60,
              right: -30,
              width: 220,
              height: 220,
              borderRadius: "50%",
              background: "rgba(34,169,74,0.15)",
            }}
          />
          <div style={{ position: "relative" }}>
            <div
              style={{
                display: "flex",
                alignItems: "flex-start",
                justifyContent: "space-between",
                marginBottom: 28,
              }}
            >
              <DUI.Logo invert />
              <div style={{ textAlign: "right" }}>
                <div
                  className="d-mono"
                  style={{
                    font: "500 11px/1 JetBrains Mono",
                    color: "rgba(255,255,255,0.65)",
                    letterSpacing: "0.06em",
                  }}
                >
                  PROPOSTA COMERCIAL
                </div>
                <div
                  className="d-mono"
                  style={{ font: "700 18px/1 JetBrains Mono", marginTop: 6 }}
                >
                  {projeto.id}
                </div>
              </div>
            </div>
            <div
              style={{
                font: "500 12px/1 Inter",
                color: "rgba(255,255,255,0.65)",
                textTransform: "uppercase",
                letterSpacing: "0.08em",
              }}
            >
              Cliente
            </div>
            <div style={{ font: "600 16px/1.2 Inter", marginTop: 4 }}>
              {projeto.cliente}
            </div>
            <h1
              style={{
                margin: "20px 0 0",
                font: "700 28px/1.15 Inter",
                letterSpacing: "-0.01em",
              }}
            >
              {projeto.nome}
            </h1>
            <div
              style={{
                display: "flex",
                gap: 24,
                marginTop: 16,
                font: "500 12.5px/1 Inter",
                color: "rgba(255,255,255,0.85)",
              }}
            >
              <span>
                <DUI.Icon name="pin" size={12} /> {projeto.local}
              </span>
              <span>
                <DUI.Icon name="clock" size={12} /> Validade: 60 dias
              </span>
              <span>
                <DUI.Icon name="user" size={12} /> Responsável: Ana
              </span>
            </div>
          </div>
        </div>

        {/* Sumário executivo */}
        <div
          style={{
            padding: "32px 40px",
            borderBottom: "1px solid var(--d-border)",
          }}
        >
          <SectionTitle>1. Sumário executivo</SectionTitle>
          <div
            style={{
              font: "500 14px/1.65 Inter",
              color: "var(--d-text-2)",
              marginBottom: 22,
            }}
          >
            A Destaca Engenharia apresenta sua proposta para a execução de
            fundações em estacas para o projeto
            <strong style={{ color: "var(--d-text)" }}> {projeto.nome}</strong>,
            contemplando {projeto.obras.length} obra(s) e {totalFrentes}{" "}
            frente(s) de trabalho, totalizando{" "}
            <strong style={{ color: "var(--d-text)" }}>
              {fmtSF(totalEstacas)} estacas
            </strong>
            . Prazo total estimado de{" "}
            <strong style={{ color: "var(--d-text)" }}>9 meses</strong>,
            incluindo mobilização, execução e desmobilização.
          </div>
          <div
            style={{
              display: "grid",
              gridTemplateColumns: "repeat(4, 1fr)",
              gap: 14,
            }}
          >
            <SumItem
              label="Valor total"
              v={brlSFk(projeto.valor)}
              accent="#22A94A"
            />
            <SumItem
              label="Estacas"
              v={fmtSF(totalEstacas)}
              sub={totalFrentes + " frentes"}
            />
            <SumItem label="Prazo" v="9 meses" sub="ago/26 → mai/27" />
            <SumItem
              label="R$ / estaca"
              v={brlSFk(projeto.valor / totalEstacas)}
            />
          </div>
        </div>

        {/* Escopo */}
        <div
          style={{
            padding: "32px 40px",
            borderBottom: "1px solid var(--d-border)",
          }}
        >
          <SectionTitle>2. Escopo de execução</SectionTitle>
          {projeto.obras.map((o, i) => {
            const valorObra =
              projeto.valor * (o.estacas / Math.max(totalEstacas, 1));
            return (
              <div key={o.id} style={{ marginBottom: 22 }}>
                <div
                  style={{
                    display: "flex",
                    alignItems: "baseline",
                    gap: 10,
                    paddingBottom: 8,
                    borderBottom: "1px solid var(--d-border)",
                  }}
                >
                  <div
                    className="d-mono"
                    style={{
                      font: "500 11px/1 JetBrains Mono",
                      color: "var(--d-text-3)",
                    }}
                  >
                    OBRA {String(i + 1).padStart(2, "0")}
                  </div>
                  <div style={{ font: "600 16px/1.2 Inter", flex: 1 }}>
                    {o.nome}
                  </div>
                  <div
                    className="d-mono"
                    style={{
                      font: "700 15px/1 JetBrains Mono",
                      color: "#22A94A",
                    }}
                  >
                    {brlSFk(valorObra)}
                  </div>
                </div>
                <div style={{ padding: "12px 0" }}>
                  {o.frentes.length === 0 && (
                    <div
                      style={{
                        font: "500 12.5px/1.4 Inter",
                        color: "var(--d-text-3)",
                        fontStyle: "italic",
                      }}
                    >
                      Detalhamento das frentes a definir
                    </div>
                  )}
                  {o.frentes.map((f, fi) => (
                    <div
                      key={f.id}
                      style={{
                        display: "flex",
                        alignItems: "center",
                        gap: 12,
                        padding: "10px 0",
                        borderTop:
                          fi > 0 ? "1px solid var(--d-border)" : "none",
                      }}
                    >
                      <div style={{ flex: 1 }}>
                        <div style={{ font: "600 13px/1.3 Inter" }}>
                          {f.nome}
                        </div>
                        <div
                          style={{
                            font: "500 11.5px/1.3 Inter",
                            color: "var(--d-text-3)",
                            marginTop: 2,
                          }}
                        >
                          {f.tipoEstaca} · profundidade {f.comprimento}m ·{" "}
                          {f.equipes} equipe{f.equipes > 1 ? "s" : ""}{" "}
                          simultânea{f.equipes > 1 ? "s" : ""}
                        </div>
                      </div>
                      <div
                        className="d-mono"
                        style={{
                          font: "600 13px/1 JetBrains Mono",
                          textAlign: "right",
                        }}
                      >
                        {fmtSF(f.estacas)}
                        <div
                          style={{
                            font: "500 10px/1 Inter",
                            color: "var(--d-text-3)",
                            marginTop: 3,
                          }}
                        >
                          estacas
                        </div>
                      </div>
                      <div
                        className="d-mono"
                        style={{
                          font: "600 13px/1 JetBrains Mono",
                          textAlign: "right",
                        }}
                      >
                        {f.mesesEstim}m
                        <div
                          style={{
                            font: "500 10px/1 Inter",
                            color: "var(--d-text-3)",
                            marginTop: 3,
                          }}
                        >
                          prazo
                        </div>
                      </div>
                    </div>
                  ))}
                </div>
              </div>
            );
          })}
        </div>

        {/* Cronograma */}
        <div
          style={{
            padding: "32px 40px",
            borderBottom: "1px solid var(--d-border)",
          }}
        >
          <SectionTitle>3. Cronograma macro</SectionTitle>
          <div
            style={{
              display: "flex",
              borderTop: "1px solid var(--d-border)",
              borderBottom: "1px solid var(--d-border)",
            }}
          >
            {[
              "Ago/26",
              "Set/26",
              "Out/26",
              "Nov/26",
              "Dez/26",
              "Jan/27",
              "Fev/27",
              "Mar/27",
              "Abr/27",
              "Mai/27",
            ].map((m, i) => (
              <div
                key={i}
                style={{
                  flex: 1,
                  padding: "10px 0",
                  textAlign: "center",
                  font: "500 10.5px/1 JetBrains Mono",
                  color: "var(--d-text-2)",
                  borderLeft: i > 0 ? "1px solid var(--d-border)" : "none",
                }}
              >
                {m}
              </div>
            ))}
          </div>
          {[
            { label: "Mobilização", start: 0, end: 1.5, cor: "#d97706" },
            {
              label: "Cravação Cais Norte",
              start: 1.5,
              end: 7.5,
              cor: "#22A94A",
            },
            {
              label: "Cravação Cais Sul",
              start: 1.5,
              end: 5.5,
              cor: "#1a8a3c",
            },
            {
              label: "Atracadouro PR-3 (frente deslocada)",
              start: 5.5,
              end: 8.5,
              cor: "#0E2A47",
            },
            { label: "Desmobilização", start: 8.5, end: 10, cor: "#7c8597" },
          ].map((b, i) => (
            <div
              key={i}
              style={{
                display: "flex",
                alignItems: "center",
                height: 32,
                borderBottom: "1px solid var(--d-border)",
              }}
            >
              <div
                style={{
                  width: 240,
                  padding: "0 12px",
                  font: "500 12.5px/1 Inter",
                  color: "var(--d-text-2)",
                }}
              >
                {b.label}
              </div>
              <div style={{ flex: 1, position: "relative", height: "100%" }}>
                <div
                  style={{
                    position: "absolute",
                    top: 8,
                    height: 16,
                    left: (b.start / 10) * 100 + "%",
                    width: ((b.end - b.start) / 10) * 100 + "%",
                    background: b.cor,
                    borderRadius: 100,
                  }}
                />
              </div>
            </div>
          ))}
        </div>

        {/* Investimento */}
        <div
          style={{
            padding: "32px 40px",
            borderBottom: "1px solid var(--d-border)",
          }}
        >
          <SectionTitle>4. Investimento</SectionTitle>
          {(() => {
            // Coleta heranças de todas frentes do projeto p/ exibir como desconto
            const herancas = projeto.obras.flatMap((o) =>
              o.frentes.filter((f) => f.heranca),
            );
            const totalDesconto = herancas.reduce(
              (s, f) => s + (f.heranca?.custoEvitado || 0),
              0,
            );
            const subtotal = projeto.valor + totalDesconto;
            return (
              <table style={{ width: "100%", borderCollapse: "collapse" }}>
                <tbody>
                  {projeto.obras.map((o, i) => {
                    const valorObra =
                      subtotal * (o.estacas / Math.max(totalEstacas, 1));
                    return (
                      <tr
                        key={o.id}
                        style={{ borderBottom: "1px solid var(--d-border)" }}
                      >
                        <td
                          style={{
                            padding: "14px 0",
                            font: "500 13px/1.3 Inter",
                          }}
                        >
                          {o.nome}
                          <div
                            style={{
                              font: "500 11.5px/1 Inter",
                              color: "var(--d-text-3)",
                              marginTop: 3,
                            }}
                          >
                            {fmtSF(o.estacas)} estacas
                          </div>
                        </td>
                        <td
                          className="num"
                          style={{
                            padding: "14px 0",
                            font: "600 14px/1 JetBrains Mono",
                          }}
                        >
                          {brlSF(valorObra)}
                        </td>
                      </tr>
                    );
                  })}
                  {totalDesconto > 0 && (
                    <>
                      <tr style={{ borderBottom: "1px solid var(--d-border)" }}>
                        <td
                          style={{
                            padding: "14px 0",
                            font: "500 13px/1.3 Inter",
                            color: "var(--d-text-2)",
                          }}
                        >
                          Subtotal (mobilizações independentes)
                        </td>
                        <td
                          className="num"
                          style={{
                            padding: "14px 0",
                            font: "500 13px/1 JetBrains Mono",
                            color: "var(--d-text-2)",
                          }}
                        >
                          {brlSF(subtotal)}
                        </td>
                      </tr>
                      {herancas.map((f) => (
                        <tr
                          key={f.id}
                          style={{
                            borderBottom: "1px solid var(--d-border)",
                            background: "var(--d-green-soft)",
                          }}
                        >
                          <td
                            style={{
                              padding: "12px 12px",
                              font: "500 13px/1.3 Inter",
                              color: "#1a8a3c",
                            }}
                          >
                            <strong>
                              Desconto por compartilhamento de recursos
                            </strong>
                            <div
                              style={{
                                font: "500 11.5px/1.4 Inter",
                                color: "var(--d-text-2)",
                                marginTop: 3,
                              }}
                            >
                              {f.nome} reaproveita equipe e equipamentos da{" "}
                              {f.heranca.deFrenteNome} ({f.heranca.deObraNome})
                              a partir do mês {f.heranca.mesInicio}, evitando
                              dupla mobilização.
                            </div>
                          </td>
                          <td
                            className="num"
                            style={{
                              padding: "12px 12px",
                              font: "700 14px/1 JetBrains Mono",
                              color: "#1a8a3c",
                            }}
                          >
                            − {brlSF(f.heranca.custoEvitado)}
                          </td>
                        </tr>
                      ))}
                    </>
                  )}
                  <tr style={{ background: "#0E2A47", color: "white" }}>
                    <td
                      style={{ padding: "18px 14px", font: "700 14px/1 Inter" }}
                    >
                      VALOR TOTAL
                    </td>
                    <td
                      className="num"
                      style={{
                        padding: "18px 14px",
                        font: "800 22px/1 JetBrains Mono",
                        color: "#22A94A",
                      }}
                    >
                      {brlSF(projeto.valor)}
                    </td>
                  </tr>
                </tbody>
              </table>
            );
          })()}
          <div
            style={{
              marginTop: 16,
              padding: 14,
              background: "var(--d-bg)",
              borderRadius: 6,
              font: "500 12.5px/1.6 Inter",
              color: "var(--d-text-2)",
            }}
          >
            <strong>Condições de pagamento:</strong> 20% mobilização + 70%
            medições mensais + 10% entrega final.
            <br />
            <strong>Reajuste:</strong> conforme dissídio anual da categoria
            (outubro), aplicado proporcionalmente aos meses restantes.
            <br />
            <strong>Responsabilidade do cliente:</strong> sondagem, projeto
            executivo, fornecimento de água/energia no canteiro.
            <br />
            <strong>Compartilhamento de recursos:</strong> o desconto exibido é
            vinculado à execução completa das frentes que cedem recursos.
            Cancelamento ou redução parcial dessas frentes implica revisão do
            valor de venda das frentes que delas dependem.
          </div>
        </div>

        {/* O que está incluso */}
        <div style={{ padding: "32px 40px" }}>
          <SectionTitle>5. O que está incluso</SectionTitle>
          <div
            style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 12 }}
          >
            {[
              [
                "Equipe completa de execução",
                "Mestre de obra, encarregados, operadores, soldadores, ajudantes",
              ],
              [
                "Equipamentos especializados",
                "Guindaste 100t, perfuratriz, martelo vibratório, máquinas de solda",
              ],
              ["Materiais de soldagem", "Eletrodos, gases, EPIs específicos"],
              [
                "Mobilização e desmobilização",
                "Transporte de equipamentos ida e volta",
              ],
              [
                "Alimentação e alojamento",
                "Café, almoço, jantar e casas para equipe",
              ],
              [
                "Acompanhamento técnico",
                "Engenheiro de produção, técnico de segurança",
              ],
              ["Seguros e ART", "Cobertura para equipamentos e pessoal"],
              ["Relatório técnico de cravação", "Por estaca, conforme NBR"],
            ].map((it, i) => (
              <div
                key={i}
                style={{
                  display: "flex",
                  gap: 8,
                  padding: 10,
                  background: "var(--d-bg)",
                  borderRadius: 6,
                }}
              >
                <DUI.Icon
                  name="check"
                  size={14}
                  style={{ color: "#22A94A", marginTop: 2, flex: "none" }}
                />
                <div>
                  <div style={{ font: "600 12.5px/1.3 Inter" }}>{it[0]}</div>
                  <div
                    style={{
                      font: "500 11.5px/1.4 Inter",
                      color: "var(--d-text-3)",
                      marginTop: 2,
                    }}
                  >
                    {it[1]}
                  </div>
                </div>
              </div>
            ))}
          </div>
        </div>

        {/* Footer */}
        <div
          style={{
            padding: "24px 40px",
            background: "var(--d-bg)",
            display: "flex",
            alignItems: "center",
            gap: 14,
          }}
        >
          <DUI.Logo small />
          <div
            style={{
              flex: 1,
              font: "500 11.5px/1.5 Inter",
              color: "var(--d-text-3)",
            }}
          >
            <div style={{ fontWeight: 600, color: "var(--d-text-2)" }}>
              Destaca Engenharia de Fundações Ltda.
            </div>
            CNPJ 00.000.000/0001-00 · Sertãozinho/SP · contato@destaca.com.br ·
            (16) 0000-0000
          </div>
          <div
            style={{
              font: "500 11px/1 Inter",
              color: "var(--d-text-3)",
              textAlign: "right",
            }}
          >
            Documento gerado em
            <br />
            <strong className="d-mono" style={{ color: "var(--d-text-2)" }}>
              06/05/2026 14:32
            </strong>
          </div>
        </div>
      </div>
    </div>
  );
}
function SectionTitle({ children }) {
  return (
    <div
      style={{
        display: "flex",
        alignItems: "baseline",
        gap: 12,
        marginBottom: 18,
      }}
    >
      <h2
        style={{
          margin: 0,
          font: "700 18px/1 Inter",
          letterSpacing: "-0.01em",
        }}
      >
        {children}
      </h2>
      <div style={{ flex: 1, height: 1, background: "var(--d-border)" }} />
    </div>
  );
}
function SumItem({ label, v, sub, accent }) {
  return (
    <div style={{ padding: 12, background: "var(--d-bg)", borderRadius: 6 }}>
      <div
        style={{
          font: "600 10.5px/1 Inter",
          color: "var(--d-text-3)",
          textTransform: "uppercase",
          letterSpacing: "0.06em",
        }}
      >
        {label}
      </div>
      <div
        className="d-mono"
        style={{
          font: "700 18px/1 JetBrains Mono",
          color: accent || "var(--d-text)",
          marginTop: 8,
        }}
      >
        {v}
      </div>
      {sub && (
        <div
          style={{
            font: "500 11px/1.3 Inter",
            color: "var(--d-text-3)",
            marginTop: 4,
          }}
        >
          {sub}
        </div>
      )}
    </div>
  );
}

/* ============================ DETALHE PROJETO ============================ */
function DetalheProjetoV3({ projeto, navTo, forceRefresh }) {
  if (!projeto) return null;
  const totalEstacas = projeto.obras.reduce((s, o) => s + o.estacas, 0);
  const totalFrentes = projeto.obras.reduce((s, o) => s + o.frentes.length, 0);
  const valorPorEstaca = projeto.valor / Math.max(totalEstacas, 1);

  // Mapa: frenteId -> [frentes que herdam dela] (lado "cede")
  const cedidaPara = {};
  projeto.obras.forEach((o) =>
    o.frentes.forEach((f) => {
      if (f.heranca?.deFrenteId) {
        (cedidaPara[f.heranca.deFrenteId] ||= []).push({
          id: f.id,
          nome: f.nome,
          custoEvitado: f.heranca.custoEvitado,
          mesInicio: f.heranca.mesInicio,
        });
      }
    }),
  );

  return (
    <div style={{ maxWidth: 1280, position: "relative" }}>
      <div
        style={{
          display: "flex",
          alignItems: "flex-start",
          marginBottom: 18,
          gap: 12,
        }}
      >
        <div style={{ flex: 1 }}>
          <div
            style={{
              display: "flex",
              alignItems: "center",
              gap: 10,
              marginBottom: 6,
            }}
          >
            <span
              className="d-mono"
              style={{ color: "var(--d-text-3)", fontSize: 12 }}
            >
              {projeto.id}
            </span>
            <DUI.StatusPill status={projeto.status} />
          </div>
          <h1
            style={{
              margin: 0,
              font: "700 24px/1.15 Inter",
              letterSpacing: "-0.01em",
            }}
          >
            {projeto.nome}
          </h1>
          <div
            style={{
              display: "flex",
              gap: 18,
              marginTop: 8,
              font: "500 13px/1 Inter",
              color: "var(--d-text-2)",
            }}
          >
            <span>
              <DUI.Icon name="user" size={13} /> {projeto.cliente}
            </span>
            <span>
              <DUI.Icon name="pin" size={13} /> {projeto.local}
            </span>
            <span>
              <DUI.Icon name="clock" size={13} /> Atualizado{" "}
              {dataRelativa(projeto.atualizado)}
            </span>
          </div>
        </div>
        <DUI.MockArea inline>
          <button
            className="btn"
            disabled
            style={{
              cursor: "not-allowed",
              background: "transparent",
              border: "none",
            }}
          >
            <DUI.Icon name="excel" size={14} />
            Exportar planilha
          </button>
        </DUI.MockArea>
        <DUI.MockArea inline>
          <button
            className="btn"
            disabled
            style={{
              cursor: "not-allowed",
              background: "transparent",
              border: "none",
            }}
          >
            <DUI.Icon name="download" size={14} />
            PDF
          </button>
        </DUI.MockArea>
        <button className="btn btn-navy" onClick={() => navTo("resumo")}>
          <DUI.Icon name="eye" size={14} />
          Visão do cliente
        </button>
      </div>

      <div
        className="card"
        style={{
          display: "grid",
          gridTemplateColumns: "repeat(5, 1fr)",
          marginBottom: 22,
        }}
      >
        <DUI.Kpi
          label="Valor total"
          value={"R$ " + (projeto.valor / 1_000_000).toFixed(2) + " M"}
          accent="#22A94A"
        />
        <DUI.Kpi
          label="Estacas"
          value={fmtSF(totalEstacas)}
          sub={totalFrentes + " frentes"}
        />
        <DUI.Kpi label="Obras" value={projeto.obras.length} />
        <DUI.Kpi label="R$ / estaca" value={brlSF(valorPorEstaca)} />
        <DUI.Kpi
          label={
            <>
              <DUI.Term>BDI</DUI.Term> aplicado
            </>
          }
          value="29,1%"
          sub="lucro 12% + impostos 8,7%"
        />
      </div>

      <div style={{ display: "flex", alignItems: "center", marginBottom: 12 }}>
        <h2 style={{ margin: 0, font: "600 16px/1 Inter" }}>Obras</h2>
        <div
          style={{
            font: "500 12px/1 Inter",
            color: "var(--d-text-3)",
            marginLeft: 10,
          }}
        >
          · {projeto.obras.length}
        </div>
        <button className="btn btn-sm" style={{ marginLeft: "auto" }}>
          <DUI.Icon name="plus" size={12} />
          Nova obra
        </button>
      </div>

      <div style={{ display: "flex", flexDirection: "column", gap: 12 }}>
        {projeto.obras.map((o, i) => {
          const valorObra =
            projeto.valor * (o.estacas / Math.max(totalEstacas, 1));
          return (
            <div
              key={o.id}
              className="card"
              style={{ padding: 0, overflow: "hidden" }}
            >
              <div
                style={{
                  padding: "14px 18px",
                  display: "flex",
                  alignItems: "center",
                  gap: 12,
                  background: "var(--d-bg)",
                  borderBottom: "1px solid var(--d-border)",
                }}
              >
                <div
                  style={{
                    width: 32,
                    height: 32,
                    borderRadius: 6,
                    background: "rgba(14,42,71,0.08)",
                    color: "var(--d-navy)",
                    display: "flex",
                    alignItems: "center",
                    justifyContent: "center",
                  }}
                >
                  <DUI.Icon name="layers" size={16} />
                </div>
                <div style={{ flex: 1 }}>
                  <div
                    className="d-mono"
                    style={{ color: "var(--d-text-3)", fontSize: 11.5 }}
                  >
                    OBRA {String(i + 1).padStart(2, "0")}
                  </div>
                  <h3 style={{ margin: "2px 0 0", font: "600 15px/1.2 Inter" }}>
                    {o.nome}
                  </h3>
                </div>
                <div style={{ display: "flex", gap: 22, alignItems: "center" }}>
                  <div style={{ textAlign: "right" }}>
                    <div
                      style={{
                        font: "600 10.5px/1 Inter",
                        color: "var(--d-text-3)",
                        textTransform: "uppercase",
                        letterSpacing: "0.06em",
                      }}
                    >
                      Estacas
                    </div>
                    <div
                      className="d-mono"
                      style={{
                        font: "700 16px/1 JetBrains Mono",
                        marginTop: 4,
                      }}
                    >
                      {fmtSF(o.estacas)}
                    </div>
                  </div>
                  <div style={{ textAlign: "right" }}>
                    <div
                      style={{
                        font: "600 10.5px/1 Inter",
                        color: "var(--d-text-3)",
                        textTransform: "uppercase",
                        letterSpacing: "0.06em",
                      }}
                    >
                      Frentes
                    </div>
                    <div
                      className="d-mono"
                      style={{
                        font: "700 16px/1 JetBrains Mono",
                        marginTop: 4,
                      }}
                    >
                      {o.frentes.length}
                    </div>
                  </div>
                  <div style={{ textAlign: "right" }}>
                    <div
                      style={{
                        font: "600 10.5px/1 Inter",
                        color: "var(--d-text-3)",
                        textTransform: "uppercase",
                        letterSpacing: "0.06em",
                      }}
                    >
                      Valor
                    </div>
                    <div
                      className="d-mono"
                      style={{
                        font: "700 16px/1 JetBrains Mono",
                        marginTop: 4,
                        color: "#22A94A",
                      }}
                    >
                      {"R$ " + (valorObra / 1_000_000).toFixed(2) + " M"}
                    </div>
                  </div>
                  <button
                    className="btn btn-sm"
                    onClick={() => navTo("obra", { obra: o.id })}
                  >
                    Abrir
                    <DUI.Icon name="chevR" size={12} />
                  </button>
                </div>
              </div>
              <div>
                {o.frentes.map((f, fi) => {
                  const est = window.DESTACA_CALC.estimarFrente(f);
                  const solo = window.DESTACA_DATA.solos.find(
                    (s) => s.id === f.soloId,
                  );
                  return (
                    <div
                      key={f.id}
                      style={{
                        padding: "12px 18px",
                        borderTop:
                          fi > 0 ? "1px solid var(--d-border)" : "none",
                        display: "flex",
                        alignItems: "center",
                        gap: 14,
                        cursor: "pointer",
                      }}
                      onClick={() =>
                        navTo("frente", { obra: o.id, frente: f.id })
                      }
                    >
                      <div
                        style={{
                          width: 24,
                          height: 24,
                          borderRadius: 6,
                          background: "rgba(34,169,74,0.12)",
                          color: "#1a8a3c",
                          display: "flex",
                          alignItems: "center",
                          justifyContent: "center",
                          flex: "none",
                        }}
                      >
                        <DUI.Icon name="pile" size={13} />
                      </div>
                      <div style={{ flex: 1, minWidth: 0 }}>
                        <div style={{ font: "600 13.5px/1.2 Inter" }}>
                          {f.nome}
                        </div>
                        <div
                          style={{
                            font: "500 12px/1.3 Inter",
                            color: "var(--d-text-3)",
                            marginTop: 3,
                          }}
                        >
                          {f.tipoEstaca} · {f.comprimento}m · solo{" "}
                          {solo?.nome.toLowerCase()} · {f.equipes} equipe
                          {f.equipes > 1 ? "s" : ""}
                        </div>
                      </div>
                      <span className="chip chip-navy">
                        {f.modo === "performance" ? (
                          <DUI.Term>Performance</DUI.Term>
                        ) : (
                          <DUI.Term>Prazo</DUI.Term>
                        )}
                      </span>
                      {cedidaPara[f.id] &&
                        cedidaPara[f.id].map((dest) => (
                          <span
                            key={dest.id}
                            className="chip"
                            onClick={(e) => {
                              e.stopPropagation();
                              navTo("frente", { obra: o.id, frente: dest.id });
                            }}
                            title={`Cede recursos para ${dest.nome} a partir do mês ${dest.mesInicio} · economia compartilhada`}
                            style={{
                              background: "var(--d-green-soft)",
                              color: "#1a8a3c",
                              cursor: "pointer",
                              textTransform: "none",
                              letterSpacing: 0,
                              fontSize: 10.5,
                              display: "inline-flex",
                              alignItems: "center",
                              gap: 4,
                            }}
                          >
                            <DUI.Icon name="share" size={10} />↪ cede para{" "}
                            {dest.id} (mês {dest.mesInicio})
                          </span>
                        ))}
                      {f.heranca && (
                        <span
                          className="chip"
                          onClick={(e) => {
                            e.stopPropagation();
                            navTo("frente", { obra: o.id, frente: f.id });
                          }}
                          title={`Herda recursos de ${f.heranca.deFrenteNome} · risco financeiro projetado em caso de cancelamento`}
                          style={{
                            background: "var(--d-warn-bg)",
                            color: "var(--d-warn)",
                            cursor: "pointer",
                            textTransform: "none",
                            letterSpacing: 0,
                            fontSize: 10.5,
                            display: "inline-flex",
                            alignItems: "center",
                            gap: 4,
                          }}
                        >
                          <DUI.Icon name="bell" size={10} />↰ herda de{" "}
                          {f.heranca.deFrenteId} · −R${" "}
                          {(f.heranca.custoEvitado / 1000).toLocaleString(
                            "pt-BR",
                          )}
                          k
                        </span>
                      )}
                      <div
                        className="d-mono"
                        style={{
                          width: 80,
                          textAlign: "right",
                          font: "600 13px/1 JetBrains Mono",
                        }}
                      >
                        {fmtSF(f.estacas)}
                        <div
                          style={{
                            font: "500 10px/1 Inter",
                            color: "var(--d-text-3)",
                            marginTop: 3,
                          }}
                        >
                          estacas
                        </div>
                      </div>
                      <div
                        className="d-mono"
                        style={{
                          width: 90,
                          textAlign: "right",
                          font: "600 13px/1 JetBrains Mono",
                        }}
                      >
                        {est.mesesNecessarios.toFixed(1)}
                        <div
                          style={{
                            font: "500 10px/1 Inter",
                            color: "var(--d-text-3)",
                            marginTop: 3,
                          }}
                        >
                          meses
                        </div>
                      </div>
                      <div
                        className="d-mono"
                        style={{
                          width: 110,
                          textAlign: "right",
                          font: "700 14px/1 JetBrains Mono",
                          color: "#0E2A47",
                        }}
                      >
                        {brlSF(est.total)}
                      </div>
                      <DUI.Icon
                        name="chevR"
                        size={14}
                        style={{ color: "var(--d-text-4)" }}
                      />
                    </div>
                  );
                })}
                {o.frentes.length === 0 && (
                  <div
                    style={{
                      padding: 24,
                      textAlign: "center",
                      color: "var(--d-text-3)",
                    }}
                  >
                    Sem frentes.{" "}
                    <button
                      className="btn btn-sm btn-primary"
                      style={{ marginLeft: 8 }}
                    >
                      <DUI.Icon name="plus" size={12} />
                      Criar frente
                    </button>
                  </div>
                )}
              </div>
            </div>
          );
        })}
      </div>
    </div>
  );
}

// Wrapper p/ adicionar callout na tela Margem
function MargemFrenteCallout({ children }) {
  return (
    <div style={{ position: "relative" }}>
      <DUI.Callout num="④" anchor="right" top={120} right={-8} width={220}>
        <strong>Margem por frente</strong>, não só do projeto. Identifica qual
        frente "sangra" antes do cliente fechar.
      </DUI.Callout>
      {children}
    </div>
  );
}

window.SistemaFinalApp = SistemaFinalApp;
