/* ==========================================================================
   API CLIENT & HTTP HELPERS
   ========================================================================== */

const API = {
  baseUrl: '',

  getToken() {
    return localStorage.getItem('duobi_token') || localStorage.getItem('oliveira_bi_token');
  },

  setToken(token) {
    localStorage.setItem('duobi_token', token);
    localStorage.setItem('oliveira_bi_token', token);
  },

  removeToken() {
    localStorage.removeItem('duobi_token');
    localStorage.removeItem('oliveira_bi_token');
  },

  getCurrentUser() {
    try {
      const u = localStorage.getItem('duobi_user') || localStorage.getItem('oliveira_bi_user');
      return u ? JSON.parse(u) : null;
    } catch {
      return null;
    }
  },

  setCurrentUser(user) {
    localStorage.setItem('duobi_user', JSON.stringify(user));
    localStorage.setItem('oliveira_bi_user', JSON.stringify(user));
  },

  async request(endpoint, options = {}) {
    const url = `${this.baseUrl}${endpoint}`;
    const headers = {
      'Content-Type': 'application/json',
      ...(options.headers || {})
    };

    const token = this.getToken();
    if (token) {
      headers['Authorization'] = `Bearer ${token}`;
    }

    try {
      const response = await fetch(url, {
        ...options,
        headers
      });

      if (response.status === 401) {
        // Token expirado ou inválido
        this.removeToken();
        if (window.App && window.App.showLogin) {
          window.App.showLogin();
        }
        throw new Error('Sessão expirada. Por favor faça login novamente.');
      }

      const data = await response.json();
      if (!response.ok || data.success === false) {
        throw new Error(data.error || 'Erro na requisição');
      }

      return data;
    } catch (err) {
      console.error(`[API ERROR] ${endpoint}:`, err);
      throw err;
    }
  },

  get(endpoint, params = {}) {
    const query = new URLSearchParams(params).toString();
    const url = query ? `${endpoint}?${query}` : endpoint;
    return this.request(url, { method: 'GET' });
  },

  post(endpoint, body = {}) {
    return this.request(endpoint, {
      method: 'POST',
      body: JSON.stringify(body)
    });
  }
};

/* TOAST NOTIFICATION HELPER */
function showToast(message, type = 'info', duration = 3500) {
  const container = document.getElementById('toast-container');
  if (!container) return;

  const toast = document.createElement('div');
  toast.className = `toast ${type}`;
  
  let iconSvg = '';
  if (type === 'success') {
    iconSvg = `<svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5"><polyline points="20 6 9 17 4 12"></polyline></svg>`;
  } else if (type === 'error') {
    iconSvg = `<svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5"><circle cx="12" cy="12" r="10"></circle><line x1="15" y1="9" x2="9" y2="15"></line><line x1="9" y1="9" x2="15" y2="15"></line></svg>`;
  } else {
    iconSvg = `<svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5"><circle cx="12" cy="12" r="10"></circle><line x1="12" y1="16" x2="12" y2="12"></line><line x1="12" y1="8" x2="12.01" y2="8"></line></svg>`;
  }

  toast.innerHTML = `
    ${iconSvg}
    <span>${message}</span>
  `;

  container.appendChild(toast);

  setTimeout(() => {
    toast.style.opacity = '0';
    toast.style.transform = 'translateY(10px)';
    toast.style.transition = 'all 0.3s ease';
    setTimeout(() => toast.remove(), 300);
  }, duration);
}
