describe('Dashboard - smoke tests', () => {
  const fmtBRL = (v) => {
    try { return new Intl.NumberFormat('pt-BR',{style:'currency',currency:'BRL'}).format(v||0); }
    catch(e){ return `R$ ${Number(v||0).toFixed(2)}`; }
  };

  beforeEach(() => {
    // Stub PDV, Pedidos, Orçamentos para KPIs e Tempo real
    cy.intercept('GET', '/api/pdv/vendas', {
      statusCode: 200,
      body: {
        data: [
          { id: 1, numero: '0001', valor_total: 150.35, created_at: '2025-11-01T10:15:00Z' },
          { id: 2, numero: '0002', valor_total: 200.00, created_at: '2025-11-01T12:30:00Z' },
          { id: 3, numero: '0003', valor_total: 99.90,  created_at: '2025-11-02T09:05:00Z' }
        ]
      }
    }).as('pdvVendas');

    cy.intercept('GET', '/api/vendas/pedidos', {
      statusCode: 200,
      body: {
        data: [
          { id: 10, valor_total: 300.00, status: 'aberto', created_at: '2025-11-01T11:00:00Z' },
          { id: 11, valor_total: 180.00, status: 'faturado', created_at: '2025-11-02T14:00:00Z' }
        ]
      }
    }).as('pedidos');

    cy.intercept('GET', '/api/vendas/orcamentos', {
      statusCode: 200,
      body: {
        data: [
          { id: 100, valor_total: 500.00, created_at: '2025-10-20T10:00:00Z' },
          { id: 101, valor_total: 250.00, created_at: '2025-10-21T10:00:00Z' }
        ]
      }
    }).as('orcamentos');

    // Stub finanças (pagar/receber)
    cy.intercept('GET', /\/api\/finance\/payables\?.*/, {
      statusCode: 200,
      body: {
        data: [
          { due_at: '2025-11-03', description: 'Internet', category: 'fixas', status: 'aberto', amount: 120.00 },
          { due_at: '2025-11-05', supplier_name: 'Fornecedor X', category: 'fornecedores', status: 'pendente', amount_cents: 34500 }
        ]
      }
    }).as('payables');

    cy.intercept('GET', /\/api\/finance\/receivables\?.*/, {
      statusCode: 200,
      body: {
        data: [
          { receive_at: '2025-11-04', customer_name: 'Cliente A', origin: 'vendas', status: 'pendente', amount: 500.00 },
          { due_at: '2025-11-07', customer_name: 'Cliente B', origin: 'assinatura', status: 'aberto', amount_cents: 25900 }
        ]
      }
    }).as('receivables');
  });

  it('carrega e exibe elementos principais', () => {
    cy.visit('/dashboard');
    cy.get('h1').contains('Dashboard');
    cy.get('.tab-nav .tab-btn').should('have.length.at.least', 3);
    cy.get('#btnApplyFilters').should('exist');
  });

  it('renderiza KPIs a partir de dados stubados', () => {
    cy.visit('/dashboard');
    cy.wait(['@pdvVendas', '@pedidos', '@orcamentos']);

    const fatTotal = 150.35 + 200.00 + 99.90 + 300.00; // PDV + Pedidos faturamento
    const pedidosAbertos = 1; // apenas um com status 'aberto'
    const totalItens = 3 + 2; // pdv + pedidos
    const ticketMedio = fatTotal / totalItens;

    cy.get('#kpiFatTotal .value').should('contain', fmtBRL(fatTotal));
    cy.get('#kpiPedidosAbertos .value').should('contain', String(pedidosAbertos));
    cy.get('#kpiTicketMedio .value').should('contain', fmtBRL(ticketMedio));
  });

  it('lista tempo real com vendas stubadas', () => {
    cy.visit('/dashboard');
    cy.wait('@pdvVendas');
    cy.get('#rtList li').should('have.length.at.least', 1);
  });

  it('renderiza quadros financeiros e resumo', () => {
    cy.visit('/dashboard');
    cy.wait(['@payables', '@receivables']);
    cy.get('#fpSummary').should('contain', 'Pendentes:');
    cy.get('#frSummary').should('contain', 'Esperados:');
    cy.get('#fpRows tr').should('have.length.at.least', 1);
    cy.get('#frRows tr').should('have.length.at.least', 1);
  });

  it('alterna aba e mantém navegação visual', () => {
    cy.visit('/dashboard');
    cy.get('.tab-nav .tab-btn[href="#sec-despesas"]').click();
    cy.get('.tab-nav .tab-btn[href="#sec-despesas"]').should('have.class', 'active');
    cy.get('.tab-nav .tab-btn[href="#sec-resumo"]').click();
    cy.get('.tab-nav .tab-btn[href="#sec-resumo"]').should('have.class', 'active');
  });
});