/* ==========================================================================
   APP CONTROLLER & MAIN ROUTER (DUOBI)
   Theme Switcher, Global Filters, Navigation Lifecycle
   ========================================================================== */

const App = {
  currentView: 'overview',
  filters: {
    start_date: '',
    end_date: '',
    operador: 'all',
    canal: 'all',
    origem: 'all',
    qualificacao: 'all'
  },

  init() {
    this.initTheme();
    this.initNavigation();
    this.initFilterBar();
    this.initUserModal();
    WebhookSimulator.init();
    Auth.init();
  },

  /* ==========================================================================
     THEME SWITCHER (DARK MODE DEFAULT / LIGHT MODE)
     ========================================================================== */
  initTheme() {
    const savedTheme = localStorage.getItem('duobi_theme') || localStorage.getItem('oliveira_bi_theme') || 'dark';
    if (savedTheme === 'light') {
      document.body.classList.add('light-theme');
    } else {
      document.body.classList.remove('light-theme');
    }
    this.updateThemeButtonIcon();

    const btnThemeToggle = document.getElementById('btn-theme-toggle');
    if (btnThemeToggle) {
      btnThemeToggle.addEventListener('click', () => this.toggleTheme());
    }
  },

  toggleTheme() {
    document.body.classList.toggle('light-theme');
    const isLight = document.body.classList.contains('light-theme');
    localStorage.setItem('duobi_theme', isLight ? 'light' : 'dark');
    this.updateThemeButtonIcon();
    showToast(`Tema ${isLight ? 'Claro' : 'Escuro (DuoBI)'} ativado.`, 'info', 2000);

    // Recriar gráficos com novas cores
    this.refreshCurrentView();
  },

  updateThemeButtonIcon() {
    const isLight = document.body.classList.contains('light-theme');
    const btn = document.getElementById('btn-theme-toggle');
    if (!btn) return;

    if (isLight) {
      btn.innerHTML = `
        <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M21 12.79A9 9 0 1 1 11.21 3 7 7 0 0 0 21 12.79z"></path></svg>
        <span class="theme-text">Modo Escuro</span>
      `;
    } else {
      btn.innerHTML = `
        <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><circle cx="12" cy="12" r="5"></circle><line x1="12" y1="1" x2="12" y2="3"></line><line x1="12" y1="21" x2="12" y2="23"></line><line x1="4.22" y1="4.22" x2="5.64" y2="5.64"></line><line x1="18.36" y1="18.36" x2="19.78" y2="19.78"></line><line x1="1" y1="12" x2="3" y2="12"></line><line x1="21" y1="12" x2="23" y2="12"></line><line x1="4.22" y1="19.78" x2="5.64" y2="18.36"></line><line x1="18.36" y1="5.64" x2="19.78" y2="4.22"></line></svg>
        <span class="theme-text">Modo Claro</span>
      `;
    }
  },

  /* ==========================================================================
     SPA ROUTING & NAVIGATION
     ========================================================================== */
  initNavigation() {
    window.addEventListener('hashchange', () => this.handleHashChange());

    document.querySelectorAll('.nav-item').forEach((link) => {
      link.addEventListener('click', (e) => {
        const targetView = link.dataset.view;
        if (targetView) {
          e.preventDefault();
          this.navigate(targetView);
        }
      });
    });
  },

  handleHashChange() {
    const hash = window.location.hash.replace('#', '') || 'overview';
    if (['overview', 'metrics', 'intelligence', 'conversations', 'settings'].includes(hash)) {
      this.navigate(hash, false);
    }
  },

  navigate(viewName, updateHash = true) {
    if (!API.getToken()) {
      this.showLogin();
      return;
    }

    this.currentView = viewName;
    if (updateHash) {
      window.location.hash = viewName;
    }

    // Atualizar Sidebar Active Class
    document.querySelectorAll('.nav-item').forEach((item) => {
      item.classList.toggle('active', item.dataset.view === viewName);
    });

    // Ocultar todas as views e exibir a ativa
    document.querySelectorAll('.view-container').forEach((el) => {
      el.classList.add('hidden');
    });

    const activeViewEl = document.getElementById(`view-${viewName}`);
    if (activeViewEl) {
      activeViewEl.classList.remove('hidden');
      activeViewEl.classList.add('view-animate');
    }

    // Atualizar títulos do Header
    this.updateHeaderTitles(viewName);

    // Carregar dados da view correspondente
    this.loadViewData(viewName);
  },

  updateHeaderTitles(viewName) {
    const titleEl = document.getElementById('page-title-text');
    const subEl = document.getElementById('page-subtitle-text');
    if (!titleEl || !subEl) return;

    const titles = {
      overview: { title: 'Visão Geral Executiva', sub: 'Painel de métricas consolidadas, KPIs e atividades em tempo real' },
      metrics: { title: 'Métricas & Operação BI', sub: 'Análise aprofundada de canais, funil de conversão e performance de operadores' },
      intelligence: { title: 'Inteligência & Prescrições', sub: 'Alertas automáticos de anomalias, playbooks de abordagem e matriz de gargalos' },
      conversations: { title: 'Histórico & Auditoria', sub: 'Registro completo de conversas, leitor de timeline e inspetor de payload JSON' },
      settings: { title: 'Configurações & Logs', sub: 'Monitor de banco de dados MySQL 8.0, auditoria de eventos e gestão de usuários' }
    };

    const cur = titles[viewName] || titles.overview;
    titleEl.textContent = cur.title;
    subEl.textContent = cur.sub;
  },

  loadViewData(viewName) {
    if (viewName === 'overview') OverviewModule.load();
    else if (viewName === 'metrics') MetricsModule.load();
    else if (viewName === 'intelligence') IntelligenceModule.load();
    else if (viewName === 'conversations') ConversationsModule.load();
    else if (viewName === 'settings') SettingsModule.load();
  },

  refreshCurrentView() {
    this.loadViewData(this.currentView);
  },

  showLogin() {
    document.getElementById('app-view-container').classList.add('hidden');
    document.getElementById('login-view-container').classList.remove('hidden');
  },

  showApp() {
    document.getElementById('login-view-container').classList.add('hidden');
    document.getElementById('app-view-container').classList.remove('hidden');
    this.populateFilterDropdowns();
    this.handleHashChange();
  },

  /* ==========================================================================
     GLOBAL FILTER MANAGEMENT
     ========================================================================== */
  initFilterBar() {
    const selChat = document.getElementById('filter-nome-chat');
    const selOperador = document.getElementById('filter-operador');
    const selLoja = document.getElementById('filter-loja');
    const selOrigem = document.getElementById('filter-origem');
    const btnApply = document.getElementById('btn-apply-filters');
    const btnReset = document.getElementById('btn-reset-filters');
    const btnExport = document.getElementById('btn-export-csv');

    if (btnApply) {
      btnApply.addEventListener('click', () => this.applyFilters());
    }

    if (btnReset) {
      btnReset.addEventListener('click', () => {
        if (selChat) selChat.value = 'all';
        if (selOperador) selOperador.value = 'all';
        if (selLoja) selLoja.value = 'all';
        if (selOrigem) selOrigem.value = 'all';
        document.getElementById('filter-start-date').value = '';
        document.getElementById('filter-end-date').value = '';
        this.applyFilters();
      });
    }

    if (btnExport) {
      btnExport.addEventListener('click', () => this.exportFilteredData());
    }

    // Botões de Período Rápido
    document.querySelectorAll('.btn-period-quick').forEach((btn) => {
      btn.addEventListener('click', () => {
        document.querySelectorAll('.btn-period-quick').forEach((b) => b.classList.remove('btn-primary'));
        btn.classList.add('btn-primary');

        const period = btn.dataset.period;
        this.setQuickPeriod(period);
        this.applyFilters();
      });
    });
  },

  setQuickPeriod(period) {
    const today = new Date();
    const formatDate = (d) => d.toISOString().split('T')[0];

    const startInput = document.getElementById('filter-start-date');
    const endInput = document.getElementById('filter-end-date');

    if (period === 'today') {
      startInput.value = formatDate(today);
      endInput.value = formatDate(today);
    } else if (period === '7d') {
      const past = new Date();
      past.setDate(today.getDate() - 7);
      startInput.value = formatDate(past);
      endInput.value = formatDate(today);
    } else if (period === '30d') {
      const past = new Date();
      past.setDate(today.getDate() - 30);
      startInput.value = formatDate(past);
      endInput.value = formatDate(today);
    } else if (period === 'all') {
      startInput.value = '';
      endInput.value = '';
    }
  },

  applyFilters() {
    const selChat = document.getElementById('filter-nome-chat');
    const selOperador = document.getElementById('filter-operador');
    const selLoja = document.getElementById('filter-loja');
    const selOrigem = document.getElementById('filter-origem');
    const startInput = document.getElementById('filter-start-date');
    const endInput = document.getElementById('filter-end-date');

    this.filters = {
      nome_chat: selChat ? selChat.value : 'all',
      operador: selOperador ? selOperador.value : 'all',
      loja: selLoja ? selLoja.value : 'all',
      origem: selOrigem ? selOrigem.value : 'all',
      start_date: startInput ? startInput.value : '',
      end_date: endInput ? endInput.value : ''
    };

    showToast('Filtros aplicados com sucesso!', 'info', 1800);
    this.refreshCurrentView();
  },

  getFilters() {
    return { ...this.filters };
  },

  async populateFilterDropdowns() {
    try {
      const res = await API.get('/api/bi/filter-options');
      const selChat = document.getElementById('filter-nome-chat');
      const selOperador = document.getElementById('filter-operador');
      const selLoja = document.getElementById('filter-loja');
      const selOrigem = document.getElementById('filter-origem');

      if (selChat && res.chats) {
        selChat.innerHTML = '<option value="all">Todos os Chats (Estados)</option>' +
          res.chats.map((ch) => `<option value="${ch}">${ch}</option>`).join('');
      }

      if (selOperador && res.operadores) {
        selOperador.innerHTML = '<option value="all">Todos os Operadores</option>' +
          res.operadores.map((op) => `<option value="${op}">${op}</option>`).join('');
      }

      if (selLoja && res.lojas) {
        selLoja.innerHTML = '<option value="all">Todas as Lojas (Key Entity)</option>' +
          res.lojas.map((l) => `<option value="${l}">${l}</option>`).join('');
      }

      if (selOrigem && res.origens) {
        selOrigem.innerHTML = '<option value="all">Todas as Origens</option>' +
          res.origens.map((o) => `<option value="${o}">${o}</option>`).join('');
      }
    } catch (err) {
      console.error('[FILTER POPULATE ERROR]', err);
    }
  },

  exportFilteredData() {
    const query = new URLSearchParams(this.filters).toString();
    const token = API.getToken();
    const url = `/api/bi/export?format=csv&${query}`;

    fetch(url, {
      headers: { 'Authorization': `Bearer ${token}` }
    })
      .then((res) => res.blob())
      .then((blob) => {
        const downloadUrl = window.URL.createObjectURL(blob);
        const a = document.createElement('a');
        a.href = downloadUrl;
        a.download = `atendimentos_duobi_${new Date().toISOString().split('T')[0]}.csv`;
        document.body.appendChild(a);
        a.click();
        a.remove();
        showToast('Exportação CSV iniciada!', 'success');
      })
      .catch(() => showToast('Erro ao exportar dados.', 'error'));
  },

  /* ==========================================================================
     USER PROFILE & USER MANAGEMENT MODAL CONTROLLER
     ========================================================================== */
  initUserModal() {
    const profileWidget = document.querySelector('.user-profile-widget');
    const modal = document.getElementById('user-profile-modal');
    const btnClose = document.getElementById('btn-close-user-modal');

    const tabMyProfile = document.getElementById('tab-btn-my-profile');
    const tabManageUsers = document.getElementById('tab-btn-manage-users');
    const contentMyProfile = document.getElementById('tab-content-my-profile');
    const contentManageUsers = document.getElementById('tab-content-manage-users');

    if (profileWidget) {
      profileWidget.addEventListener('click', (e) => {
        if (e.target.closest('#btn-logout')) return;
        this.openUserModal();
      });
    }

    if (btnClose) {
      btnClose.addEventListener('click', () => {
        if (modal) modal.classList.remove('open');
      });
    }

    if (modal) {
      modal.addEventListener('click', (e) => {
        if (e.target === modal) modal.classList.remove('open');
      });
    }

    if (tabMyProfile && tabManageUsers) {
      tabMyProfile.addEventListener('click', () => {
        tabMyProfile.className = 'btn btn-primary btn-sm';
        tabManageUsers.className = 'btn btn-secondary btn-sm';
        contentMyProfile.classList.remove('hidden');
        contentManageUsers.classList.add('hidden');
      });

      tabManageUsers.addEventListener('click', () => {
        tabManageUsers.className = 'btn btn-primary btn-sm';
        tabMyProfile.className = 'btn btn-secondary btn-sm';
        contentManageUsers.classList.remove('hidden');
        contentMyProfile.classList.add('hidden');
        this.loadUsersList();
      });
    }

    // Avatar Presets
    document.querySelectorAll('.btn-avatar-preset').forEach((btn) => {
      btn.addEventListener('click', () => {
        const url = btn.dataset.url;
        const avatarInput = document.getElementById('profile-avatar-input');
        const preview = document.getElementById('modal-profile-preview');
        if (avatarInput) avatarInput.value = url;
        if (preview) preview.src = url;
      });
    });

    const avatarInput = document.getElementById('profile-avatar-input');
    if (avatarInput) {
      avatarInput.addEventListener('input', (e) => {
        const preview = document.getElementById('modal-profile-preview');
        if (preview && e.target.value.trim()) preview.src = e.target.value.trim();
      });
    }

    // Save Profile
    const btnSaveProfile = document.getElementById('btn-save-profile');
    if (btnSaveProfile) {
      btnSaveProfile.addEventListener('click', () => this.saveMyProfile());
    }

    // New User Form Submit
    const newUserForm = document.getElementById('new-user-form');
    if (newUserForm) {
      newUserForm.addEventListener('submit', (e) => this.handleCreateUser(e));
    }
  },

  async openUserModal() {
    const modal = document.getElementById('user-profile-modal');
    if (!modal) return;

    try {
      const user = API.getCurrentUser() || {};
      const preview = document.getElementById('modal-profile-preview');
      const avatarInput = document.getElementById('profile-avatar-input');
      const nameInput = document.getElementById('profile-name-input');
      const cargoInput = document.getElementById('profile-cargo-input');
      const emailInput = document.getElementById('profile-email-input');

      const avatarUrl = user.avatar || 'https://images.unsplash.com/photo-1534528741775-53994a69daeb?w=150';
      if (preview) preview.src = avatarUrl;
      if (avatarInput) avatarInput.value = avatarUrl;
      if (nameInput) nameInput.value = user.nome || '';
      if (cargoInput) cargoInput.value = user.cargo || user.role || 'Head de Inteligência';
      if (emailInput) emailInput.value = user.email || '';

      modal.classList.add('open');
    } catch (e) {
      console.error('[OPEN USER MODAL ERROR]', e);
    }
  },

  async saveMyProfile() {
    const nome = document.getElementById('profile-name-input').value.trim();
    const cargo = document.getElementById('profile-cargo-input').value.trim();
    const email = document.getElementById('profile-email-input').value.trim();
    const avatar = document.getElementById('profile-avatar-input').value.trim();

    if (!nome || !email) {
      showToast('Nome e e-mail são obrigatórios.', 'error');
      return;
    }

    try {
      const res = await API.post('/api/auth/profile', { nome, cargo, email, avatar });
      if (res.success) {
        showToast('Perfil atualizado com sucesso!', 'success');
        if (res.user) {
          API.setCurrentUser(res.user);
          Auth.renderUserProfile(res.user);
        }
        const modal = document.getElementById('user-profile-modal');
        if (modal) modal.classList.remove('open');
      }
    } catch (err) {
      showToast(err.message || 'Erro ao atualizar perfil.', 'error');
    }
  },

  async loadUsersList() {
    const tbody = document.getElementById('modal-users-list-body');
    if (!tbody) return;

    try {
      tbody.innerHTML = `<tr><td colspan="4" style="text-align: center; padding: 1.5rem;"><div class="spinner-sm"></div> Carregando usuários...</td></tr>`;
      const res = await API.get('/api/auth/users');
      const users = res.users || [];

      if (users.length === 0) {
        tbody.innerHTML = `<tr><td colspan="4" style="text-align: center; padding: 1rem;">Nenhum usuário cadastrado.</td></tr>`;
        return;
      }

      tbody.innerHTML = users.map((u) => `
        <tr>
          <td>
            <div style="display: flex; align-items: center; gap: 0.5rem;">
              <img src="${u.avatar || 'https://images.unsplash.com/photo-1534528741775-53994a69daeb?w=150'}" style="width: 28px; height: 28px; border-radius: 50%; object-fit: cover;" />
              <span class="font-semibold" style="font-size: 0.82rem;">${u.nome}</span>
            </div>
          </td>
          <td><span style="font-size: 0.78rem; color: var(--text-muted);">${u.cargo || u.role}</span></td>
          <td><span style="font-size: 0.76rem; font-family: monospace;">${u.email}</span></td>
          <td style="text-align: right;">
            <button class="btn btn-secondary btn-sm" onclick="App.deleteUser(${u.id})" style="padding: 0.2rem 0.5rem; color: var(--danger);">Excluir</button>
          </td>
        </tr>
      `).join('');
    } catch (err) {
      showToast('Erro ao carregar usuários.', 'error');
    }
  },

  async handleCreateUser(e) {
    e.preventDefault();
    const nome = document.getElementById('new-user-name').value.trim();
    const email = document.getElementById('new-user-email').value.trim();
    const password = document.getElementById('new-user-password').value.trim();
    const cargo = document.getElementById('new-user-cargo').value.trim();
    const avatar = document.getElementById('new-user-avatar').value.trim();

    try {
      const res = await API.post('/api/auth/users', { nome, email, password, cargo, avatar });
      if (res.success) {
        showToast(`Usuário ${nome} cadastrado com sucesso!`, 'success');
        document.getElementById('new-user-form').reset();
        this.loadUsersList();
      }
    } catch (err) {
      showToast(err.message || 'Erro ao criar usuário.', 'error');
    }
  },

  async deleteUser(userId) {
    if (!confirm('Tem certeza que deseja excluir este usuário?')) return;
    try {
      const res = await API.delete(`/api/auth/users/${userId}`);
      if (res.success) {
        showToast('Usuário removido com sucesso!', 'info');
        this.loadUsersList();
      }
    } catch (err) {
      showToast(err.message || 'Erro ao remover usuário.', 'error');
    }
  }
};

// Bootstrap inicial
document.addEventListener('DOMContentLoaded', () => {
  window.App = App;
  App.init();
});
