<template>
  <div class="flex flex-col h-full bg-white">
    <!-- Шапка -->
    <div class="p-4 flex justify-between items-center border-b">
      <h2 class="text-lg font-semibold">Ваш маршрут готов</h2>
      <button
          class="text-sm text-cyan-600 cursor-pointer hover:underline"
          @click="restart"
      >
        Начать заново
      </button>
    </div>

    <!-- Основной контент с прокруткой -->
    <div class="flex-1 overflow-y-auto p-4 space-y-6">
      <!-- Контейнер карты -->
      <div class="relative w-full h-64 rounded-lg overflow-hidden border">
        <div id="map" class="absolute inset-0"></div>
      </div>

      <!-- Описание маршрута -->
      <div v-if="store.route?.description" class="prose prose-sm max-w-none">
        <div v-html="renderedDescription" class="text-gray-700 leading-relaxed"></div>
      </div>

      <!-- Список точек маршрута -->
      <div>
        <h3 class="font-semibold text-lg mb-3">Точки маршрута</h3>
        <div class="space-y-5">
          <div v-for="(place, index) in store.route?.places" :key="index" class="border-b pb-4 last:border-b-0">
            <div class="flex items-start gap-3">
              <div class="flex-shrink-0 bg-cyan-500 text-white rounded-full h-8 w-8 flex items-center justify-center font-bold">
                {{ index + 1 }}
              </div>
              <div class="flex-grow">
                <h4 class="font-semibold text-md">{{ place.title || place.name }}</h4>
                <div class="text-xs text-gray-500 mt-1 flex items-center gap-4 flex-wrap">
                  <span v-if="place.time_to_travel" class="flex items-center gap-1">
                    <WalkIcon class="w-4 h-4" /> До точки: ~{{ Math.round(place.time_to_travel) }} мин.
                  </span>
                  <span v-if="place.time_to_visit" class="flex items-center gap-1">
                    <HourglassIcon class="w-4 h-4" /> На точке: {{ place.time_to_visit }} мин.
                  </span>
                </div>
                <p v-if="place.explanation" class="text-sm text-gray-700 mt-2">
                  {{ stripQuotes(place.explanation) }}
                </p>
                <p v-if="place.description" class="text-sm text-gray-700 mt-2">
                  {{ place.description }}
                </p>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>

    <div class="p-4 border-t">
      <button
          class="w-full border py-3 rounded-2xl cursor-pointer hover:bg-gray-50 transition"
          @click="restart"
      >
        Построить ещё маршрут
      </button>
    </div>
  </div>
</template>

<script setup>
import { onMounted, nextTick, computed } from "vue";
import { useMainStore } from "../store/main";
import { marked } from "marked";
import "leaflet/dist/leaflet.css";
import { Home as HomeIcon, Footprints as WalkIcon, Hourglass as HourglassIcon } from "lucide-vue-next";

const store = useMainStore();
let map;

const osrmBaseUrl = import.meta.env.VITE_OSRM_BASE_URL;

// Рендерим markdown в HTML
const renderedDescription = computed(() => {
  if (!store.route?.description) return '';
  return marked(store.route.description);
});

function stripQuotes(str) {
  if (!str) return '';
  return str.replace(/^"|"$/g, '');
}

async function getRouteFromOSRM() {
  if (!osrmBaseUrl || !store.route?.places?.length) {
    console.warn("OSRM URL не сконфигурирован или нет точек для маршрута.");
    return null;
  }

  const allCoords = [
    store.route.coordinates[0],
    ...store.route.places.map(p => {
      if (typeof p.coordinate === 'string') {
        return p.coordinate.split(',').map(Number);
      } else if (Array.isArray(p.coordinate)) {
        return p.coordinate;
      }
      return null;
    }).filter(c => c !== null)
  ];

  const coordsString = allCoords.map(coord => `${coord[1]},${coord[0]}`).join(';');

  const url = `${osrmBaseUrl}/route/v1/foot/${coordsString}?overview=full&geometries=geojson`;

  try {
    const response = await fetch(url);
    if (!response.ok) {
      throw new Error(`OSRM request failed with status: ${response.status}`);
    }
    const data = await response.json();

    if (data.code === 'Ok' && data.routes && data.routes.length > 0) {
      console.log("Маршрут от OSRM успешно получен.");
      return data.routes[0].geometry;
    } else {
      throw new Error(`OSRM response error: ${data.message || 'No route found'}`);
    }
  } catch (error) {
    console.error("Ошибка при получении маршрута от OSRM:", error);
    return null;
  }
}

