jQuery(function ($) {
  "use strict";

  if (typeof window.fold82smMiniAnalytics === "undefined") {
    console.error("fold82smMiniAnalytics non definito");
    return;
  }

  const cfg = window.fold82smMiniAnalytics;

  const state = {
    pagesPeriod: "today", // Default today
    postsPeriod: "today", // Default today
    busy: false,
  };

  function escHtml(str) {
    return String(str)
      .replace(/&/g, "&amp;")
      .replace(/</g, "&lt;")
      .replace(/>/g, "&gt;")
      .replace(/"/g, "&quot;")
      .replace(/'/g, "&#039;");
  }

  function renderRows(items) {
    if (!Array.isArray(items) || items.length === 0) {
      return `<div style="padding: 20px 0; color:#666; font-size:13px; text-align:center;">No data available for this period.</div>`;
    }

    let html = `
      <div style="display:grid; grid-template-columns: 42px 1fr 80px; gap:10px; padding:8px 0; border-bottom:1px solid #eee; color:#666; font-size:12px;">
        <div><strong>#</strong></div>
        <div><strong>Title</strong></div>
        <div style="text-align:right;"><strong>Views</strong></div>
      </div>
    `;

    items.forEach((it, idx) => {
      const n = idx + 1;
      const title = escHtml(it.title || "Untitled");
      const views = Number(it.views || 0);
      const editUrl = it.edit_url ? String(it.edit_url) : "#";
      const viewUrl = it.view_url ? String(it.view_url) : "#";

      html += `
        <div style="display:grid; grid-template-columns: 42px 1fr 80px; gap:10px; align-items:center; padding:9px 0; border-bottom:1px solid #f3f3f3;">
          <div style="font-weight:700; color:#0073aa;">${n}</div>
          <div style="min-width:0; overflow:hidden; text-overflow:ellipsis; white-space:nowrap;">
            <a href="${escHtml(editUrl)}" style="text-decoration:none; color:#23282d; font-weight:600;">
              ${title}
            </a>
            ${viewUrl !== "#" ? `<a href="${escHtml(viewUrl)}" target="_blank" rel="noopener noreferrer" style="margin-left:6px; color:#0073aa; text-decoration:none;" title="View">↗</a>` : ""}
          </div>
          <div style="text-align:right; font-weight:700; color:#23282d;">${views}</div>
        </div>
      `;
    });

    return html;
  }

  function setLoading($el) {
    $el.html(`<div style="padding: 20px 0; color:#666; font-size:13px; text-align:center;">Loading...</div>`);
  }

  function loadData(type, period) {
    console.log(`loadData chiamato: type=${type}, period=${period}`);
    
    const $pages = $("#fold82sm-mini-analytics-pages");
    const $posts = $("#fold82sm-mini-analytics-posts");
    
    if (type === "pages" && $pages.length) {
      setLoading($pages);
    } else if (type === "posts" && $posts.length) {
      setLoading($posts);
    } else if (type === "all") {
      if ($pages.length) setLoading($pages);
      if ($posts.length) setLoading($posts);
    }

    $.ajax({
      url: cfg.ajax_url,
      method: "POST",
      dataType: "json",
      data: {
        action: "fold82sm_get_mini_analytics",
        nonce: cfg.nonce,
        period: period,
      },
    })
    .done(function (resp) {
      console.log("AJAX response:", resp);
      
      if (resp && resp.success && resp.data) {
        if ($pages.length) {
          $pages.html(renderRows(resp.data.pages || []));
        }
        if ($posts.length) {
          $posts.html(renderRows(resp.data.posts || []));
        }
      } else {
        console.log("Error in response:", resp);
        if ($pages.length) $pages.html(renderRows([]));
        if ($posts.length) $posts.html(renderRows([]));
      }
    })
    .fail(function (jqXHR, textStatus, errorThrown) {
      console.log("AJAX error:", textStatus, errorThrown);
      if ($pages.length) $pages.html(renderRows([]));
      if ($posts.length) $posts.html(renderRows([]));
    });
  }

  // Handle filter click - PAGES
  $(document).on("click", ".fold82sm-mini-analytics-filters-pages button", function (e) {
    e.preventDefault();
    
    const $btn = $(this);
    const period = String($btn.data("period") || "today");
    
    console.log("Click filtro PAGES:", period);
    
    // update UI active state
    $btn.closest("div").find("button").removeClass("is-active");
    $btn.addClass("is-active");
    
    // update state
    state.pagesPeriod = period;
    
    // load data for both
    loadData("all", period);
  });

  // Handle filter click - POSTS
  $(document).on("click", ".fold82sm-mini-analytics-filters-posts button", function (e) {
    e.preventDefault();
    
    const $btn = $(this);
    const period = String($btn.data("period") || "today");
    
    console.log("Click filtro POSTS:", period);
    
    // update UI active state
    $btn.closest("div").find("button").removeClass("is-active");
    $btn.addClass("is-active");
    
    // upgrade state
    state.postsPeriod = period;
    
    // load data for both
    loadData("all", period);
  });

  // load default period="today"
  console.log("Inizializzazione dashboard analytics - default today");
  loadData("all", "today");
});