import { ref } from 'vue';

/**
 * Composable for managing markers via Kirby API
 * Replaces the old YAML-based useMarkers composable
 */
export function useMarkersApi(pageId) {
  const markers = ref([]);
  const loading = ref(false);
  const error = ref(null);

  // Get CSRF token from Kirby Panel
  const getCsrfToken = () => {
    // Try multiple methods to get the CSRF token

    // Method 1: From window.panel (Kirby Panel global)
    if (window.panel && window.panel.csrf) {
      return window.panel.csrf;
    }

    // Method 2: From meta tag (for non-Panel contexts)
    const meta = document.querySelector('meta[name="csrf"]');
    if (meta && meta.content) {
      return meta.content;
    }

    // Method 3: From window.csrf (sometimes used in Panel)
    if (window.csrf) {
      return window.csrf;
    }

    console.warn('CSRF token not found');
    return '';
  };

  /**
   * Fetch all markers for a page
   */
  async function fetchMarkers() {
    loading.value = true;
    error.value = null;

    try {
      const response = await fetch(`/api/map-editor/pages/${pageId}/markers`, {
        method: 'GET',
        headers: {
          'Content-Type': 'application/json'
        }
      });

      const result = await response.json();

      if (result.status === 'error') {
        throw new Error(result.message || 'Failed to fetch markers');
      }

      markers.value = result.data.markers || [];
      return markers.value;

    } catch (err) {
      error.value = err.message;
      console.error('Error fetching markers:', err);
      throw err;
    } finally {
      loading.value = false;
    }
  }

  /**
   * Create a new marker at the given position
   */
  async function createMarker(position) {
    loading.value = true;
    error.value = null;

    try {
      const response = await fetch(`/api/map-editor/pages/${pageId}/markers`, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
          'X-CSRF': getCsrfToken()
        },
        body: JSON.stringify({ position })
      });

      const result = await response.json();

      if (result.status === 'error') {
        throw new Error(result.message || 'Failed to create marker');
      }

      const newMarker = result.data.marker;
      markers.value.push(newMarker);

      return newMarker;

    } catch (err) {
      error.value = err.message;
      console.error('Error creating marker:', err);
      throw err;
    } finally {
      loading.value = false;
    }
  }

  /**
   * Update a marker's position
   */
  async function updateMarkerPosition(markerId, position) {
    loading.value = true;
    error.value = null;

    try {
      const response = await fetch(`/api/map-editor/pages/${pageId}/markers/${markerId}`, {
        method: 'PATCH',
        headers: {
          'Content-Type': 'application/json',
          'X-CSRF': getCsrfToken()
        },
        body: JSON.stringify({ position })
      });

      const result = await response.json();

      if (result.status === 'error') {
        throw new Error(result.message || 'Failed to update marker position');
      }

      // Update local marker
      const index = markers.value.findIndex(m => m.id === markerId);
      if (index !== -1) {
        markers.value[index] = result.data.marker;
      }

      return result.data.marker;

    } catch (err) {
      error.value = err.message;
      console.error('Error updating marker position:', err);
      throw err;
    } finally {
      loading.value = false;
    }
  }

  /**
   * Delete a marker
   */
  async function deleteMarker(markerId) {
    loading.value = true;
    error.value = null;

    try {
      const response = await fetch(`/api/map-editor/pages/${pageId}/markers/${markerId}`, {
        method: 'DELETE',
        headers: {
          'Content-Type': 'application/json',
          'X-CSRF': getCsrfToken()
        }
      });

      const result = await response.json();

      if (result.status === 'error') {
        throw new Error(result.message || 'Failed to delete marker');
      }

      // Remove from local markers array
      const index = markers.value.findIndex(m => m.id === markerId);
      if (index !== -1) {
        markers.value.splice(index, 1);
      }

      return true;

    } catch (err) {
      error.value = err.message;
      console.error('Error deleting marker:', err);
      throw err;
    } finally {
      loading.value = false;
    }
  }

  return {
    markers,
    loading,
    error,
    fetchMarkers,
    createMarker,
    updateMarkerPosition,
    deleteMarker
  };
}
