import { fallbackBounds } from "./sampleData.js";

export function buildTimeline(response) {
  const drones = [];
  const allPoints = [];
  let longest = 0;

  if (!response || !response.dronePaths) {
    return { drones, totalSteps: 0, bounds: fallbackBounds };
  }

  for (const path of response.dronePaths) {
    const coords = flattenDeliveries(path.deliveries);
    if (!coords.length) continue;
    drones.push({ id: path.droneId, path: coords });
    coords.forEach((p) => allPoints.push(p));
    longest = Math.max(longest, coords.length);
  }

  // Add padding points for bounds calculation if empty
  const basePoints =
    allPoints.length > 0
      ? allPoints
      : [
          {
            lng: fallbackBounds.minLng,
            lat: fallbackBounds.minLat,
          },
          {
            lng: fallbackBounds.maxLng,
            lat: fallbackBounds.maxLat,
          },
        ];

  return {
    drones,
    totalSteps: longest || 0,
    bounds: computeBounds(basePoints),
  };
}

function flattenDeliveries(deliveries) {
  const coords = [];
  for (const delivery of deliveries || []) {
    for (const point of delivery.flightPath || []) {
      if (!coords.length || !samePoint(coords[coords.length - 1], point)) {
        coords.push(point);
      }
    }
  }
  return coords;
}

function samePoint(a, b) {
  return Math.abs(a.lng - b.lng) < 1e-9 && Math.abs(a.lat - b.lat) < 1e-9;
}

export function computeBounds(points) {
  if (!points.length) return fallbackBounds;
  let minLng = Infinity,
    maxLng = -Infinity,
    minLat = Infinity,
    maxLat = -Infinity;
  for (const p of points) {
    minLng = Math.min(minLng, p.lng);
    maxLng = Math.max(maxLng, p.lng);
    minLat = Math.min(minLat, p.lat);
    maxLat = Math.max(maxLat, p.lat);
  }
  const padding = 0.002; // Slightly more padding
  return {
    minLng: minLng - padding,
    maxLng: maxLng + padding,
    minLat: minLat - padding,
    maxLat: maxLat + padding,
  };
}

export function colorFor(idx, palette) {
  if (!palette || palette.length === 0) return "#000";
  return palette[idx % palette.length];
}

export function formatDuration(sec) {
  const m = Math.floor(sec / 60)
    .toString()
    .padStart(2, "0");
  const s = Math.floor(sec % 60)
    .toString()
    .padStart(2, "0");
  return `${m}:${s}`;
}

export function computeWallClock(start, seconds) {
  const base = start ? new Date(start) : new Date();
  const ts = new Date(base.getTime() + seconds * 1000);
  return isNaN(ts.getTime()) ? new Date().toISOString() : ts.toISOString();
}

export function boundsKey(bounds) {
  if (!bounds) return "";
  return `${bounds.minLat}:${bounds.maxLat}:${bounds.minLng}:${bounds.maxLng}`;
}