async function initMap() {
  if (!store.route?.coordinates) return;

  const L = await import("leaflet");

  await nextTick();

  if (map) {
    map.remove();
    map = null;
  }

  const container = document.getElementById("map");
  if (!container) return;

  map = L.map(container, {
    zoomControl: false,
    attributionControl: false
  }).setView(store.route.coordinates[0], 14);

  L.tileLayer("https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png").addTo(map);

  let routeLayer;

  const routeGeometry = await getRouteFromOSRM();

  if (routeGeometry) {
    routeLayer = L.geoJSON(routeGeometry, {
      style: {
        color: "#06b6d4",
        weight: 5,
        opacity: 0.8,
      }
    }).addTo(map);
  } else {
    console.warn("Не удалось построить маршрут через OSRM, рисуем прямые линии.");
    routeLayer = L.polyline(store.route.coordinates, {
      color: "#06b6d4",
      weight: 5,
      opacity: 0.8,
    }).addTo(map);
  }

  store.route.places.forEach((place, i) => {
    let lat, lon;

    if (typeof place.coordinate === 'string') {
      [lat, lon] = place.coordinate.split(',').map(Number);
    } else if (Array.isArray(place.coordinate)) {
      [lat, lon] = place.coordinate;
    } else {
      console.warn(`Неверный формат координат для точки ${i}`);
      return;
    }

    const customIcon = L.divIcon({
      className: 'custom-div-icon',
      html: `<div style='background-color:#06b6d4; color:white; border-radius:50%; width:24px; height:24px; display:flex; align-items:center; justify-content:center; font-size:12px; font-weight:bold; border: 2px solid white;'>${i + 1}</div>`,
      iconSize: [24, 24],
      iconAnchor: [12, 12]
    });

    const popupContent = `<b>${place.title || place.name}</b>${place.address ? '<br>' + place.address : ''}`;

    L.marker([lat, lon], {icon: customIcon})
        .addTo(map)
        .bindPopup(popupContent);
  });

  const startIcon = L.divIcon({
    className: 'start-div-icon',
    html: `
    <svg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 24 24' width='24' height='24' style='color:#06b6d4;'>
      <path
        d='M3 9.75V21h6v-5.25a3 3 0 0 1 6 0V21h6V9.75L12 3 3 9.75z'
        fill='#06b6d4'
        stroke='white'
        stroke-width='2'
        stroke-linejoin='round'
      />
    </svg>
  `,
    iconSize: [24, 24],
    iconAnchor: [12, 24]
  });


  L.marker(store.route.coordinates[0], {icon: startIcon})
      .addTo(map)
      .bindPopup("<b>Вы здесь</b><br>" + store.address);

  map.fitBounds(routeLayer.getBounds().pad(0.1));

  setTimeout(() => map.invalidateSize(), 350);
}

onMounted(() => initMap());

function restart() {
  store.reset();
}
</script>

<style scoped>
/* Стили для markdown контента */
.prose :deep(h1) {
  font-size: 1.5rem;
  font-weight: 700;
  margin-top: 1rem;
  margin-bottom: 0.5rem;
}

.prose :deep(h2) {
  font-size: 1.25rem;
  font-weight: 600;
  margin-top: 0.75rem;
  margin-bottom: 0.5rem;
}

.prose :deep(h3) {
  font-size: 1.125rem;
  font-weight: 600;
  margin-top: 0.5rem;
  margin-bottom: 0.5rem;
}

.prose :deep(p) {
  margin-bottom: 0.75rem;
}

.prose :deep(ul), .prose :deep(ol) {
  margin-left: 1.5rem;
  margin-bottom: 0.75rem;
}

.prose :deep(li) {
  margin-bottom: 0.25rem;
}

.prose :deep(strong) {
  font-weight: 600;
}

.prose :deep(em) {
  font-style: italic;
}

.prose :deep(code) {
  background-color: #f3f4f6;
  padding: 0.125rem 0.25rem;
  border-radius: 0.25rem;
  font-size: 0.875rem;
}
</style>
