// pages/mobile/MobileDocumentos.jsx — design mobile-first com aba Equipe e seguranca

function MobileDocumentos() {
  const [tab, setTab] = React.useState("obra");
  const equipeSummary = window.EQUIPE_SUMMARY || null;
  const docsEmpresa = window.DOCS_EMPRESA || [];
  const totalEmpresa = docsEmpresa.reduce((a, p) => a + (p.totalItens || 0), 0);

  return (
    <>
      <h1 className="m-title">Documentos</h1>
      <div className="m-subtitle">
        Contratos, projetos e seguranca
        {equipeSummary && equipeSummary.totalAtivos > 0
          ? ` · ${equipeSummary.totalAtivos} ${equipeSummary.totalAtivos === 1 ? "trabalhador" : "trabalhadores"}`
          : ""}
      </div>

      {/* Tabs em pill-segmented horizontal scrollavel se nao caber */}
      <div style={{
        display: "flex", gap: 4, padding: 4,
        background: "var(--bg-muted, #F5F5F5)",
        border: "1px solid var(--border)",
        borderRadius: 999,
        marginBottom: 14,
        overflowX: "auto",
        WebkitOverflowScrolling: "touch",
      }}>
        <SegBtn active={tab === "obra"} onClick={() => setTab("obra")}>
          Obra <span className="mono" style={{ opacity: 0.6, marginLeft: 4 }}>{DOCS_OBRA.length}</span>
        </SegBtn>
        <SegBtn active={tab === "empresa"} onClick={() => setTab("empresa")}>
          Empresa <span className="mono" style={{ opacity: 0.6, marginLeft: 4 }}>{totalEmpresa}</span>
        </SegBtn>
        <SegBtn active={tab === "equipe"} onClick={() => setTab("equipe")}>
          Entregas <span className="mono" style={{ opacity: 0.6, marginLeft: 4 }}>{DOCS_EQUIPE.length}</span>
        </SegBtn>
        <SegBtn active={tab === "seguranca"} onClick={() => setTab("seguranca")}>
          Equipe <span className="mono" style={{ opacity: 0.6, marginLeft: 4 }}>{equipeSummary?.totalAtivos || 0}</span>
        </SegBtn>
      </div>

      {tab === "seguranca" ? (
        <MobileSegurancaPanel summary={equipeSummary} />
      ) : tab === "empresa" ? (
        <MobileEmpresaPanel pastas={docsEmpresa} />
      ) : tab === "obra" ? (
        <DocumentList docs={DOCS_OBRA} />
      ) : (
        <DocumentList docs={DOCS_EQUIPE} />
      )}
    </>
  );
}

function SegBtn({ active, onClick, children }) {
  return (
    <button
      onClick={onClick}
      style={{
        flex: 1,
        height: 34,
        background: active ? "#fff" : "transparent",
        border: active ? "1px solid var(--border)" : "1px solid transparent",
        borderRadius: 999,
        fontSize: 12,
        fontWeight: active ? 600 : 500,
        color: active ? "var(--fg)" : "var(--fg-3)",
        cursor: "pointer",
        boxShadow: active ? "0 1px 3px rgba(0,0,0,0.04)" : "none",
        transition: "background 120ms ease, color 120ms ease",
        display: "inline-flex",
        alignItems: "center",
        justifyContent: "center",
        padding: "0 10px",
        whiteSpace: "nowrap",
      }}
    >
      {children}
    </button>
  );
}

