(function ($) {
  function guardPages() {
    const token = localStorage.getItem("alertaprecio_token");
    const params = new URLSearchParams(window.location.search);
    const page = params.get("page"); 
    if (!token && (page === "alertaprecio_scraper" || page === "alertaprecio_enrich")) {
      window.location.href = `${window.location.origin}${window.location.pathname}?page=alertaprecio`;
    }
  }

  $(document).ready(() => {
    guardPages();
  });
})(jQuery);

(function ($) {
  "use strict";

  const STORAGE_KEYS = {
    token: ["alertaprecio_token", "alertaprecio_token"],
    email: ["alertaprecio_email", "alertaprecio_email"],
    alerts: ["alertaprecio_numberAlerts", "alertaprecio_alerts"],
    webtoken: ["alertaprecio_webToken", "alertaprecio_webToken"],
  };
  let dummyProducts = [];
  let priceThresholdPercent = 80;

  function getUserData() {
    try {
      const token = STORAGE_KEYS.token
        .map((k) => localStorage.getItem(k))
        .find((v) => v);
      const email = STORAGE_KEYS.email
        .map((k) => localStorage.getItem(k))
        .find((v) => v);
      const numberAlerts = STORAGE_KEYS.alerts
        .map((k) => localStorage.getItem(k))
        .find((v) => v);
      return token && email ? { email, numberAlerts } : null;
    } catch (e) {
      console.error("Error al obtener datos de usuario de localStorage:", e);
      return null;
    }
  }
  function clearWscraperCookies() {
    const names = [
      "alertaprecio_token",
      "alertaprecio_email",
      "alertaprecio_alerts",
      "alertaprecio_webtoken",
    ];
    const paths = ["/wp-admin/", "/"];

    names.forEach((name) => {
      paths.forEach((path) => {
        document.cookie = [
          `${name}=;`,
          `Path=${path};`,
          `Expires=Thu, 01 Jan 1970 00:00:00 GMT;`,
          "SameSite=Lax;",
          "Secure",
        ].join(" ");
      });
    });
  }

  $("#wscraper-logout")
    .off("click")
    .on("click", () => {
      if (!confirm("¿Cerrar sesión?")) return;
      clearWscraperCookies();
      localStorage.clear();
      $.post(ALERTAPRECIO.ajaxurl, {
        action: "alertaprecio_logout",
        _ajax_nonce: ALERTAPRECIO.nonce,
      }).always(() => {
        localStorage.clear();
        location.reload();
      });
      location.reload();
    });

  function updateUserInfoUI(user) {
    if (!user) return;
    $("#wscraper-user-info").show();
    $("#user-email").text(user.email);
    $("#user-alerts").text(user.numberAlerts);
    $("#wscraper-login-google").hide();

    $("#wscraper-logout")
      .off("click")
      .on("click", () => {
        if (!confirm("¿Cerrar sesión?")) return;
        clearWscraperCookies();
        localStorage.clear();
        location.reload();
      });
  }

  async function refreshPluginAlerts() {
    const token = localStorage.getItem("alertaprecio_token");
    const userEmail = localStorage.getItem("alertaprecio_email");
    if (!token || !userEmail) return;

    try {
      const res = await fetch(
        `${ALERTAPRECIO.apiBase}/users/${userEmail}/alerts/plugin`,
        {
          method: "GET",
          headers: {
            Authorization: `Bearer ${token}`,
            "Content-Type": "application/json",
          },
        }
      );
      if (!res.ok) throw new Error(`HTTP ${res.status}`);
      const json = await res.json();
      if (json.numberAlerts != null) {
        $("#user-alerts").text(json.numberAlerts);
      }
    } catch (e) {
      console.error("Error refrescando alertas del plugin:", e);
    }
  }

  function runCronNow() {
    if (!confirm("¿Seguro? Esto consumirá tokens.")) return;
    showCronLoader("🔄 Ejecutando monitoreo…");

    $.post(
      ALERTAPRECIO.ajaxurl,
      {
        action: "alertaprecio_run_cron_now",
        _ajax_nonce: ALERTAPRECIO.nonce,
      },
      (res) => {
        hideCronLoader();
        if (res.success) {
          alert("✅ Cron ejecutado correctamente.");
          refreshPluginAlerts();
          renderProducts();
        } else {
          alert("❌ " + (res.data || "Error al ejecutar cron"));
        }
      }
    ).fail(() => {
      hideCronLoader();
      alert("❌ Falló la llamada AJAX");
    });
  }

  function loadPriceThreshold() {
    $.post(
      ALERTAPRECIO.ajaxurl,
      {
        action: "alertaprecio_get_price_threshold",
        _ajax_nonce: ALERTAPRECIO.nonce,
      },
      (res) => {
        if (res.success && res.data != null) {
          priceThresholdPercent = parseFloat(res.data);
          $("#wscraper-threshold").val(priceThresholdPercent);
        }
      }
    );
  }

  function loadExistingProducts() {
    $.post(
      ALERTAPRECIO.ajaxurl,
      {
        action: "alertaprecio_get_scraped_products",
        _ajax_nonce: ALERTAPRECIO.nonce,
      },
      (res) => {
        if (res.success && Array.isArray(res.data)) {
          dummyProducts = res.data.map((p) => ({
            ...p,
            wooProductId: p.id,
            accepted: p.accepted === true,
            rejected: p.rejected === true,
            alertaprecioConfirmed: p.accepted === true,
            monitoreable: p.monitoreable === true,
            threshold: parseFloat(p.threshold) || priceThresholdPercent,
            markup: parseFloat(p.markup) || 0,
            alertaprecioAutomaticaPrice: p.alertaprecioAutomaticaPrice === true,
          }));
          renderProducts();
        }
      }
    );
  }
function renderProducts(page = 1) {
  const perPage = 8;                               
  const start = (page - 1) * perPage;
  const sorted = dummyProducts.slice().sort((a, b) => b.id - a.id);
  const pageItems = sorted.slice(start, start + perPage);

  const $cont = $("#wscraper-products").empty();
  const $pag = $("#wscraper-pagination").empty();

  pageItems.forEach((p) => {
    const finalPrice = Math.round(
      p.scrapedPrice * (1 + (p.markup || 0) / 100)
    );
    const minPrice = Math.round(p.scrapedPrice * (p.threshold / 100));
    const monitorTxt = p.monitoreable
      ? "✅ Monitoreando"
      : "📡 No monitoreado";

    const $card = $(`
      <div class="wscraper-card" data-id="${p.id}">
        <img src="${p.image}" class="wscraper-img square-img" alt="${p.title}" />
        <div class="wscraper-details">
          <h3>${p.title}</h3>
          <p>${(p.description || "").slice(0, 100)}</p>
          <p class="price-real">Precio origen: ${p.scrapedPrice} ${p.currency}</p>

          ${
            p.alertaprecioConfirmed
              ? `
              <label><strong>% adicional:</strong></label>
              <div style="display:flex;gap:8px;align-items:center;">
                <input
                  type="number"
                  class="markup-input"
                  data-id="${p.id}"
                  value="${p.markup || 0}"
                  min="0"
                  max="100"
                />
                <p style="margin:0;">
                  <span class="final-price">${finalPrice}</span> ${p.currency}
                </p>
             
              </div>

              <label><strong>Umbral mínimo (%):</strong></label>
              <div style="display:flex;gap:8px;align-items:center;">
                <input
                  type="number"
                  class="threshold-input"
                  id=""
                  data-id="${p.id}"
                  value="${p.threshold}"
                  min="0"
                  max="100"
                  style="width:60px;"
                />
                <p>≥ ${minPrice} ${p.currency}</p>
              
              </div>

              <p style="text-align:center;">
                <strong>Estado:</strong> ${monitorTxt}
              </p>

              ${
                p.wooProductId
                  ? `<button class="wscraper-toggle" data-id="${p.id}">
                     ${p.monitoreable ? "Desactivar" : "Activar"} monitoreo
                   </button>`
                  : `<p style="color:red;">❌ Guarda el producto para monitorear</p>`
              }

              ${
                p.wooProductId && p.monitoreable
                  ? `<button class="wscraper-toggle-auto" data-id="${p.id}">
                     ${
                       p.alertaprecioAutomaticaPrice
                         ? "⛔ Desactivar automática"
                         : "🔄 Activar automática"
                     }
                   </button>`
                  : ""
              }
            `
              : ""
          }

          <button class="wscraper-save" data-id="${p.id}">
            ${p.wooProductId ? "Actualizar" : "Guardar"} en WooCommerce
          </button>
        </div>
      </div>
    `);

    $cont.append($card);
  });

  const totalPages = Math.ceil(dummyProducts.length / perPage);
  if (totalPages > 1) {
    for (let i = 1; i <= totalPages; i++) {
      const $b = $(`<button class="wscraper-page-button">${i}</button>`).on(
        "click",
        () => renderProducts(i)
      );
      if (i === page) $b.addClass("active");
      $pag.append($b);
    }
  }
}


  function bindEventHandlers() {
    $(document)
  .off("input", ".threshold-input")
  .on("input", ".threshold-input", function () {
    const id = $(this).data("id");
    const val = parseFloat($(this).val());
    if (isNaN(val) || val < 0 || val > 100) return;
    const prod = dummyProducts.find((p) => p.id === id);
    prod.threshold = val;

    const minPrice = Math.round(prod.scrapedPrice * (val / 100));
    $(this)
      .closest("div")
      .find("p")
      .html(`≥ ${minPrice} ${prod.currency}`);
  });
    $("#wscraper-run-cron").off("click").on("click", runCronNow);
    $(".wscraper-plan-link")
      .off("click")
      .on("click", (e) => {
        e.preventDefault();
        $("#wscraper-modal").fadeIn();
      });
    $(".wscraper-modal-close, #wscraper-modal")
      .off("click")
      .on("click", (e) => {
        if (
          e.target.id === "wscraper-modal" ||
          $(e.target).hasClass("wscraper-modal-close")
        ) {
          $("#wscraper-modal").fadeOut();
        }
      });

    $("#wscraper-login-google")
      .off("click")
      .on("click", () => {
        const callback = encodeURIComponent(
          `${window.location.origin}/?rest_route=/alertaprecio/v1/google-callback`
        );
        window.open(
          `https://api.alertaprecio.online/google-wp-login?callback=${callback}`,
          "_self"
        );
      });

    $("#save-threshold")
      .off("click")
      .on("click", () => {
        const val = parseFloat($("#wscraper-threshold").val());
        if (isNaN(val) || val < 0 || val > 100) {
          return alert(
            "⚠️ El umbral debe ser un porcentaje válido entre 0 y 100."
          );
        }
        $.post(
          ALERTAPRECIO.ajaxurl,
          {
            action: "alertaprecio_set_price_threshold",
            threshold: val,
            _ajax_nonce: ALERTAPRECIO.nonce,
          },
          (res) => {
            if (res.success) {
              priceThresholdPercent = val;
              alert("✅ Umbral guardado correctamente");
              renderProducts();
            } else {
              alert("❌ Error al guardar el umbral");
            }
          }
        );
      });
    const $loader = $("#enrich-loader");
    const $loaderText = $("#enrich-loader-text");
    const $spinner = $loader.find(".spinner");
    const $loaderBtn = $("#enrich-complete-ok");

    function showLoader(msg, showBtn = false) {
      $loaderText.text(msg);
      $spinner.show();
      $loaderBtn.toggle(showBtn);
      $loader.addClass("active");
    }
    function hideLoader() {
      $loader.removeClass("active");
    }
    $loaderBtn.off("click").on("click", function (e) {
      e.preventDefault();
      hideLoader();
    });


    $("#wscraper-fetch").on("click", function () {
      const url = $("#wscraper-url").val().trim();
      if (!url) return alert("⚠️ Ingresa una URL válida");

      showLoader("🔍 Buscando producto…");
  const jwt       = localStorage.getItem('alertaprecio_token')     || '';
const apiKey    = localStorage.getItem('alertaprecio_webtoken') || '';
const headers = {
  'Content-Type': 'application/json',
  'x-api-key':    apiKey,  
  'Authorization': `Bearer ${jwt}`,  
};
    
      fetch(`${ALERTAPRECIO.apiBase}/products/woosearch`, {
        method: "POST",
        headers,
        body: JSON.stringify({ input: url, currency: ALERTAPRECIO.currency }),
      })
        .then((r) => r.json())
        .then((data) => {
          if (!data.price || parseFloat(data.price) <= 0) {
            throw new Error("No se encontró un precio válido");
          }
          const now = Date.now();
          dummyProducts.push({
            id: now,
            alertaprecioUrl: url,
            title: data.name || "Producto sin nombre",
            image: data.image || "",
            description: data.description || 'No hay información',
            scrapedPrice: Math.round(parseFloat(data.price)),
            currency: ALERTAPRECIO.currency,
            markup: 0,
            threshold: priceThresholdPercent,
            monitoreable: false,
            alertaprecioConfirmed: false,
          });
          renderProducts();
          refreshPluginAlerts();

          showLoader("✅ Producto encontrado", true);
        })
        .catch((err) => {
          console.error(err);
          showLoader(`❌ ${err.message}`, true);
        });
    });

    $(document)
      .off("click", ".wscraper-accept, .wscraper-reject")
      .on("click", ".wscraper-accept, .wscraper-reject", function () {
        const id = $(this).data("id");
        const prod = dummyProducts.find((p) => p.id === id);
        if ($(this).hasClass("wscraper-accept")) {
          prod.accepted = true;
          prod.rejected = false;
          prod.alertaprecioConfirmed = true;
        } else {
          prod.rejected = true;
          prod.accepted = false;
          prod.monitoreable = false;
          prod.alertaprecioConfirmed = false;
        }
        renderProducts();
      });

    $(document)
      .off("click", ".wscraper-save")
      .on("click", ".wscraper-save", function () {
        const id = $(this).data("id");
        const prod = dummyProducts.find((p) => p.id === id);
        const isNew = !prod.wooProductId;

        if (
          !confirm(
            `¿Seguro que quieres ${
              isNew ? "guardar" : "actualizar"
            } este producto en WooCommerce con precio final ${Math.round(
              prod.scrapedPrice * (1 + (prod.markup || 0) / 100)
            )}?`
          )
        ) {
          return;
        }

        const priceToSave = Math.round(
          prod.scrapedPrice * (1 + (prod.markup || 0) / 100)
        );
        const val = parseFloat($(`.threshold-input[data-id="${id}"]`).val());

        const payload = {
          ...prod,
          price: priceToSave,
          priceScraped: prod.scrapedPrice,
          monitoreable: prod.monitoreable,
          _alertaprecio_confirmed: true,
          threshold:val,
        };
        const action = isNew
          ? "alertaprecio_add_product"
          : "alertaprecio_update_product_price";

        $.post(
          ALERTAPRECIO.ajaxurl,
          { action, data: payload, _ajax_nonce: ALERTAPRECIO.nonce },
          (res) => {
            if (res.success) {
              alert(
                `✅ Producto ${isNew ? "creado" : "actualizado"} correctamente`
              );
              prod.wooProductId = res.data.id;
              prod.id = res.data.id;
              prod.alertaprecioConfirmed = true;
              prod.monitoreable = true;
              
              renderProducts();
            } else {
              alert("❌ Error: " + res.data);
            }
          }
        );
      });

    $(document)
      .off("click", ".wscraper-toggle")
      .on("click", ".wscraper-toggle", function () {
        const id = $(this).data("id");
        const prod = dummyProducts.find((p) => p.id === id);
        const enable = !prod.monitoreable;
        const msg = enable
          ? "¿Confirmar activación de monitoreo?"
          : "¿Confirmar desactivación de monitoreo?";
        if (!confirm(msg)) return;
        $.post(
          ALERTAPRECIO.ajaxurl,
          {
            action: "alertaprecio_toggle_monitoring",
            product_id: prod.wooProductId,
            monitor: enable,
            _ajax_nonce: ALERTAPRECIO.nonce,
          },
          (res) => {
             prod.monitoreable = enable;
              renderProducts();
          }
        );
      });
    $(document)
      .off("click", ".wscraper-toggle-auto")
      .on("click", ".wscraper-toggle-auto", function () {
        const id = $(this).data("id");
        const prod = dummyProducts.find((p) => p.id === id);
        const enable = !prod.alertaprecioAutomaticaPrice;
        const msg = enable
          ? "¿Confirmar activación de automática?"
          : "¿Confirmar desactivación de automática?";
        if (!confirm(msg)) return;
        $.post(
          ALERTAPRECIO.ajaxurl,
          {
            action: "alertaprecio_toggle_auto_price",
            product_id: prod.wooProductId,
            auto: enable,
            _ajax_nonce: ALERTAPRECIO.nonce,
          },
          (res) => {
            if (res.success) {
              prod.alertaprecioAutomaticaPrice = enable;
              renderProducts();
            } else {
              alert("❌ No se pudo cambiar estado.");
            }
          }
        );
      });
    $(document)
      .off("input", ".markup-input")
      .on("input", ".markup-input", function () {
        const id = $(this).data("id");
        const val = parseFloat($(this).val());
        if (isNaN(val) || val < 0) return;
        const prod = dummyProducts.find((p) => p.id === id);
        prod.markup = val;
        const newP = Math.round(prod.scrapedPrice * (1 + val / 100));
        $(this).closest(".wscraper-card").find(".final-price").text(newP);
      });

    $(document)
      .off("click", ".assign-markup")
      .on("click", ".assign-markup", function () {
        const id = $(this).data("id");
        const val = parseFloat($(`.markup-input[data-id="${id}"]`).val());
        if (isNaN(val) || val < 0) {
          return alert("⚠️ Valor inválido");
        }
        $.post(
          ALERTAPRECIO.ajaxurl,
          {
            action: "alertaprecio_update_markup",
            product_id: id,
            markup: val,
            _ajax_nonce: ALERTAPRECIO.nonce,
          },
          (res) => {
            if (res.success) {
              alert("✅ Porcentaje asignado");
              const prod = dummyProducts.find((p) => p.id === id);
              prod.markup = val;
              renderProducts();
            } else {
              alert("❌ No se pudo actualizar");
            }
          }
        );
      });
    $(document)
      .off("click", ".assign-threshold")
      .on("click", ".assign-threshold", function () {
        const id = $(this).data("id");
        const val = parseFloat($(`.threshold-input[data-id="${id}"]`).val());
        if (isNaN(val) || val < 0 || val > 100) {
          return alert("⚠️ Valor inválido");
        }
        $.post(
          ALERTAPRECIO.ajaxurl,
          {
            action: "alertaprecio_update_threshold",
            product_id: id,
            threshold: val,
            _ajax_nonce: ALERTAPRECIO.nonce,
          },
          (res) => {
            if (res.success) {
              alert("✅ Umbral actualizado");
              const prod = dummyProducts.find((p) => p.id === id);
              prod.threshold = val;
              renderProducts();
            } else {
              alert("❌ No se pudo actualizar");
            }
          }
        );
      });
  }

  const $enrichLoader = $("#enrich-loader");
  const $enrichLoaderText = $("#enrich-loader-text");
  const $enrichCompleteBtn = $("#enrich-complete-ok");
  let enrichCanceled = false;

  function showEnrichLoader() {
    enrichCanceled = false;
    $enrichLoader.addClass("active");
    $(".spinner").show();
    $enrichCompleteBtn.hide();
  }

  function hideEnrichLoader() {
    $enrichLoader.removeClass("active");
  }

  $enrichCompleteBtn.off("click").on("click", () => location.reload());
  const $cronLoader = $("#enrich-loader");
  const $cronLoaderText = $("#enrich-loader-text");

  function showCronLoader(msg) {
    $cronLoaderText.text(msg);
    $cronLoader.addClass("active");
    $cronLoader.find(".spinner").show();
    $("#enrich-complete-ok").hide();
  }

  function hideCronLoader() {
    $cronLoader.removeClass("active");
  }

  async function callEnrichAPI(mode, items) {
    const token = localStorage.getItem("alertaprecio_token");
    const webtoken = localStorage.getItem("alertaprecio_webtoken");
    const email = localStorage.getItem("alertaprecio_email");

    if (!token || !webtoken || !email) {
      alert("❌ Debes iniciar sesión antes de enriquecer.");
      throw new Error("No se encontró información de sesión.");
    }

    const url = `${ALERTAPRECIO.apiBase}/enrich/${mode}`;
    try {
      const res = await fetch(url, {
        method: "POST",
        headers: {
          "Content-Type": "application/json",
          Authorization: `Bearer ${token}`,
        },
        body: JSON.stringify({ items }),
      });

      if (!res.ok) {
        const text = await res.text();
        throw new Error(`HTTP ${res.status}: ${text}`);
      }

      const json = await res.json();

      if (Array.isArray(json)) {
        return json;
      }

      if (json.success) {
        return json.data;
      }

      throw new Error(json.error || "Respuesta inválida del servidor");
    } catch (err) {
      console.error(`❌ Error en enrich/${mode}:`, err);
      alert(`❌ Falló enrich/${mode}: ${err.message}`);
      throw err;
    }
  }

  async function handleEnrichment(mode, costPerItem) {
    const items = $(".enrich-checkbox:checked")
      .map((_, cb) => {
        const $tr = $(cb).closest("tr");
        return {
          webToken: localStorage.getItem("alertaprecio_webtoken"),
          productId: $tr.data("id"),
          title: $tr.data("title"),
          description: $tr.data("description") || 'No hay información',
          url: $tr.data("url"),
          images: $tr.data("images") || [],
        };
      })
      .get();

    if (!items.length) {
      return alert("⚠️ Selecciona al menos un producto.");
    }
    const totalTokens = items.length * costPerItem;
    if (
      !confirm(
        `¿Gastar ${totalTokens} tokens en Enriquecedor ${
          mode === "basic" ? "Básico" : "Premium"
        }?`
      )
    ) {
      return;
    }

    showEnrichLoader();
    try {
      for (let i = 0; i < items.length; i++) {
        if (enrichCanceled) break;

        $enrichLoaderText.text(
          `Enviando ${mode === "basic" ? "Básico" : "Premium"} ${i + 1} de ${
            items.length
          }…`
        );
        let enriched;
        try {
          enriched = await callEnrichAPI(mode, [items[i]]);
        } catch (e) {
          $enrichLoaderText.text(`❌ Error en envío ${mode} ${i + 1}`);
          break;
        }

        if (enrichCanceled) break;

        $enrichLoaderText.text(
          `Procesando ${mode === "basic" ? "Básico" : "Premium"} ${i + 1} de ${
            items.length
          }…`
        );
        if (Array.isArray(enriched) && enriched[0]) {
          try {
            await $.post(ALERTAPRECIO.ajaxurl, {
              action: "alertaprecio_update_enriched",
              data: enriched[0],
              _ajax_nonce: ALERTAPRECIO.nonce,
            });
          } catch (e) {
            console.error(e);
            $enrichLoaderText.text(`❌ Error guardando ${mode} ${i + 1}`);
            break;
          }
        }

        $(`tr[data-id="${items[i].productId}"] .col-enrich`).css(
          "font-weight",
          "bold"
        );
      }
    } finally {
      if (!enrichCanceled) {
        $enrichLoaderText.text(
          `✅ Enriquecimiento ${
            mode === "basic" ? "Básico" : "Premium"
          } completado.`
        );
      } else {
        $enrichLoaderText.text("❌ Enriquecido cancelado.");
      }
      $(".spinner").hide();
      $enrichCompleteBtn.show();
      refreshPluginAlerts();
    }
  }

  function renderEnrichmentProducts() {
    const $rows = $("#wscraper-enrich-rows");
    const $btnB = $("#wscraper-enrich-basic");
    const $btnP = $("#wscraper-enrich-premium");

    $btnB.prop("disabled", true).addClass("btn-disabled");
    $btnP.prop("disabled", true).addClass("btn-disabled");

    ALERTAPRECIO_ENRICH_SETTINGS.products.forEach((p) => {
      const descEscaped = (p.description || "No hay información").replace(/"/g, "&quot;");
      const url = p.url || "";
    
      $rows.append(`
        <tr
          data-id="${p.id}"
          data-description="${p.description}"
          data-title="${p.title}"
          data-url="${url}"
        >
          <th><input type="checkbox" class="enrich-checkbox"></th>
          <td class="col-id">${p.id}</td>
          <td class="col-title">${p.title}</td>
                <td class="col-description">
            ${
              p.description
                ? p.description
                    .replace(/<img[^>]*>/gi, "")
                    .replace(/https?:\/\/[^\s"]+/gi, "")
                    .replace(/<[^>]+>/g, "")
                    .slice(0, 100) + (p.description.length > 100 ? "…" : "")
                : ""
            }
          </td>

          <td class="col-enrich">${p.enrich_score || 0}/10</td>
          <td class="col-seo">${p.seo_score || 0}/10</td>
          <td class="col-url">
            ${
              url
                ? `<a href="${url}" target="_blank" href="url">${
                    url.slice(0, 50) + "…"
                  }</a>`
                : "—"
            }
          </td>
        
        </tr>
      `);
    });

   function updateSelection() {
      const count = $(".enrich-checkbox:checked").length;
const $btnBasic   = $('#wscraper-enrich-basic');
const $btnPremium = $('#wscraper-enrich-premium')
  $btnBasic
    .prop('disabled', count === 0)
    .toggleClass('btn-disabled', count === 0);
  $btnPremium
    .prop('disabled', count === 0)
    .toggleClass('btn-disabled', count === 0);

  $('#wscraper-selected-count').text(count);
  $('#wscraper-selected-cost').text(`${count * 5} Básico / ${count * 10} Premium`);

  const $visible = $tbody.find('.enrich-checkbox');
  const allVisSel = $visible.length > 0
    && $visible.toArray().every(chk => selectedIds.has($(chk).closest('tr').data('id')));
  $masterChk.prop('checked', allVisSel);
}
    $(document)
      .off("change", ".enrich-checkbox")
      .on("change", ".enrich-checkbox", updateSelection);

    $(document)
      .off("change", "#check-all-enrich")
      .on("change", "#check-all-enrich", function () {
        $(".enrich-checkbox").prop("checked", $(this).is(":checked"));
        updateSelection();
      });

    updateSelection();
  }
function initEnrichPagination() {
  const products   = ALERTAPRECIO_ENRICH_SETTINGS.products;
  const perPage    = 5;
  let currentPage  = 1;
  const selectedIds = new Set();            
  const $tbody       = $('#wscraper-enrich-rows');
  const $pagination  = $('#wscraper-enrich-pagination');
  const $btnBasic    = $('#wscraper-enrich-basic');
  const $btnPremium  = $('#wscraper-enrich-premium');
  const $masterChk   = $('#check-all-enrich');

  function updateSelection() {
    const count = selectedIds.size;
    $btnBasic.prop('disabled', count === 0);
    $btnPremium.prop('disabled', count === 0);
    $('#wscraper-selected-count').text(count);
    $('#wscraper-selected-cost').text(`${count * 5} Básico / ${count * 10} Premium`);
    const $visible = $tbody.find('.enrich-checkbox');
    const allVisSel = $visible.length > 0
      && $visible.toArray().every(chk => selectedIds.has(
           $(chk).closest('tr').data('id')
         ));
    $masterChk.prop('checked', allVisSel);
  }

  function bindSelectionEvents() {
    $tbody
      .off('change', '.enrich-checkbox')
      .on('change', '.enrich-checkbox', function() {
        const id = $(this).closest('tr').data('id');
        this.checked ? selectedIds.add(id) : selectedIds.delete(id);
        updateSelection();
      });

    $masterChk
      .off('change')
      .on('change', function() {
        const checked = this.checked;
        $tbody.find('.enrich-checkbox').each(function() {
          $(this).prop('checked', checked);
          const id = $(this).closest('tr').data('id');
          checked ? selectedIds.add(id) : selectedIds.delete(id);
        });
        updateSelection();
      });
  }

  function renderPage(page) {
    currentPage = page;
    $tbody.empty();

    const start     = (page - 1) * perPage;
    const pageItems = products.slice(start, start + perPage);

    pageItems.forEach(p => {
      const rawUrl     = p.url || '';
const displayUrl = rawUrl.length > 50 ? rawUrl.slice(0, 50) + '...' : rawUrl;
      const desc = (p.description || 'No hay información')
        .replace(/<[^>]+>/g, '')
        .slice(0, 100) + (p.description.length > 100 ? '…' : '');
      const checked = selectedIds.has(p.id) ? 'checked' : '';
      $tbody.append(`
        <tr data-id="${p.id}" data-description="${desc}" data-title="${p.title}">
          <th><input type="checkbox" class="enrich-checkbox" ${checked}></th>
          <td>${p.id}</td>
          <td>${p.title}</td>
          <td>${desc}</td>
          <td>${p.enrich_score}/10</td>
          <td>${p.seo_score}/10</td>
    <td>${
  rawUrl
    ? `<a href="${rawUrl}" target="_blank">${displayUrl}</a>`
    : '—'
}</td>
        </tr>
      `);
    });

    renderPagination();
    bindSelectionEvents();
    updateSelection();
  }

  function renderPagination() {
    $pagination.empty();
    const totalPages = Math.ceil(products.length / perPage);
    for (let i = 1; i <= totalPages; i++) {
      $('<button>')
        .text(i)
        .attr('data-page', i)
        .toggleClass('active', i === currentPage)
        .css({ margin: '0 4px', padding: '4px 8px', cursor: 'pointer' })
        .on('click', () => renderPage(i))
        .appendTo($pagination);
    }
  }
  renderPage(1);
}


  function init() {
    const user = getUserData();
    updateUserInfoUI(user);
    bindEventHandlers();
    loadPriceThreshold();
    loadExistingProducts();
    refreshPluginAlerts();

   if (typeof ALERTAPRECIO_ENRICH_SETTINGS !== "undefined") {
        initEnrichPagination();    
        $("#enrich-complete-ok")
          .off("click")
          .on("click", () => location.reload());

        $("#wscraper-enrich-basic")
          .off("click")
          .on("click", () => handleEnrichment("basic", 5));
        $("#wscraper-enrich-premium")
          .off("click")
          .on("click", () => handleEnrichment("premium", 10));
      }
  }

  $(document).ready(init);
  (function ($) {
    function toggleSubmenus() {
      const loggedIn = !!localStorage.getItem("alertaprecio_token");
      if (!loggedIn) {
        $("#toplevel_page_alertaprecio .wp-submenu li").each(function (i) {
          if (i > 0) $(this).hide();
        });
      }
    }
    function init() {
      toggleSubmenus();
    }
    $(document).ready(init);
  })(jQuery);
})(jQuery);
