// ============================================================================
// Weather Schedule Management
// Similar to android_new WeatherSchedule implementation
// ============================================================================

let weatherScheduleData = null;
let currentWeatherData = null;
let weatherCheckInterval = null;
const WEATHER_API_KEY = "41b5176532e682fd8b4cb6a44e3bd1a4";
const GENERATE_PREVIEW_LAST_REQUEST_KEY = "generatePreview:lastRequestAt";
const GENERATE_PREVIEW_MIN_INTERVAL_MS = 3000;

function sleep(ms) {
  return new Promise((resolve) => setTimeout(resolve, ms));
}

async function waitForGeneratePreviewRateLimitSlot() {
  try {
    const lastRequestAt = Number(
      localStorage.getItem(GENERATE_PREVIEW_LAST_REQUEST_KEY) || "0",
    );
    const now = Date.now();
    const waitMs = Math.max(
      0,
      lastRequestAt + GENERATE_PREVIEW_MIN_INTERVAL_MS - now,
    );

    if (waitMs > 0) {
      await sleep(waitMs);
    }

    localStorage.setItem(GENERATE_PREVIEW_LAST_REQUEST_KEY, String(Date.now()));
  } catch {
    await sleep(GENERATE_PREVIEW_MIN_INTERVAL_MS);
  }
}

/**
 * Check if current date is within schedule date range
 */
function checkDateRange(startDate, endDate) {
  const start = new Date(startDate);
  const end = new Date(endDate);
  const now = new Date();

  return now > start && now < end;
}

/**
 * Get weather data from OpenWeatherMap API
 */
async function getWeatherDetails(latitude, longitude, tempUnit) {
  try {
    const response = await fetch(
      `https://api.openweathermap.org/data/2.5/weather?lat=${latitude}&lon=${longitude}&appid=${WEATHER_API_KEY}&units=${tempUnit}`,
    );

    if (response.ok) {
      const data = await response.json();
      const currentTemp = Math.round(data.main.temp);
      console.log("🌡️ Current Temperature:", currentTemp);
      return { success: true, temperature: currentTemp };
    } else {
      console.error("Failed to fetch weather data");
      return { success: false };
    }
  } catch (error) {
    console.error("Error fetching weather:", error);
    return { success: false };
  }
}

/**
 * Check if weather conditions match schedule criteria
 */
async function checkWeatherConditions(schedule, latitude, longitude) {
  const tempUnit = schedule.tempUnit === "Celsius" ? "metric" : "imperial";
  const weatherData = await getWeatherDetails(latitude, longitude, tempUnit);

  if (!weatherData.success) {
    return false;
  }

  const currentTemp = weatherData.temperature;
  const thresholdTemp = schedule.temperature;

  if (schedule.isAbove) {
    console.log(`🌡️ Checking: ${currentTemp} > ${thresholdTemp}`);
    return currentTemp > thresholdTemp;
  } else {
    console.log(`🌡️ Checking: ${currentTemp} < ${thresholdTemp}`);
    return currentTemp < thresholdTemp;
  }
}

/**
 * Find matching weather schedule
 */
async function findMatchingWeatherSchedule() {
  console.log("🔍 Checking weather schedule...");

  if (
    !weatherScheduleData ||
    !weatherScheduleData.myWeatherSchedule ||
    weatherScheduleData.myWeatherSchedule.length === 0
  ) {
    console.log("⚠️ No weather schedule configured");
    return null;
  }

  const schedule = weatherScheduleData.myWeatherSchedule[0];

  // Check date range
  const inDateRange = checkDateRange(schedule.cStartDate, schedule.cEndDate);
  console.log("📅 In date range:", inDateRange);

  if (!inDateRange) {
    console.log("❌ Outside date range");
    return null;
  }

  // Check weather conditions
  const weatherMatches = await checkWeatherConditions(
    schedule,
    weatherScheduleData.latitude,
    weatherScheduleData.longitude,
  );
  console.log("🌤️ Weather matches:", weatherMatches);

  if (weatherMatches) {
    console.log("✅ Weather schedule active!");
    return {
      fileLink: schedule.fileType,
      mediaType: schedule.mediaType,
      screenResolutionName: schedule.screenResolutionName,
      thumbImage: schedule.thumbImage || "NA",
    };
  }

  return null;
}

/**
 * Render media based on type
 */