function DocumentList({ docs }) {
  const grouped = docs.reduce((acc, d) => {
    (acc[d.category] = acc[d.category] || []).push(d);
    return acc;
  }, {});

  if (docs.length === 0) {
    return (
      <div className="m-card" style={{ padding: 24, textAlign: "center", color: "var(--fg-4)", fontSize: 13 }}>
        Sem documentos nesta aba.
      </div>
    );
  }

  return (
    <>
      {Object.entries(grouped).map(([cat, items]) => (
        <div key={cat} style={{ marginBottom: 14 }}>
          <div className="m-section-label" style={{ margin: "4px 4px 8px" }}>{cat}</div>
          <div className="m-card">
            {items.map((d) => (
              <div key={`${d.kind}-${d.id}`} className="m-file-row">
                <div className="m-file-ico">{d.type}</div>
                <div className="m-file-body">
                  <div className="m-file-name">{d.name}</div>
                  <div className="m-file-meta">{d.size} · {fmtDate(d.date)}</div>
                </div>
                <a
                  className="m-header-action"
                  href={`/portal-cliente/api/documentos/${d.kind}/${d.id}/file`}
                  target="_blank"
                  rel="noopener noreferrer"
                  style={{ display: "inline-flex", textDecoration: "none", color: "inherit" }}
                  aria-label="Abrir"
                >
                  <I.Eye size={15} />
                </a>
                <a
                  className="m-header-action"
                  href={`/portal-cliente/api/documentos/${d.kind}/${d.id}/file?dl=1`}
                  download={d.name}
                  style={{ display: "inline-flex", textDecoration: "none", color: "inherit" }}
                  aria-label="Baixar"
                >
                  <I.Download size={15} />
                </a>
              </div>
            ))}
          </div>
        </div>
      ))}
    </>
  );
}

