export const API_CONFIG = {
  BASE_URL: `${process.env.SITE_URL}/api/proxy`,
  
  ENDPOINTS: {
    VISIT: '/analytics/visit',
    EVENT: '/analytics/event',
    COOKIE_CONSENT: '/analytics/cookie-consent',
    METRICS: '/api/analytics/metrics',
    EVENTS: '/api/analytics/events',
    DETAILED_METRICS: '/api/analytics/metrics/detailed',
    EXPORT: '/api/analytics/export'
  },
  
  HEADERS: {
    'Content-Type': 'application/json',
  }
};

export const publicApiRequest = async (endpoint, options = {}) => {
  try {
    const payload = {
      endpoint,
      method: options.method || 'GET'
    };

    if (options.body) {
      payload.body = typeof options.body === 'string' 
        ? JSON.parse(options.body) 
        : options.body;
    }

    const response = await fetch(API_CONFIG.BASE_URL, {
      method: 'POST',
      headers: API_CONFIG.HEADERS,
      body: JSON.stringify(payload)
    });

    const data = await response.json().catch(() => {
      throw new Error('Invalid JSON response');
    });

    if (!response.ok) {
      throw new Error(data.error || data.message || `HTTP error! status: ${response.status}`);
    }

    return data;
  } catch (error) {
    console.warn('Public API request failed:', error.message);
    throw error;
  }
};

export const protectedApiRequest = async (endpoint, accessToken, options = {}) => {
  try {
    const response = await fetch(API_CONFIG.BASE_URL, {
      method: 'POST',
      headers: {
        ...API_CONFIG.HEADERS,
        'Authorization': `Bearer ${accessToken}`
      },
      body: JSON.stringify({
        endpoint,
        ...options
      })
    });

    const data = await response.json().catch(() => {
      throw new Error('Response is not valid JSON');
    });

    if (!response.ok) {
      throw new Error(data.error || data.message || `HTTP error! status: ${response.status}`);
    }

    return data;
  } catch (error) {
    console.error('Protected API request failed:', error.message);
    throw error;
  }
};

export const trackAnalytics = async (url = window.location.href) => {
  const sessionId = sessionStorage.getItem('sessionId') || generateSessionId();
  sessionStorage.setItem('sessionId', sessionId);

  try {
    return await publicApiRequest(API_CONFIG.ENDPOINTS.VISIT, {
      method: 'POST',
      body: {
        timestamp: new Date().toISOString(),
        url,
        sessionId
      }
    });
  } catch (error) {
    console.error('Failed to track analytics:', error.message);
    throw error;
  }
};

export const trackEvent = async (eventName, eventData = {}) => {
  const sessionId = sessionStorage.getItem('sessionId') || generateSessionId();
  sessionStorage.setItem('sessionId', sessionId);

  try {
    return await publicApiRequest(API_CONFIG.ENDPOINTS.EVENT, {
      method: 'POST',
      body: {
        timestamp: new Date().toISOString(),
        url: window.location.href,
        sessionId,
        event: eventName,
        ...eventData
      }
    });
  } catch (error) {
    console.error('Failed to track event:', error.message);
    throw error;
  }
};

function generateSessionId() {
  return `${Date.now()}-${Math.random().toString(36).substr(2, 9)}`;
}