function renderMedia(mediaData) {
  const container = document.getElementById("weather-container");

  if (mediaData.mediaType === "Video") {
    container.innerHTML = `
      <video 
        autoplay 
        muted 
        loop 
        style="width: 100%; height: 100vh; object-fit: ${mediaData.screenResolutionName === "fit" ? "contain" : "cover"};"
        poster="${mediaData.thumbImage}"
      >
        <source src="${mediaData.fileLink}" type="video/mp4">
      </video>
    `;
  } else {
    container.innerHTML = `
      <img 
        src="${mediaData.fileLink}" 
        style="width: 100%; height: 100vh; object-fit: ${mediaData.screenResolutionName === "fit" ? "contain" : "cover"};"
        alt="Weather Media"
      />
    `;
  }
}

/**
 * Navigate to appropriate screen
 */
function navigateToScreen(data) {
  // Priority: Display (multiple items) > Composition > Default media
  if (data.data && data.data.length > 1) {
    window.location.href = "display-screen.html";
  } else if (
    data.myComposition &&
    data.myComposition[0] &&
    data.myComposition[0].noofBox > 0
  ) {
    window.location.href = "composition-screen.html";
  } else {
    window.location.href = "display-screen.html";
  }
}

/**
 * Check weather schedule periodically
 */
async function checkWeatherSchedule() {
  console.log("⏰ Checking weather schedule at:", new Date().toISOString());

  const weatherMedia = await findMatchingWeatherSchedule();

  if (weatherMedia) {
    // Show weather media
    currentWeatherData = weatherMedia;
    renderMedia(weatherMedia);

    // Hide loader
    if (typeof loaderManager !== "undefined") {
      loaderManager.hide();
    }
  } else {
    // Weather conditions not met, navigate to next screen
    console.log("🔄 Weather conditions not met, navigating...");
    navigateToScreen(weatherScheduleData);
  }
}

/**
 * Initialize weather schedule
 */
async function initWeatherSchedule() {
  console.log("🚀 Initializing weather schedule...");

  try {
    const baseUrl = "https://back.disploy.com/api/NewScreen/GeneratePreview";
    for (let attempt = 1; attempt <= 3; attempt++) {
      await waitForGeneratePreviewRateLimitSlot();

      try {
        const response = await axios.post(baseUrl, {
          macid: localStorage.getItem("machineId"),
        });
        weatherScheduleData = response.data;
        break;
      } catch (error) {
        const isRateLimited = error?.response?.status === 429;
        if (isRateLimited && attempt < 3) {
          console.warn(
            `GeneratePreview 429 (attempt ${attempt}/3). Retrying in 3 seconds...`,
          );
          await sleep(GENERATE_PREVIEW_MIN_INTERVAL_MS);
          continue;
        }
        throw error;
      }
    }

    if (!weatherScheduleData) {
      throw new Error("GeneratePreview data unavailable");
    }

    // Store latitude/longitude for weather checks
    const deviceData = await lookupUserCountry();
    weatherScheduleData.latitude = deviceData.latitude;
    weatherScheduleData.longitude = deviceData.longitude;

    console.log("📊 Weather Schedule Data:", weatherScheduleData);

    // Initial check
    await checkWeatherSchedule();

    // Check every 5 minutes (like android_new)
    weatherCheckInterval = setInterval(
      () => {
        checkWeatherSchedule();
      },
      5 * 60 * 1000,
    );

    console.log("✅ Weather checking started (every 5 minutes)");
  } catch (error) {
    console.error("❌ Error initializing weather schedule:", error);

    // On error, navigate to display screen
    window.location.href = "display-screen.html";
  }
}

// Helper function from index.js (reused here)
async function lookupUserCountry() {
  const defaultResult = {
    latitude: "",
    longitude: "",
  };

  const apiUrl =
    "https://api.ipregistry.co/?key=ira_cAwrJQJ06EjwpdaN0fr3cA5QiFA8cZ18JDx9";

  try {
    const response = await fetch(apiUrl);
    if (!response.ok) {
      return defaultResult;
    }

    const data = await response.json();
    const location = data.location || {};

    return {
      latitude:
        location.latitude !== undefined ? String(location.latitude) : "",
      longitude:
        location.longitude !== undefined ? String(location.longitude) : "",
    };
  } catch (error) {
    console.error("IP lookup failed:", error);
    return defaultResult;
  }
}

// Initialize on page load
document.addEventListener("DOMContentLoaded", initWeatherSchedule);