// ---------------- Painel mobile: Equipe e seguranca ----------------
function MobileSegurancaPanel({ summary }) {
  const [openType, setOpenType] = React.useState(null);
  const [openFunc, setOpenFunc] = React.useState(null);

  if (!summary || summary.totalAtivos === 0) {
    return (
      <div className="m-card" style={{ padding: 24, textAlign: "center", color: "var(--fg-4)", fontSize: 13 }}>
        Sem trabalhadores alocados nesta obra no momento.
      </div>
    );
  }

  const statusColor = (s) => {
    if (s === "vigente") return "#16a34a";
    if (s === "vencendo") return "#b45309";
    if (s === "vencido" || s === "ausente") return "#dc2626";
    return "#999";
  };
  const statusLabel = (s) => {
    if (s === "vigente") return "Vigente";
    if (s === "vencendo") return "Vencendo";
    if (s === "vencido") return "Vencido";
    if (s === "ausente") return "Ausente";
    return "Sem validade";
  };
  const fileUrl = (id, dl) => "/portal-cliente/api/equipe/documento/" + id + "/file" + (dl ? "?dl=1" : "");

  // Compliance score: % de funcionarios com ASO + NR-35 vigentes
  const totalAtivos = summary.totalAtivos;
  const okASO = summary.porFuncionario.filter((f) => f.asoStatus === "vigente").length;
  const okNR35 = summary.porFuncionario.filter((f) => f.nr35Status === "vigente").length;
  const compliancePct = totalAtivos > 0
    ? Math.round(((okASO + okNR35) / (totalAtivos * 2)) * 100)
    : 0;

  return (
    <>
      {/* Hero card de compliance — alto impacto visual no mobile */}
      <div className="m-card" style={{ marginBottom: 14, overflow: "hidden" }}>
        <div className="m-card-body" style={{ padding: 18 }}>
          <div style={{ display: "flex", alignItems: "center", gap: 14 }}>
            <ComplianceRing pct={compliancePct} />
            <div style={{ flex: 1, minWidth: 0 }}>
              <div style={{ fontSize: 11, color: "var(--fg-4)", textTransform: "uppercase", letterSpacing: "0.06em", fontWeight: 600 }}>
                Compliance
              </div>
              <div style={{ fontSize: 14, fontWeight: 600, color: "var(--fg)", marginTop: 2 }}>
                {totalAtivos} {totalAtivos === 1 ? "trabalhador" : "trabalhadores"} alocado{totalAtivos !== 1 ? "s" : ""}
              </div>
              <div style={{ fontSize: 11.5, color: "var(--fg-3)", marginTop: 2 }}>
                {okASO} com ASO vigente · {okNR35} com NR-35 vigente
              </div>
            </div>
          </div>
        </div>
      </div>

      {/* Cards de tipos de documento — clicaveis para abrir lista */}
      {summary.porTipo.length > 0 && (
        <>
          <div className="m-section-label" style={{ margin: "4px 4px 8px" }}>Cursos e certificados</div>
          <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 8, marginBottom: 14 }}>
            {summary.porTipo.map((t) => {
              const isOpen = openType === t.tipo;
              return (
                <button
                  key={t.tipo}
                  onClick={() => setOpenType(isOpen ? null : t.tipo)}
                  style={{
                    background: "#fff",
                    border: "1px solid " + (isOpen ? "var(--fg)" : "var(--border)"),
                    borderRadius: 16,
                    padding: 14,
                    textAlign: "left",
                    cursor: "pointer",
                    transition: "border-color 120ms ease, background 120ms ease",
                    fontFamily: "inherit",
                    minHeight: 120,
                    display: "flex",
                    flexDirection: "column",
                    gap: 6,
                  }}
                >
                  <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center" }}>
                    <span style={{ fontSize: 9.5, color: "var(--fg-4)", textTransform: "uppercase", letterSpacing: "0.07em", fontWeight: 600 }}>
                      {t.tipo}
                    </span>
                    <I.Chevron size={11} style={{ color: "var(--fg-4)", transform: isOpen ? "rotate(90deg)" : "none", transition: "transform 120ms ease" }} />
                  </div>
                  <div style={{ fontSize: 12.5, fontWeight: 600, color: "var(--fg)", lineHeight: 1.25 }}>
                    {t.label}
                  </div>
                  <div style={{ display: "flex", alignItems: "baseline", gap: 6, marginTop: "auto" }}>
                    <span className="mono" style={{ fontSize: 22, fontWeight: 600, color: "var(--fg)" }}>{t.total}</span>
                    {t.vigente > 0 && (
                      <span style={{ fontSize: 10, color: "#16a34a", fontWeight: 600 }}>
                        ✓ {t.vigente} ok
                      </span>
                    )}
                    {t.vencido > 0 && (
                      <span style={{ fontSize: 10, color: "#dc2626", fontWeight: 600 }}>
                        ✕ {t.vencido}
                      </span>
                    )}
                  </div>
                </button>
              );
            })}
          </div>

          {/* Lista de docs do tipo aberto */}
          {openType && (() => {
            const t = summary.porTipo.find((x) => x.tipo === openType);
            if (!t || !t.documentos || !t.documentos.length) return null;
            return (
              <div className="m-card" style={{ marginBottom: 14, animation: "slideDownFade 0.22s var(--ease-out, ease-out) both" }}>
                <div style={{
                  padding: "10px 14px",
                  borderBottom: "1px solid var(--border)",
                  display: "flex", alignItems: "center", justifyContent: "space-between",
                }}>
                  <div>
                    <div style={{ fontSize: 12, fontWeight: 600, color: "var(--fg)" }}>{t.label}</div>
                    <div style={{ fontSize: 10.5, color: "var(--fg-4)", marginTop: 1 }}>{t.documentos.length} documento{t.documentos.length !== 1 ? "s" : ""}</div>
                  </div>
                  <button
                    onClick={() => setOpenType(null)}
                    style={{ background: "var(--bg-muted)", border: "none", width: 28, height: 28, borderRadius: "50%", display: "grid", placeItems: "center", color: "var(--fg-3)" }}
                    aria-label="Fechar"
                  >
                    <I.X size={12} />
                  </button>
                </div>
                {t.documentos.map((d) => (
                  <div key={d.id} className="m-file-row" style={{ alignItems: "center" }}>
                    <div style={{
                      width: 36, height: 36, borderRadius: 8,
                      background: statusColor(d.status) + "20",
                      color: statusColor(d.status),
                      display: "grid", placeItems: "center",
                      flexShrink: 0,
                      fontSize: 14, fontWeight: 700,
                    }}>
                      {d.status === "vigente" ? "✓" : d.status === "vencido" ? "✕" : d.status === "vencendo" ? "!" : "—"}
                    </div>
                    <div className="m-file-body">
                      <div className="m-file-name" style={{ fontSize: 13 }}>{d.funcionario?.nome || "Documento"}</div>
                      <div className="m-file-meta" style={{ fontSize: 10.5 }}>
                        {d.funcionario?.cargo || "—"}
                        {d.expiryDate && <> · valido ate {fmtDate(d.expiryDate)}</>}
                      </div>
                    </div>
                    <a
                      className="m-header-action"
                      href={fileUrl(d.id)}
                      target="_blank"
                      rel="noopener noreferrer"
                      style={{ display: "inline-flex", textDecoration: "none", color: "inherit" }}
                      aria-label="Abrir"
                    >
                      <I.Eye size={15} />
                    </a>
                    <a
                      className="m-header-action"
                      href={fileUrl(d.id, true)}
                      download={d.nome}
                      style={{ display: "inline-flex", textDecoration: "none", color: "inherit" }}
                      aria-label="Baixar"
                    >
                      <I.Download size={15} />
                    </a>
                  </div>
                ))}
              </div>
            );
          })()}
        </>
      )}

      {/* Lista de trabalhadores — cards expansiveis */}
      <div className="m-section-label" style={{ margin: "4px 4px 8px" }}>Trabalhadores alocados</div>
      <div className="m-card" style={{ overflow: "hidden" }}>
        {summary.porFuncionario.map((f, idx) => {
          const isOpen = openFunc === f.id;
          const docCount = (f.documentos || []).length;
          const initials = (f.nome || "").split(/\s+/).filter(Boolean).slice(0, 2).map((p) => p[0]?.toUpperCase()).join("");
          return (
            <React.Fragment key={f.id}>
              <button
                onClick={() => docCount > 0 && setOpenFunc(isOpen ? null : f.id)}
                style={{
                  display: "flex", alignItems: "center", gap: 12,
                  width: "100%", padding: "14px 16px",
                  background: isOpen ? "var(--bg-muted)" : "transparent",
                  border: "none",
                  borderTop: idx ? "1px solid var(--border)" : "none",
                  cursor: docCount > 0 ? "pointer" : "default",
                  textAlign: "left",
                  fontFamily: "inherit",
                  transition: "background 120ms ease",
                }}
              >
                <div style={{
                  width: 38, height: 38, borderRadius: "50%",
                  background: "var(--fg-3)", color: "#fff",
                  display: "grid", placeItems: "center",
                  fontSize: 12, fontWeight: 600,
                  flexShrink: 0,
                }}>
                  {initials || "?"}
                </div>
                <div style={{ flex: 1, minWidth: 0 }}>
                  <div style={{ fontSize: 13, fontWeight: 600, color: "var(--fg)", overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }}>
                    {f.nome}
                  </div>
                  <div style={{ fontSize: 10.5, color: "var(--fg-4)", marginTop: 2 }}>
                    {f.cargo || "—"}
                  </div>
                  <div style={{ display: "flex", gap: 8, marginTop: 6, flexWrap: "wrap" }}>
                    <StatusBadge label="ASO" status={f.asoStatus} statusColor={statusColor} />
                    <StatusBadge label="NR-35" status={f.nr35Status} statusColor={statusColor} />
                  </div>
                </div>
                {docCount > 0 && (
                  <div style={{
                    fontSize: 10.5, color: "var(--fg-4)",
                    display: "flex", alignItems: "center", gap: 4,
                    flexShrink: 0,
                  }}>
                    {docCount} {docCount === 1 ? "doc" : "docs"}
                    <I.Chevron size={12} style={{ transform: isOpen ? "rotate(90deg)" : "none", transition: "transform 120ms ease" }} />
                  </div>
                )}
              </button>
              {isOpen && f.documentos && f.documentos.length > 0 && (
                <div style={{ background: "var(--bg-muted, #FAFAFA)", borderTop: "1px solid var(--border)", animation: "slideDownFade 0.22s var(--ease-out, ease-out) both" }}>
                  {f.documentos.map((d, i) => (
                    <div key={d.id} style={{
                      display: "flex", alignItems: "center", gap: 10,
                      padding: "10px 16px 10px 60px",
                      borderTop: i ? "1px solid var(--border)" : "none",
                    }}>
                      <span style={{
                        fontSize: 10, fontWeight: 600, color: "var(--fg-3)",
                        background: "#fff",
                        border: "1px solid var(--border)",
                        borderRadius: 999,
                        padding: "2px 8px",
                        flexShrink: 0,
                      }}>
                        {d.tipo}
                      </span>
                      <div style={{ flex: 1, minWidth: 0 }}>
                        <div style={{ fontSize: 12, fontWeight: 500, color: "var(--fg)", overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }}>
                          {d.tipoLabel}
                        </div>
                        <div style={{ fontSize: 10, color: "var(--fg-4)", marginTop: 1, display: "flex", alignItems: "center", gap: 6 }}>
                          <span className="status-dot" style={{ background: statusColor(d.status), display: "inline-block", width: 6, height: 6, borderRadius: "50%" }} />
                          {statusLabel(d.status)}
                          {d.expiryDate && <> · ate {fmtDate(d.expiryDate)}</>}
                        </div>
                      </div>
                      <a
                        className="m-header-action"
                        href={fileUrl(d.id)}
                        target="_blank"
                        rel="noopener noreferrer"
                        style={{ display: "inline-flex", textDecoration: "none", color: "inherit" }}
                        aria-label="Abrir"
                      >
                        <I.Eye size={14} />
                      </a>
                      <a
                        className="m-header-action"
                        href={fileUrl(d.id, true)}
                        download={d.nome}
                        style={{ display: "inline-flex", textDecoration: "none", color: "inherit" }}
                        aria-label="Baixar"
                      >
                        <I.Download size={14} />
                      </a>
                    </div>
                  ))}
                </div>
              )}
            </React.Fragment>
          );
        })}
      </div>

      {/* Privacy banner — discreto */}
      <div style={{
        marginTop: 14,
        padding: "12px 14px",
        background: "var(--bg-muted, #FAFAFA)",
        border: "1px solid var(--border)",
        borderRadius: 16,
        fontSize: 11,
        color: "var(--fg-4)",
        lineHeight: 1.5,
      }}>
        <strong style={{ color: "var(--fg-3)" }}>Privacidade:</strong> exibimos apenas certificados de cursos
        (NR-35, NR-18), atestados e fichas de EPI. Documentos pessoais (RG, CPF, CTPS) nao sao expostos.
      </div>
    </>
  );
}

