/* =========================================================
 * RESPONSIVIDADE GERAL — Camada 1 (Fatia R3)
 *
 * Aplica regras gerais a TODAS as views do sistema.
 * Complementa os arquivos específicos:
 *   - responsivo-fatia10.css (Catálogo, OS, Locação, Estoque)
 *   - responsivo-pdv.css     (PDV)
 *
 * Filosofia: regras genéricas que cobrem 80% dos casos sem
 * conhecer detalhes de cada view. Para views complexas
 * (leads-kanban, admin), tratamento específico em arquivo
 * separado depois.
 * ========================================================= */

/* ─────────────────────────────────────────────────────────────
 * MOBILE — até 640px
 * Aplica em qualquer .view do sistema
 * ─────────────────────────────────────────────────────────── */
@media (max-width: 640px) {

  /* ──── Inputs: font 16px evita zoom safari iOS ao focar ──── */
  .view input[type="text"],
  .view input[type="number"],
  .view input[type="date"],
  .view input[type="email"],
  .view input[type="tel"],
  .view input[type="search"],
  .view input[type="password"],
  .view select,
  .view textarea {
    font-size: 16px !important;
  }

  /* ──── Modais genéricos: tela cheia em celular ──── */
  /* Cobre os modais que usam .modal-bg + .modal-card (legado) */
  .modal-bg .modal-card {
    max-width: calc(100vw - 12px) !important;
    width: calc(100vw - 12px) !important;
    margin: 0 auto !important;
    max-height: calc(100vh - 12px) !important;
    overflow-y: auto !important;
  }
  .modal-bg {
    padding: 6px !important;
    align-items: flex-start !important;
  }

  /* ──── SUB-NAV (sub-tabs dentro de uma view): scroll horizontal ──── */
  /* Quando a view tem muitas sub-abas, em mobile elas quebram em
     várias linhas. Forço scroll horizontal pra preservar layout */
  .sub-nav {
    overflow-x: auto !important;
    flex-wrap: nowrap !important;
    -webkit-overflow-scrolling: touch !important;
    padding-bottom: 4px !important;
    scrollbar-width: thin !important;
  }
  .sub-nav .sub-tab {
    flex: 0 0 auto !important;
    white-space: nowrap !important;
  }

  /* ──── TABELAS HTML: scroll horizontal por padrão ──── */
  /* Pra que rolem em vez de estourar a tela.
     Wrapper genérico — tabela vai dentro de div .table-wrap */
  .view table {
    min-width: 100% !important;
    font-size: 12px !important;
  }
  /* Se a tabela está direta dentro de um sub-pane sem wrapper,
     adiciona scroll horizontal no PRÓPRIO pai */
  .sub-pane > table,
  .view > table {
    display: block !important;
    overflow-x: auto !important;
    white-space: nowrap !important;
    -webkit-overflow-scrolling: touch !important;
  }

  /* ──── GRIDS GENÉRICOS: padrões de layout que viram 1 coluna ──── */
  /* Atenção: já cobertos em arquivos específicos os ids/classes
     da Fatia 10. Aqui pega o RESTO (views antigas) */

  /* Grids de 2 colunas iguais */
  .view [style*="grid-template-columns:1fr 1fr"]:not([style*="1fr 1fr 1fr"]),
  .view [style*="grid-template-columns: 1fr 1fr"]:not([style*="1fr 1fr 1fr"]) {
    grid-template-columns: 1fr !important;
  }
  /* Grids de 3 colunas */
  .view [style*="grid-template-columns:1fr 1fr 1fr"]:not([style*="1fr 1fr 1fr 1fr"]),
  .view [style*="grid-template-columns: 1fr 1fr 1fr"]:not([style*="1fr 1fr 1fr 1fr"]) {
    grid-template-columns: 1fr !important;
  }
  /* Grids 2fr 1fr e 1fr 2fr (assimétricos comuns) */
  .view [style*="grid-template-columns:2fr 1fr"],
  .view [style*="grid-template-columns:1fr 2fr"] {
    grid-template-columns: 1fr !important;
  }

  /* ──── BOTÕES: alvo de toque ──── */
  /* Botões dentro das views ganham mínimo de 38px no celular,
     exceto os explicitamente "btn-sm" ou "mini" */
  .view .btn:not(.btn-sm):not(.btn-mini) {
    min-height: 38px !important;
  }

  /* ──── KPIs/cards em grid auto-fit ──── */
  /* Padrão comum: minmax(180px,1fr), minmax(220px,1fr) etc.
     Em celular pequeno os 220px ficam apertados */
  .view [style*="minmax(220px"],
  .view [style*="minmax(240px"],
  .view [style*="minmax(280px"] {
    grid-template-columns: 1fr !important;
  }

  /* ──── ABAS DO TOPO (tabs principais) ──── */
  /* Já tem padrão no sistema, só refino se necessário */
  .tabs {
    overflow-x: auto !important;
    -webkit-overflow-scrolling: touch !important;
  }

  /* ──── Esconder colunas/blocos marcados como secundários ──── */
  /* Convenção: classe .hide-mobile esconde em celular */
  .hide-mobile { display: none !important; }
  /* .only-mobile aparece só em celular */
  .only-mobile { display: revert !important; }

  /* ──── Espaçamento das views: padding lateral menor ──── */
  /* O conteúdo das views fica colado nas bordas da tela
     em padding generoso. No celular, encolhe. */
  .view {
    padding-left: 12px !important;
    padding-right: 12px !important;
  }

  /* ──── Headers de seção (h1/h2 inline) ──── */
  /* Muitas views têm "div com font-size 18px+ font-family var(--dp)" */
  .view [style*="font-family:var(--dp)"][style*="font-size:24px"],
  .view [style*="font-family: var(--dp)"][style*="font-size: 24px"] {
    font-size: 18px !important;
  }
  .view [style*="font-family:var(--dp)"][style*="font-size:22px"] {
    font-size: 17px !important;
  }
  .view [style*="font-family:var(--dp)"][style*="font-size:20px"] {
    font-size: 16px !important;
  }

  /* ──── Tabelas geradas via JS dentro de panes (Análises, etc) ──── */
  /* Padrão comum: <div style="overflow-x:auto"><table...> */
  /* Garante que se a tabela escapou, fica navegável */
  .sub-pane table:not(.dt):not(.perm-table) {
    font-size: 11px !important;
  }

  /* ──── DASHBOARD: tabelas geradas via JS ──── */
  /* O dashboard tem 4 tabelas inline (novos contratos, cancelamentos,
     top tickets, distribuição). Forço scroll horizontal pra elas
     não estourarem a tela */
  #view-dashboard table {
    min-width: 100%;
    font-size: 10px !important;
  }
  /* O wrapper da tabela já tem max-height + overflow-y. Adiciono
     overflow-x pra rolar lateralmente quando colunas excedem largura */
  #view-dashboard [style*="overflow-y:auto"][style*="border:1px solid"] {
    overflow-x: auto !important;
    -webkit-overflow-scrolling: touch !important;
  }
  /* Cabeçalhos de tabela menores em mobile */
  #view-dashboard th,
  #view-dashboard td {
    padding: 4px 6px !important;
    white-space: nowrap !important;
  }

  /* ──── DASHBOARD: KPIs grandes que ficam absurdos em mobile ──── */
  /* Padrão "font-size:32px font-weight:800" em mobile fica enorme */
  #view-dashboard [style*="font-size:32px"] {
    font-size: 22px !important;
  }
  #view-dashboard [style*="font-size:24px"] {
    font-size: 18px !important;
  }
  #view-dashboard [style*="font-size:20px"][style*="font-weight:9"] {
    font-size: 16px !important;
  }

  /* ──── DASHBOARD: cards do "Saldo Líquido" e similares ──── */
  /* Padding muito grande em telas estreitas */
  #view-dashboard [style*="padding:20px"][style*="border-radius:12px"] {
    padding: 14px !important;
  }
  #view-dashboard [style*="padding:14px"][style*="border-left:4px solid"] {
    padding: 10px !important;
  }

  /* ──── DASHBOARD: grids do tipo "1fr 1fr 1fr" (Min/Mediana/Máximo) ──── */
  /* Já cobertos pelo seletor genérico .view, mas reforço aqui pra
     priorizar mesmo sem o seletor genérico */
  #view-dashboard [style*="grid-template-columns:1fr 1fr 1fr"] {
    grid-template-columns: 1fr 1fr 1fr !important; /* mantém 3 cols mas com gap menor */
    gap: 6px !important;
  }
  #view-dashboard [style*="grid-template-columns:1fr 1fr 1fr"] > div {
    padding: 8px !important;
  }
  #view-dashboard [style*="grid-template-columns:1fr 1fr 1fr"] [style*="font-size:16px"] {
    font-size: 13px !important;
  }

  /* ──── DASHBOARD: Previsão de Caixa (3 períodos) ──── */
  /* Tem grid auto-fit com minmax(140px) — em celular pequeno fica apertado */
  #view-dashboard [style*="minmax(140px"] {
    grid-template-columns: 1fr !important;
  }
  #view-dashboard [style*="minmax(120px"] {
    grid-template-columns: repeat(2, 1fr) !important;
  }

  /* ──── DASHBOARD: Alerta de vencimentos ──── */
  /* O .dash-alerta-venc tem layout horizontal que pode quebrar feio */
  .dash-alerta-venc .dav-row {
    flex-wrap: wrap !important;
    gap: 6px !important;
  }

  /* ──── MODAL BACKUP: botões com texto longo em mobile ──── */
  /* Botão "Baixar ZIP do Sistema (index + módulos JS)" — texto não cabe.
     Botão "Auto Ativo — Desativar" no rodapé — texto não cabe.
     Solução: permitir quebra de linha em palavras + ajustar padding/font. */
  #modal-backup .btn {
    white-space: normal !important;
    word-break: break-word !important;
    line-height: 1.25 !important;
    text-align: center !important;
    padding-left: 10px !important;
    padding-right: 10px !important;
  }
  /* O grid de 3 botões (Supabase / JSON / CSV) quebra pra 1 coluna */
  #modal-backup .bkp-btn-grid {
    grid-template-columns: 1fr !important;
  }
  /* Rodapé do modal: 2 botões (Fechar + Auto Ativo) — empilhar */
  #modal-backup .modal-f {
    flex-wrap: wrap !important;
  }
  #modal-backup .modal-f .btn {
    flex: 1 1 100% !important;
    font-size: 12px !important;
  }
  /* Botão "Auto Ativo — Desativar" especificamente: font menor */
  #btn-auto-bkp {
    font-size: 12px !important;
  }

  /* ──── TOPBAR: badge de sincronização ──── */
  /* Em mobile, "⏳ 1 pendente(s)" não cabe e fica cortado.
     Esconde a palavra "pendente(s)" via técnica de overflow.
     Mantém só "⏳ 1" que é mais que suficiente — clica pra ver detalhes. */
  #cp-sync-badge {
    max-width: 60px !important;
    overflow: hidden !important;
    text-overflow: clip !important;
    white-space: nowrap !important;
    font-size: 10px !important;
    padding: 4px 6px !important;
  }
  /* Botão de busca global na topbar: garante mínimo de toque mas compacto */
  .busca-global-wrap {
    max-width: 130px !important;
  }
  /* Topbar: gap menor pros botões caberem */
  .topbar {
    gap: 4px !important;
  }
}
}

  /* ──── DASHBOARD: textos cortados em mobile — REWORK ──── */
  /* Print mostrou que liberar quebra de linha sem mudar o layout
     deixava o texto espremido entre ícone e botão.

     Solução: em mobile, esses blocos viram COLUNA (emoji+texto em
     cima, botão embaixo full-width). Texto fica com largura toda.

     Casos:
     1. Alertas do topo (#dash-alertas) — emoji + texto + botão
     2. Inadimplência (#dash-inadimplencia) — texto + valor + botão
     3. Top vendedores/clientes — nome + valor à direita
     4. Cards de meta — nome em destaque
  */

  /* Caso 1: Alertas — vira coluna */
  #dash-alertas > div > div[style*="display:flex"][style*="align-items:flex-start"][style*="gap:12px"] {
    flex-wrap: wrap !important;
  }
  /* O bloco do texto: ocupa 100% (deixa espaço pro botão ir embaixo) */
  #dash-alertas [style*="flex:1"][style*="min-width:0"] {
    flex: 1 1 calc(100% - 40px) !important;
  }
  /* Texto do alerta: libera quebra (já fiz, reforço aqui pro caso específico) */
  #dash-alertas [style*="white-space:nowrap"][style*="text-overflow:ellipsis"] {
    white-space: normal !important;
    text-overflow: clip !important;
    overflow: visible !important;
    word-break: break-word !important;
  }
  /* Botão "Ver contratos →" — vai pra linha de baixo, full-width */
  #dash-alertas button.btn-sm {
    flex: 1 1 100% !important;
    margin-top: 8px !important;
  }

  /* Caso 2: Inadimplência — mesma lógica */
  #dash-inadimplencia > div > div[style*="display:flex"][style*="align-items:center"][style*="gap:10px"] {
    flex-wrap: wrap !important;
  }
  #dash-inadimplencia [style*="flex:1"][style*="min-width:0"] {
    flex: 1 1 100% !important;
  }
  #dash-inadimplencia [style*="white-space:nowrap"][style*="text-overflow:ellipsis"] {
    white-space: normal !important;
    text-overflow: clip !important;
    overflow: visible !important;
    word-break: break-word !important;
  }
  /* Valor à direita ganha linha própria */
  #dash-inadimplencia [style*="font-family:var(--mo)"][style*="color:var(--yw)"][style*="white-space:nowrap"] {
    flex: 0 0 auto !important;
    margin-right: 8px !important;
  }
  /* Botão "Cobrar" também */
  #dash-inadimplencia button.btn-sm {
    flex: 0 0 auto !important;
  }

  /* Caso 3: Top 10 vendedores/clientes — nome quebra mas mantém valor à direita */
  /* Esses cards já estão melhor; só garantir que o nome quebre */
  #view-dashboard [style*="flex:1"][style*="min-width:0"]
    > [style*="overflow:hidden"][style*="text-overflow:ellipsis"][style*="white-space:nowrap"] {
    white-space: normal !important;
    text-overflow: clip !important;
    overflow: visible !important;
    word-break: break-word !important;
  }

  /* Caso 4: Cards de meta por vendedor — nome em destaque */
  #view-dashboard [style*="font-weight:700"][style*="font-size:13px"][style*="overflow:hidden"][style*="text-overflow:ellipsis"][style*="white-space:nowrap"] {
    white-space: normal !important;
    text-overflow: clip !important;
    overflow: visible !important;
    word-break: break-word !important;
  }
}

  /* ──── Kanban de Leads ──── */
  /* Já é responsivo, só refino o tamanho das colunas pra elas
     ficarem mais utilizáveis no celular pequeno */
  #leads-kanban-board .kanban-col {
    flex: 0 0 85vw !important;
    max-width: 320px !important;
  }
  /* Painel de detalhe do lead já está display:none em <768px,
     mas reforço aqui caso a media query tenha sido sobrescrita */
  #lead-detalhe-panel {
    display: none !important;
  }

  /* ──── Admin → matriz de permissões ──── */
  /* É uma tabela larga, scroll horizontal é a forma certa */
  #perm-matrix,
  .perm-table {
    min-width: 560px !important;
    font-size: 10px !important;
  }
  /* Wrapper precisa scroll */
  .perm-table-wrap,
  div:has(> #perm-matrix) {
    overflow-x: auto !important;
    -webkit-overflow-scrolling: touch !important;
  }
}

