document.addEventListener("DOMContentLoaded", function () {
  // Modal trigger logic for schedule-settings
  const modalBtns = document.querySelector(".schedule-settings .modal-btns");
  if (modalBtns) {
    const [cancelBtn, saveBtn] = modalBtns.querySelectorAll("button");
    const modalSuccess = document.querySelector(
      ".schedule-settings .modal-success"
    );
    const modalError = document.querySelector(
      ".schedule-settings .modal-manage"
    );
    const closeBtns = document.querySelectorAll(
      ".schedule-settings .modal .modal-close"
    );

    if (cancelBtn && modalError) {
      cancelBtn.addEventListener("click", function (e) {
        e.preventDefault();
        modalError.style.display = "block";
      });
    }
    if (saveBtn && modalSuccess) {
      saveBtn.addEventListener("click", function (e) {
        e.preventDefault();
        modalSuccess.style.display = "block";
      });
    }
    closeBtns.forEach((btn) => {
      btn.addEventListener("click", function () {
        modalSuccess && (modalSuccess.style.display = "none");
        modalError && (modalError.style.display = "none");
      });
    });
  }

  // Carousel logic (only if all elements exist)
  const list = document.querySelector(".pending-list");
  const cards = list ? Array.from(list.children) : [];
  const prevBtn = document.querySelector(".carousel-arrow.prev");
  const nextBtn = document.querySelector(".carousel-arrow.next");
  const visibleCount = 3;
  let currentIndex = 0;

  function updateCarousel() {
    if (!list || !cards.length || !prevBtn || !nextBtn) return;
    // Calculate offset
    const cardWidth = cards[0].offsetWidth + 39; // 20 for margin
    list.style.transform = `translateX(-${currentIndex * cardWidth}px)`;

    // Disable/enable arrows
    prevBtn.disabled = currentIndex === 0;
    nextBtn.disabled = currentIndex >= cards.length - visibleCount;
  }

  if (list && cards.length && prevBtn && nextBtn) {
    prevBtn.addEventListener("click", () => {
      if (currentIndex > 0) {
        currentIndex--;
        updateCarousel();
      }
    });

    nextBtn.addEventListener("click", () => {
      if (currentIndex < cards.length - visibleCount) {
        currentIndex++;
        updateCarousel();
      }
    });

    // Initial state
    updateCarousel();
  }

  var modal = document.querySelector(".modal");
  var modalTrigger = document.querySelector(".modal-trigger");
  var modalOverlay = document.querySelector(".modal-overlay");

  modalTrigger &&
    modalTrigger.addEventListener("click", function () {
      modal.classList.add("is-visible");
    });
  modalOverlay &&
    modalOverlay.addEventListener("click", function () {
      modal.classList.remove("is-visible");
    });

  // Chart.js dynamic logic (only if #statsChart exists)
  let dashboardChart = null;
  let currentRange = "week";
  let currentRangeData =
    boostify_blog_ai_dashboard_vars && boostify_blog_ai_dashboard_vars.dashboard_data && boostify_blog_ai_dashboard_vars.dashboard_data.weekStats
      ? boostify_blog_ai_dashboard_vars.dashboard_data.weekStats
      : [];

  // Set fixed height for the chart
  const statsChartCanvas = document.getElementById("statsChart");
  if (statsChartCanvas) {
    statsChartCanvas.style.height = "320px";
    statsChartCanvas.style.maxHeight = "320px";
    statsChartCanvas.style.minHeight = "320px";
    statsChartCanvas.style.width = "100%";
    statsChartCanvas.style.display = "block";
  }

  // Only run chart and stats logic if statsChartCanvas exists
  if (statsChartCanvas) {
    // Helper: get hours array for today
    function getTodayHoursData() {
      const hours = Array.from(
        { length: 24 },
        (_, i) => (i < 10 ? "0" : "") + i + ":00"
      );
      // Simulate posts/views per hour (replace with real data if available)
      // If backend provides per-hour data, use it here
      const postData = Array(24).fill(0);
      const viewsData = Array(24).fill(0);
      // Optionally, fetch per-hour data from backend in the future
      return { labels: hours, postData, viewsData };
    }

    // Helper: get time range labels and simulated data for a day
    function getTimeRangeDataForDayFromBackend(date, callback) {
      fetch(boostify_blog_ai_dashboard_vars.ajaxurl, {
        method: "POST",
        headers: { "Content-Type": "application/x-www-form-urlencoded" },
        body: `action=boostify_dashboard_get_range_data&range=single_day_time_range&date=${date}&nonce=${boostify_blog_ai_dashboard_vars.nonce}`,
      })
        .then((res) => res.json())
        .then((response) => {
          if (response.success) {
            callback(response.data);
          }
        });
    }

    // Helper: fetch grouped day ranges for a given month (for year view single month click)
    function getMonthRangeDataFromBackend(month, year, callback) {
      fetch(boostify_blog_ai_dashboard_vars.ajaxurl, {
        method: "POST",
        headers: { "Content-Type": "application/x-www-form-urlencoded" },
        body: `action=boostify_dashboard_get_range_data&range=month_grouped&month=${month}&year=${year}&nonce=${boostify_blog_ai_dashboard_vars.nonce}`,
      })
        .then((res) => res.json())
        .then((response) => {
          if (response.success) {
            callback(response.data);
          }
        });
    }

    function getChartData(range, data) {
      let labels, currentPeriodData, previousPeriodData;
      
      if (range === "day") {
        // For day, show hourly breakdown
        if (data.current_day && data.previous_day) {
          labels = data.current_day.map(item => item.hour_label);
          currentPeriodData = data.current_day.map(item => item.posts);
          previousPeriodData = data.previous_day.map(item => item.posts);
        } else {
          labels = ["Today", "Yesterday"];
          currentPeriodData = [0, 0];
          previousPeriodData = [0, 0];
        }
      } else if (range === "week") {
        // For week, show daily breakdown
        if (data.current_week && data.previous_week) {
          labels = data.current_week.map(item => item.day_name);
          currentPeriodData = data.current_week.map(item => item.posts);
          previousPeriodData = data.previous_week.map(item => item.posts);
        } else {
          labels = ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"];
          currentPeriodData = [0, 0, 0, 0, 0, 0, 0];
          previousPeriodData = [0, 0, 0, 0, 0, 0, 0];
        }
      } else if (range === "month") {
        // For month, show daily breakdown (every other day)
        if (data.current_month && data.previous_month) {
          labels = data.current_month.map(item => item.day + "/" + item.day_name.substring(0, 3));
          currentPeriodData = data.current_month.map(item => item.posts);
          previousPeriodData = data.previous_month.map(item => item.posts);
        } else {
          labels = ["Start", "Mid", "End"];
          currentPeriodData = [0, 0, 0];
          previousPeriodData = [0, 0, 0];
        }
      } else if (range === "year") {
        // For year, show monthly breakdown
        if (data.current_year && data.previous_year) {
          labels = data.current_year.map(item => item.month_name);
          currentPeriodData = data.current_year.map(item => item.posts);
          previousPeriodData = data.previous_year.map(item => item.posts);
        } else {
          labels = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];
          currentPeriodData = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0];
          previousPeriodData = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0];
        }
      }

      return {
        labels: labels,
        datasets: [
          {
            label: "Current Period",
            data: currentPeriodData,
            borderColor: "#AB54DB",
            backgroundColor: "rgba(171, 84, 219, 0.1)",
            borderWidth: 2,
            fill: true,
            tension: 0.4,
            pointBackgroundColor: "#AB54DB",
            pointBorderColor: "#fff",
            pointBorderWidth: 2,
            pointRadius: 4,
            pointHoverRadius: 6,
            yAxisID: "y",
            datalabels: { display: false },
          },
          {
            label: "Previous Period",
            data: previousPeriodData,
            borderColor: "#FF6B6B",
            backgroundColor: "rgba(255, 107, 107, 0.1)",
            borderWidth: 2,
            fill: true,
            tension: 0.4,
            pointBackgroundColor: "#FF6B6B",
            pointBorderColor: "#fff",
            pointBorderWidth: 2,
            pointRadius: 4,
            pointHoverRadius: 6,
            yAxisID: "y",
            datalabels: { display: false },
          }
        ]
      };
    }

    function updateStatsDisplay(data, range) {
      if (range === "day") {
        if (data.current_day && data.previous_day) {
          const currentDayTotal = data.current_day.reduce((sum, hour) => sum + hour.posts, 0);
          const previousDayTotal = data.previous_day.reduce((sum, hour) => sum + hour.posts, 0);
          
          document.querySelector(".stats-total").textContent = currentDayTotal;
          document.querySelector(".stats-label").textContent = "Posts Today vs Yesterday";
          
          // Calculate percentage change
          const change = previousDayTotal === 0 ? 
            (currentDayTotal > 0 ? 100 : 0) : 
            Math.round(((currentDayTotal - previousDayTotal) / previousDayTotal) * 100);
          
          document.querySelector(".stats-change").textContent = 
            `${change >= 0 ? '+' : ''}${change}%`;
        }
      } else if (range === "week") {
        if (data.current_week && data.previous_week) {
          const currentWeekTotal = data.current_week.reduce((sum, day) => sum + day.posts, 0);
          const previousWeekTotal = data.previous_week.reduce((sum, day) => sum + day.posts, 0);
          
          document.querySelector(".stats-total").textContent = currentWeekTotal;
          document.querySelector(".stats-label").textContent = "Posts This Week vs Last Week";
          
          // Calculate percentage change
          const change = previousWeekTotal === 0 ? 
            (currentWeekTotal > 0 ? 100 : 0) : 
            Math.round(((currentWeekTotal - previousWeekTotal) / previousWeekTotal) * 100);
          
          document.querySelector(".stats-change").textContent = 
            `${change >= 0 ? '+' : ''}${change}%`;
        }
      } else if (range === "month") {
        if (data.current_month && data.previous_month) {
          const currentMonthTotal = data.current_month.reduce((sum, day) => sum + day.posts, 0);
          const previousMonthTotal = data.previous_month.reduce((sum, day) => sum + day.posts, 0);
          
          document.querySelector(".stats-total").textContent = currentMonthTotal;
          document.querySelector(".stats-label").textContent = "Posts This Month vs Last Month";
          
          // Calculate percentage change
          const change = previousMonthTotal === 0 ? 
            (currentMonthTotal > 0 ? 100 : 0) : 
            Math.round(((currentMonthTotal - previousMonthTotal) / previousMonthTotal) * 100);
          
          document.querySelector(".stats-change").textContent = 
            `${change >= 0 ? '+' : ''}${change}%`;
        }
      } else if (range === "year") {
        if (data.current_year && data.previous_year) {
          const currentYearTotal = data.current_year.reduce((sum, month) => sum + month.posts, 0);
          const previousYearTotal = data.previous_year.reduce((sum, month) => sum + month.posts, 0);
          
          document.querySelector(".stats-total").textContent = currentYearTotal;
          document.querySelector(".stats-label").textContent = "Posts This Year vs Last Year";
          
          // Calculate percentage change
          const change = previousYearTotal === 0 ? 
            (currentYearTotal > 0 ? 100 : 0) : 
            Math.round(((currentYearTotal - previousYearTotal) / previousYearTotal) * 100);
          
          document.querySelector(".stats-change").textContent = 
            `${change >= 0 ? '+' : ''}${change}%`;
        }
      }
    }

    // Update renderChart to use the new data structure
    function renderChart(
      range = "week",
      data = boostify_blog_ai_dashboard_vars.dashboard_data.weekStats
    ) {
      const ctx = document.getElementById("statsChart");
      if (!ctx) return;
      if (dashboardChart) {
        dashboardChart.destroy();
        dashboardChart = null;
      }
      
      let chartData;
      if (range === "custom") {
        chartData = data;
      } else {
        chartData = getChartData(range, data);
      }
      
      // Gradients
      const gradientPosts = ctx
        .getContext("2d")
        .createLinearGradient(0, 0, 0, 120);
      gradientPosts.addColorStop(0, "rgba(171, 84, 219, 0.8)");
      gradientPosts.addColorStop(1, "rgba(171, 84, 219, 0.1)");
      const gradientViews = ctx
        .getContext("2d")
        .createLinearGradient(0, 0, 0, 120);
      gradientViews.addColorStop(0, "rgba(16, 185, 129, 0.8)");
      gradientViews.addColorStop(1, "rgba(16, 185, 129, 0.1)");
      
      dashboardChart = new Chart(ctx, {
        type: "line",
        data: {
          labels: chartData.labels,
          datasets: [
            {
              label: "Current Period",
              data: chartData.datasets[0].data,
              borderColor: "#AB54DB",
              backgroundColor: gradientPosts,
              borderWidth: 4,
              fill: true,
              tension: 0.4,
              pointBackgroundColor: "#AB54DB",
              pointBorderColor: "#fff",
              pointBorderWidth: 2,
              pointRadius: 4,
              pointHoverRadius: 6,
              yAxisID: "y",
              datalabels: { display: false },
            },
            {
              label: "Previous Period",
              data: chartData.datasets[1].data,
              borderColor: "#10B981",
              backgroundColor: gradientViews,
              borderWidth: 4,
              borderDash: [10, 10],
              fill: true,
              tension: 0.4,
              pointBackgroundColor: "#10B981",
              pointBorderColor: "#fff",
              pointBorderWidth: 2,
              pointRadius: 4,
              pointHoverRadius: 6,
              yAxisID: "y",
              datalabels: { display: false },
            },
          ],
        },
        options: {
          responsive: true,
          maintainAspectRatio: false,
          interaction: {
            mode: "index",
            intersect: false,
          },
          plugins: {
            legend: {
              display: true,
              position: "top",
              labels: {
                color: "rgba(255, 255, 255, 0.8)",
                usePointStyle: true,
                padding: 20,
                font: { size: 12 },
              },
            },
            tooltip: {
              enabled: true,
              backgroundColor: "rgba(0, 0, 0, 0.8)",
              titleColor: "#fff",
              bodyColor: "#fff",
              borderColor: "#AB54DB",
              borderWidth: 1,
              cornerRadius: 8,
              displayColors: true,
              callbacks: {
                title: function (context) {
                  return context[0].label;
                },
                label: function (context) {
                  if (context.datasetIndex === 0) {
                    return "Current Period Posts: " + context.parsed.y;
                  } else if (context.datasetIndex === 1) {
                    return "Previous Period Posts: " + context.parsed.y;
                  }
                },
              },
            },
          },
          scales: {
            x: {
              display: true,
              grid: { display: false },
              ticks: {
                color: "rgba(255, 255, 255, 0.7)",
                font: { size: 10 },
              },
            },
            y: {
              type: "linear",
              display: true,
              position: "left",
              grid: { color: "rgba(255, 255, 255, 0.1)", drawBorder: false },
              ticks: {
                color: "rgba(255, 255, 255, 0.7)",
                font: { size: 10 },
                stepSize: 1,
                min: 0,
                callback: function (value) {
                  return Number.isInteger(value) ? value : null;
                },
              },
              border: { display: false },
            },
          },
          elements: {
            point: { hoverBackgroundColor: "#AB54DB" },
          },
        },
      });
    }

    // Range button logic
    const rangeBtns = document.querySelectorAll(".range-btn");
    rangeBtns.forEach((btn) => {
      btn.addEventListener("click", function () {
        rangeBtns.forEach((b) => b.classList.remove("active"));
        this.classList.add("active");
        const range = this.textContent.trim().toLowerCase();
        currentRange = range;
        
        // Use the detailed data already available in dashboardData
        let rangeData = null;
        if (range === "day" && boostify_blog_ai_dashboard_vars && boostify_blog_ai_dashboard_vars.dashboard_data && boostify_blog_ai_dashboard_vars.dashboard_data.dayStats) {
          rangeData = boostify_blog_ai_dashboard_vars.dashboard_data.dayStats;
        } else if (range === "week" && boostify_blog_ai_dashboard_vars && boostify_blog_ai_dashboard_vars.dashboard_data && boostify_blog_ai_dashboard_vars.dashboard_data.weekStats) {
          rangeData = boostify_blog_ai_dashboard_vars.dashboard_data.weekStats;
        } else if (range === "month" && boostify_blog_ai_dashboard_vars && boostify_blog_ai_dashboard_vars.dashboard_data && boostify_blog_ai_dashboard_vars.dashboard_data.monthStats) {
          rangeData = boostify_blog_ai_dashboard_vars.dashboard_data.monthStats;
        } else if (range === "year" && boostify_blog_ai_dashboard_vars && boostify_blog_ai_dashboard_vars.dashboard_data && boostify_blog_ai_dashboard_vars.dashboard_data.yearStats) {
          rangeData = boostify_blog_ai_dashboard_vars.dashboard_data.yearStats;
        }
        
        if (rangeData) {
          currentRangeData = rangeData;
          console.log(rangeData);
          renderChart(range, rangeData);
          updateStatsDisplay(rangeData, range);
        } else {
          // Fallback to AJAX if data is not available
          fetch(boostify_blog_ai_dashboard_vars.ajaxurl, {
            method: "POST",
            headers: { "Content-Type": "application/x-www-form-urlencoded" },
            body: `action=boostify_dashboard_get_range_data&range=${range}&nonce=${boostify_blog_ai_dashboard_vars.nonce}`,
          })
            .then((res) => res.json())
            .then((response) => {
              if (response.success) {
                currentRangeData = response.data;
                renderChart(range, response.data);
                updateStatsDisplay(response.data, range);
              }
            });
        }
      });
    });

    // Initial render
    if (boostify_blog_ai_dashboard_vars && boostify_blog_ai_dashboard_vars.dashboard_data) {
      if (boostify_blog_ai_dashboard_vars.dashboard_data.weekStats) {
        renderChart("week", boostify_blog_ai_dashboard_vars.dashboard_data.weekStats);
        updateStatsDisplay(boostify_blog_ai_dashboard_vars.dashboard_data.weekStats, "week");
        currentRange = "week";
        currentRangeData = boostify_blog_ai_dashboard_vars.dashboard_data.weekStats;
      }
    }

    // --- SCHEDULE SETTINGS FORM LOGIC ---
    const scheduleForm = document.getElementById(
      "boostify-schedule-settings-form"
    );
    const manualRunBtn = document.getElementById("boostify-manual-run-btn");
    const modalSuccess = document.querySelector(
      ".schedule-settings .modal-success"
    );
    const modalError = document.querySelector(
      ".schedule-settings .modal-manage"
    );
    const modalManualRunAccept = document.getElementById(
      "modal-manual-run-accept"
    );
    let lastSavedSettings = null;

    // Manual Run logic
    function runManualSchedule(settings) {
      if (!settings) return;
      // Use AJAX to trigger manual run
      fetch(boostify_blog_ai_dashboard_vars.ajaxurl, {
        method: "POST",
        body: new URLSearchParams({
          action: "boostify_dashboard_run_schedule",
          nonce: boostify_blog_ai_dashboard_vars.nonce,
        }),
      })
        .then((res) => res.json())
        .then((response) => {
          if (modalError) {
            if (response.success && response.data && response.data.message) {
              // Show message in modal
              modalError.querySelector(".modal-description").textContent =
                response.data.message;
            } else if (response.message) {
              modalError.querySelector(".modal-description").textContent =
                response.message;
            } else {
              modalError.querySelector(".modal-description").textContent =
                "Manual run completed.";
            }
          }
        })
        .catch(() => {
          if (modalError) {
            modalError.querySelector(".modal-description").textContent =
              "Manual run failed.";
          }
        });
    }

    // Accept in modal triggers manual run
    if (modalManualRunAccept && modalError) {
      modalManualRunAccept.addEventListener("click", function (e) {
        e.preventDefault();
        runManualSchedule(lastSavedSettings);
      });
    }
    // Run Manually button triggers modal and manual run
    if (manualRunBtn && modalError) {
      manualRunBtn.addEventListener("click", function (e) {
        e.preventDefault();
        modalError && (modalError.style.display = "block");
        runManualSchedule(lastSavedSettings);
      });
    }
  }
});