function ComplianceRing({ pct }) {
  const size = 56;
  const stroke = 5;
  const r = (size - stroke) / 2;
  const c = 2 * Math.PI * r;
  const off = c * (1 - (pct || 0) / 100);
  const color = pct >= 90 ? "#16a34a" : pct >= 70 ? "#b45309" : "#dc2626";
  return (
    <div style={{ position: "relative", width: size, height: size, flexShrink: 0 }}>
      <svg width={size} height={size}>
        <circle cx={size / 2} cy={size / 2} r={r} stroke="var(--bg-muted, #EAEAEA)" strokeWidth={stroke} fill="none" />
        <circle
          cx={size / 2} cy={size / 2} r={r}
          stroke={color} strokeWidth={stroke} fill="none"
          strokeDasharray={c} strokeDashoffset={off}
          strokeLinecap="round"
          transform={`rotate(-90 ${size / 2} ${size / 2})`}
        />
      </svg>
      <div style={{
        position: "absolute", inset: 0,
        display: "grid", placeItems: "center",
        fontSize: 13, fontWeight: 700, color: "var(--fg)",
      }}>
        {pct}%
      </div>
    </div>
  );
}

function StatusBadge({ label, status, statusColor }) {
  return (
    <span style={{
      display: "inline-flex", alignItems: "center", gap: 4,
      fontSize: 10, fontWeight: 600,
      padding: "2px 8px",
      background: "#fff",
      border: "1px solid var(--border)",
      borderRadius: 999,
      color: "var(--fg-3)",
    }}>
      <span style={{ width: 6, height: 6, borderRadius: "50%", background: statusColor(status), display: "inline-block" }} />
      {label} · <span style={{ color: statusColor(status), fontWeight: 700 }}>{status === "ausente" ? "X" : status === "vigente" ? "OK" : status === "vencido" ? "VENC" : status === "vencendo" ? "—" : "—"}</span>
    </span>
  );
}