/* ─────────────────────────────────────────────────────────────
 * TABLET — 641px até 1024px
 * ─────────────────────────────────────────────────────────── */
@media (min-width: 641px) and (max-width: 1024px) {

  /* Grids 3 colunas em tablet → 2 colunas */
  .view [style*="grid-template-columns:1fr 1fr 1fr"]:not([style*="1fr 1fr 1fr 1fr"]),
  .view [style*="grid-template-columns: 1fr 1fr 1fr"]:not([style*="1fr 1fr 1fr 1fr"]) {
    grid-template-columns: 1fr 1fr !important;
  }

  /* Grids 4 colunas em tablet → 2 colunas */
  .view [style*="grid-template-columns:1fr 1fr 1fr 1fr"] {
    grid-template-columns: 1fr 1fr !important;
  }
}

/* ─────────────────────────────────────────────────────────────
 * UTILITÁRIOS de visibilidade (pra usar em código novo)
 * ─────────────────────────────────────────────────────────── */
.show-mobile, .only-mobile {
  display: none;
}
@media (max-width: 640px) {
  .show-mobile, .only-mobile {
    display: revert;
  }
}

/* ─────────────────────────────────────────────────────────────
 * MODAL FOOTER RESPONSIVO — botões "Gerar Proposta"
 *   - .propv4-footer: modal de personalização da proposta v4
 *   - .vnd-footer: modal "Registrar Nova Venda"
 * Em mobile estreito, empilha botões em vez de espremer lado a lado
 * ─────────────────────────────────────────────────────────── */
@media (max-width: 480px) {
  .propv4-footer,
  .vnd-footer {
    flex-direction: column !important;
    gap: 8px !important;
  }
  .propv4-footer .btn,
  .vnd-footer .btn {
    flex: 0 0 auto !important;
    width: 100% !important;
    min-width: 0 !important;
  }
}

/* ─────────────────────────────────────────────────────────────
 * PRINT (impressão de comprovantes, relatórios)
 * Esconde elementos de UI que não fazem sentido no papel
 * ─────────────────────────────────────────────────────────── */
@media print {
  .tabs, .topbar, .topb,
  .sub-nav, .sub-tab,
  .pdv-modos, .pdv-hero-actions,
  .modal-bg {
    display: none !important;
  }
  .view {
    padding: 0 !important;
    background: white !important;
    color: black !important;
  }
}
