/**
 * Composable for managing map data persistence (YAML)
 * Handles loading and saving map data to/from YAML format
 */
import { ref, onBeforeUnmount } from 'vue';
import yaml from 'js-yaml';

/**
 * @param {Object} options
 * @param {Object} options.defaultCenter - Default map center {lat, lon}
 * @param {number} options.defaultZoom - Default zoom level
 * @param {Function} options.onSave - Callback when data is saved
 * @returns {Object} MapData composable
 */
export function useMapData(options = {}) {
  const {
    defaultCenter = { lat: 43.836699, lon: 4.360054 },
    defaultZoom = 13,
    onSave = () => {},
  } = options;

  const center = ref({ ...defaultCenter });
  const zoom = ref(defaultZoom);
  const saveTimeout = ref(null);

  // Cleanup timeout on unmount
  onBeforeUnmount(() => {
    if (saveTimeout.value) {
      clearTimeout(saveTimeout.value);
    }
  });

  /**
   * Load map data from YAML string
   * @param {string} yamlString - YAML content
   * @returns {Object|null} Parsed data or null if error
   */
  function loadMapData(yamlString) {
    if (!yamlString || yamlString.trim() === '') {
      return null;
    }

    try {
      const data = yaml.load(yamlString);

      if (data) {
        if (data.center) {
          center.value = {
            lat: data.center.lat,
            lon: data.center.lon,
          };
        }
        if (data.zoom !== undefined) {
          zoom.value = data.zoom;
        }

        return data;
      }
    } catch (error) {
      console.error('Error loading map data:', error);
      return null;
    }

    return null;
  }

  /**
   * Save map data to YAML format
   * Note: Markers are now stored as subpages, not in YAML
   * @returns {string} YAML string
   */
  function saveMapData() {
    const data = {
      background: {
        type: 'osm',
      },
      center: {
        lat: center.value.lat,
        lon: center.value.lon,
      },
      zoom: zoom.value,
    };

    const yamlString = yaml.dump(data, {
      indent: 2,
      lineWidth: -1,
      noRefs: true,
    });

    onSave(yamlString);
    return yamlString;
  }

  /**
   * Debounced save function
   * @param {number} delay - Delay in milliseconds
   */
  function debouncedSave(delay = 300) {
    if (saveTimeout.value) {
      clearTimeout(saveTimeout.value);
    }
    saveTimeout.value = setTimeout(() => {
      saveMapData();
    }, delay);
  }

  return {
    // State
    center,
    zoom,

    // Methods
    loadMapData,
    saveMapData,
    debouncedSave,
  };
}