// ---------------- Painel mobile: Documentos da empresa ----------------
// Pastas geridas pelo admin em "Cursos e Documentos" (Certidoes, Alvara, Seguros, ...)
// Read-only para o cliente. Capricho mobile: hero card de resumo + cards expansiveis
// com icone tematico, contagem e arquivos com view/download.
function MobileEmpresaPanel({ pastas }) {
  const [openId, setOpenId] = React.useState(null);

  if (!pastas || pastas.length === 0) {
    return (
      <div className="m-card" style={{ padding: 24, textAlign: "center", color: "var(--fg-4)", fontSize: 13 }}>
        Sem documentos da empresa disponiveis ainda.
        <div style={{ fontSize: 11, marginTop: 8, color: "var(--fg-4)" }}>
          Quando a Strucon publicar certidoes, alvaras, seguros ou programas SST, eles aparecerao aqui.
        </div>
      </div>
    );
  }

  // Mesma ordem do desktop pra consistencia
  const ORDER = ["certidoes", "licencas", "alvaras", "seguros", "contratos", "programas-sst"];
  const ordered = [...pastas].sort((a, b) => {
    const ai = ORDER.indexOf(a.slug); const bi = ORDER.indexOf(b.slug);
    if (ai === -1 && bi === -1) return a.nome.localeCompare(b.nome);
    if (ai === -1) return 1;
    if (bi === -1) return -1;
    return ai - bi;
  });

  // SVG inline pra evitar problema com glyphs/emojis que renderizam diferente em iOS/Android
  const ICONS = {
    "certidoes": (
      <svg width="22" height="22" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round" strokeLinejoin="round">
        <rect x="6" y="3" width="12" height="18" rx="2" />
        <path d="M9 8h6M9 12h6M9 16h4" />
      </svg>
    ),
    "licencas": (
      <svg width="22" height="22" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round" strokeLinejoin="round">
        <rect x="3" y="6" width="18" height="13" rx="2" />
        <circle cx="9" cy="12.5" r="2.2" />
        <path d="M14 11h5M14 14h4" />
      </svg>
    ),
    "alvaras": (
      <svg width="22" height="22" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round" strokeLinejoin="round">
        <path d="M12 2l3 3h5v5l3 3-3 3v5h-5l-3 3-3-3H4v-5l-3-3 3-3V5h5l3-3z" />
        <path d="M9 12l2 2 4-4" />
      </svg>
    ),
    "seguros": (
      <svg width="22" height="22" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round" strokeLinejoin="round">
        <path d="M12 3l8 3v6c0 5-3.5 8-8 9-4.5-1-8-4-8-9V6l8-3z" />
      </svg>
    ),
    "contratos": (
      <svg width="22" height="22" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round" strokeLinejoin="round">
        <path d="M14 3H7a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h10a2 2 0 0 0 2-2V8z" />
        <path d="M14 3v5h5M9 13h6M9 17h6M9 9h2" />
      </svg>
    ),
    "programas-sst": (
      <svg width="22" height="22" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round" strokeLinejoin="round">
        <path d="M12 3l10 18H2L12 3z" />
        <path d="M12 10v5M12 18.5v.01" />
      </svg>
    ),
    _default: (
      <svg width="22" height="22" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round" strokeLinejoin="round">
        <path d="M3 7a2 2 0 0 1 2-2h4l2 3h8a2 2 0 0 1 2 2v8a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V7z" />
      </svg>
    ),
  };

  const fileUrl = (slug, nome, dl) =>
    "/portal-cliente/api/documentos-empresa/file?slug=" + encodeURIComponent(slug) + "&nome=" + encodeURIComponent(nome) + (dl ? "&dl=1" : "");

  const totalArquivos = ordered.reduce((a, p) => a + (p.totalItens || 0), 0);
  const totalPastas = ordered.length;

  // Pega o arquivo mais recente da empresa toda pro hero
  let maisRecente = null;
  ordered.forEach((p) => {
    (p.arquivos || []).forEach((a) => {
      if (!a.atualizadoEm) return;
      const t = new Date(a.atualizadoEm).getTime();
      if (!maisRecente || t > maisRecente.t) maisRecente = { t, pasta: p.nome, atualizadoEm: a.atualizadoEm };
    });
  });

  return (
    <>
      {/* Hero card de resumo da empresa — alto impacto visual no mobile */}
      <div className="m-card" style={{ marginBottom: 14, overflow: "hidden" }}>
        <div className="m-card-body" style={{ padding: 18 }}>
          <div style={{ display: "flex", alignItems: "center", gap: 14 }}>
            <div style={{
              width: 56, height: 56, borderRadius: 16,
              background: "var(--fg)",
              color: "#fff",
              display: "grid", placeItems: "center",
              flexShrink: 0,
            }}>
              <svg width="26" height="26" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round" strokeLinejoin="round">
                <path d="M3 21V7l9-4 9 4v14" />
                <path d="M9 21V12h6v9" />
                <path d="M3 21h18" />
              </svg>
            </div>
            <div style={{ flex: 1, minWidth: 0 }}>
              <div style={{ fontSize: 11, color: "var(--fg-4)", textTransform: "uppercase", letterSpacing: "0.06em", fontWeight: 600 }}>
                Strucon Engenharia
              </div>
              <div style={{ fontSize: 14, fontWeight: 600, color: "var(--fg)", marginTop: 2 }}>
                {totalArquivos} {totalArquivos === 1 ? "documento" : "documentos"} em {totalPastas} {totalPastas === 1 ? "pasta" : "pastas"}
              </div>
              <div style={{ fontSize: 11.5, color: "var(--fg-3)", marginTop: 2 }}>
                {maisRecente
                  ? `Ultima atualizacao · ${fmtDate(maisRecente.atualizadoEm)}`
                  : "Documentos compartilhados pela empresa"}
              </div>
            </div>
          </div>
        </div>
      </div>

      {/* Lista de pastas — cards expansiveis */}
      <div className="m-section-label" style={{ margin: "4px 4px 8px" }}>Pastas compartilhadas</div>
      <div style={{ display: "flex", flexDirection: "column", gap: 10, marginBottom: 14 }}>
        {ordered.map((pasta) => {
          const isOpen = openId === pasta.id;
          const icon = ICONS[pasta.slug] || ICONS._default;
          return (
            <div key={pasta.id} className="m-card" style={{ overflow: "hidden", transition: "border-color 120ms ease" }}>
              <button
                onClick={() => setOpenId(isOpen ? null : pasta.id)}
                style={{
                  display: "flex", alignItems: "center", gap: 12,
                  width: "100%", padding: "14px 16px",
                  background: isOpen ? "var(--bg-muted)" : "transparent",
                  border: "none",
                  cursor: "pointer",
                  textAlign: "left",
                  fontFamily: "inherit",
                  transition: "background 120ms ease",
                }}
                aria-expanded={isOpen}
              >
                <div style={{
                  width: 42, height: 42, borderRadius: 12,
                  background: isOpen ? "var(--fg)" : "var(--bg-muted, #F3F3F3)",
                  color: isOpen ? "#fff" : "var(--fg)",
                  display: "grid", placeItems: "center",
                  flexShrink: 0,
                  transition: "background 120ms ease, color 120ms ease",
                }}>
                  {icon}
                </div>
                <div style={{ flex: 1, minWidth: 0 }}>
                  <div style={{ fontSize: 13.5, fontWeight: 600, color: "var(--fg)", overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }}>
                    {pasta.nome}
                  </div>
                  <div style={{ fontSize: 10.5, color: "var(--fg-4)", marginTop: 2 }}>
                    {pasta.totalItens} {pasta.totalItens === 1 ? "arquivo" : "arquivos"}
                  </div>
                </div>
                <div style={{
                  fontSize: 10.5, color: "var(--fg-4)",
                  display: "flex", alignItems: "center", gap: 4,
                  flexShrink: 0,
                }}>
                  <span className="mono" style={{ fontSize: 13, fontWeight: 600, color: isOpen ? "var(--fg)" : "var(--fg-3)" }}>
                    {pasta.totalItens}
                  </span>
                  <I.Chevron size={12} style={{ transform: isOpen ? "rotate(90deg)" : "none", transition: "transform 120ms ease" }} />
                </div>
              </button>

              {isOpen && pasta.arquivos && pasta.arquivos.length > 0 && (
                <div style={{
                  background: "var(--bg-muted, #FAFAFA)",
                  borderTop: "1px solid var(--border)",
                  animation: "slideDownFade 0.22s var(--ease-out, ease-out) both",
                }}>
                  {pasta.arquivos.map((a, i) => (
                    <div key={a.nome} style={{
                      display: "flex", alignItems: "center", gap: 10,
                      padding: "12px 16px",
                      borderTop: i ? "1px solid var(--border)" : "none",
                    }}>
                      <div style={{
                        width: 36, height: 36, borderRadius: 8,
                        background: "#fff",
                        border: "1px solid var(--border)",
                        display: "grid", placeItems: "center",
                        flexShrink: 0,
                        fontSize: 9, fontWeight: 700,
                        color: "var(--fg-3)",
                        letterSpacing: "0.04em",
                      }}>
                        {a.type}
                      </div>
                      <div style={{ flex: 1, minWidth: 0 }}>
                        <div style={{
                          fontSize: 12.5, fontWeight: 500, color: "var(--fg)",
                          overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap",
                        }}>
                          {a.nome}
                        </div>
                        <div style={{ fontSize: 10, color: "var(--fg-4)", marginTop: 2 }}>
                          {a.tamanho ? Math.round(a.tamanho / 1024) + " KB" : "—"}
                          {a.atualizadoEm && <> · {fmtDate(a.atualizadoEm)}</>}
                        </div>
                      </div>
                      <a
                        className="m-header-action"
                        href={fileUrl(pasta.slug, a.nome)}
                        target="_blank"
                        rel="noopener noreferrer"
                        style={{ display: "inline-flex", textDecoration: "none", color: "inherit" }}
                        aria-label="Abrir"
                      >
                        <I.Eye size={14} />
                      </a>
                      <a
                        className="m-header-action"
                        href={fileUrl(pasta.slug, a.nome, true)}
                        download={a.nome}
                        style={{ display: "inline-flex", textDecoration: "none", color: "inherit" }}
                        aria-label="Baixar"
                      >
                        <I.Download size={14} />
                      </a>
                    </div>
                  ))}
                </div>
              )}
            </div>
          );
        })}
      </div>

      {/* Banner discreto — read-only e origem dos arquivos */}
      <div style={{
        padding: "12px 14px",
        background: "var(--bg-muted, #FAFAFA)",
        border: "1px solid var(--border)",
        borderRadius: 16,
        fontSize: 11,
        color: "var(--fg-4)",
        lineHeight: 1.5,
      }}>
        <strong style={{ color: "var(--fg-3)" }}>Documentos compartilhados:</strong> certidoes,
        alvaras, registros do CREA, seguros e programas SST publicados pela Strucon. Atualizados
        automaticamente conforme novas versoes sao adicionadas.
      </div>
    </>
  );
}

window.MobileDocumentos = MobileDocumentos;
