/**
 * ================================================================
 *  WordAI SEO Metabox Script — FINAL (Canonical Sync + Rank Circles)
 *  ---------------------------------------------------------------
 *  ✅ Circles stay beside labels
 *  ✅ Character counters below inputs
 *  ✅ Canonical auto-syncs with title (manual + AI aware)
 *  ✅ Global refresh handles AI updates cleanly
 * ================================================================
 */
(function ($) {
  "use strict";

  $(document).ready(function () {

    /* -----------------------------------------------------------
     * 0) Cleanup any old misplaced rank circles
     * ----------------------------------------------------------- */
    $('.wordai-seo-field .wordai-seo-rank-circle')
      .not('.wordai-seo-field-top .wordai-seo-rank-circle')
      .remove();

    /* -----------------------------------------------------------
     * 1) Character Counter + Rank Updater
     * ----------------------------------------------------------- */
    function attachCounter($field, maxChars, type) {
      if (!$field.length) return;

      const selector = `.wordai-seo-char-counter[data-type="${type}"]`;
      $field.siblings(selector).remove();
      const $counter = $(
        `<p class="wordai-seo-char-counter" data-type="${type}"><span class="current">0</span> / ${maxChars}</p>`
      );
      $field.after($counter);

      const update = () => {
        const val = $field.val() || "";
        const len = val.length;
        const pct = Math.min((len / maxChars) * 100, 100);

        $counter
          .removeClass("good warning danger")
          .addClass(pct >= 80 ? "good" : pct >= 40 ? "warning" : "danger");
        $counter.find(".current").text(len);

        window.updateSeoRank(type, val, maxChars);
      };

      $field
        .off("input.wordaiSEO keyup.wordaiSEO change.wordaiSEO")
        .on("input.wordaiSEO keyup.wordaiSEO change.wordaiSEO", update);

      update();
    }

    // Force-refresh counters when fields were changed programmatically.
    // It simply triggers the same event your counters listen to.
    function wordaiForceCounterRefresh() {
      $("#wordaiSEOTitle").trigger("input.wordaiSEO");
      $("#wordaiSEOMetaDescription").trigger("input.wordaiSEO");
      // If you ever add a visible counter for keyword, include it here too:
      // $("#wordaiSEOFocusKeyword").trigger("input.wordaiSEO");
    }


    /* -----------------------------------------------------------
     * 2) Rank Circle Visual Handler
     * ----------------------------------------------------------- */
    window.updateSeoRank = function (type, value, maxChars) {
      const $circle = $(`.wordai-seo-field-top .wordai-seo-rank-circle[data-type="${type}"]`).first();
      if (!$circle.length) return;

      const len = (value || "").length;
      let score = 0, state = "poor", text = "0%";

      if (type === "keyword") {
        if (len > 0) {
          state = "good";
          text = "✔";
        }
      } else {
        score = Math.min(Math.round((len / maxChars) * 100), 100);
        if (score >= 80) state = "good";
        else if (score >= 40) state = "average";
        else state = "poor";
        text = `${score}%`;
      }

      $circle.removeClass("poor average good").addClass(state).text(text);
      $circle.addClass("pulse");
      setTimeout(() => $circle.removeClass("pulse"), 700);
    };

    /* -----------------------------------------------------------
     * 3) SERP Preview Updater
     * ----------------------------------------------------------- */
    window.updateSerpPreview = function () {
      const title = $("#wordaiSEOTitle").val() || "";
      const desc = $("#wordaiSEOMetaDescription").val() || "";
      const url = $("#wordaiSEOCannonical").val() || window.location.href;

      $("#wordaiSerpTitle").text(title || "Example Title - WordAI");
      $("#wordaiSerpDesc").text(desc || "Your SEO meta description will appear here...");
      $("#wordaiSerpUrl").text(url);

      $("#wordaiSerpTitle, #wordaiSerpDesc").addClass("flash");
      setTimeout(() => $("#wordaiSerpTitle, #wordaiSerpDesc").removeClass("flash"), 700);
    };

    /* -----------------------------------------------------------
     * 4) Canonical Generator (from title or post)
     * ----------------------------------------------------------- */
    function generateCanonicalFromTitle(title) {
      // ✅ Use localized WordPress base URL instead of location.origin
      // const base = (typeof sftcy_wordai_seo_metabox_script_obj !== "undefined" && sftcy_wordai_seo_metabox_script_obj.base_url)
      //   ? sftcy_wordai_seo_metabox_script_obj.base_url
      //   : window.location.origin + "/";

      let base = (typeof sftcy_wordai_seo_metabox_script_obj !== "undefined" && sftcy_wordai_seo_metabox_script_obj.base_url)
        ? sftcy_wordai_seo_metabox_script_obj.base_url
        : window.location.origin;
      base = base.replace(/\/+$/, ''); // ✅ strip trailing slashes


      if (title && title.trim() !== "") {
        const slug = title
          .toLowerCase()
          .trim()
          .replace(/[^a-z0-9]+/g, "-")
          .replace(/^-+|-+$/g, "");
        // return `${base}${slug}/`;
        return `${base}/${slug}/`;
      } else {
        const postId = $("body").find("#post_ID").val() || "";
        return postId ? `${base}?p=${postId}` : base;
      }
    }

    /* -----------------------------------------------------------
     * 5) Global Master Refresh (used by AI scripts)
     * ----------------------------------------------------------- */
    window.wordaiRefreshSEO = function () {
      const $title = $("#wordaiSEOTitle");
      const $desc = $("#wordaiSEOMetaDescription");
      const $keyword = $("#wordaiSEOFocusKeyword");
      const $canonical = $("#wordaiSEOCannonical");

      if (!$title.length || !$desc.length) return;

      // ✅ Rank updates
      window.updateSeoRank("title", $title.val() || "", 60);
      window.updateSeoRank("description", $desc.val() || "", 160);
      window.updateSeoRank("keyword", $keyword.val() || "", 20);

      // ✅ Canonical auto-sync if not manually edited
      const manuallyEdited = $canonical.data("manual-edit") === true;
      if (!manuallyEdited) {
        const seoTitleVal = $title.val()?.trim();
        const postId = $("#post_ID").val() || "";
        // const base = (typeof sftcy_wordai_seo_metabox_script_obj !== "undefined" && sftcy_wordai_seo_metabox_script_obj.base_url)? sftcy_wordai_seo_metabox_script_obj.base_url : window.location.origin + "/";
        let base = (typeof sftcy_wordai_seo_metabox_script_obj !== "undefined" && sftcy_wordai_seo_metabox_script_obj.base_url)? sftcy_wordai_seo_metabox_script_obj.base_url : window.location.origin;
        base = base.replace(/\/+$/, ''); // ✅ normalize, remove trailing slash

        let newCanonical = "";

        if (seoTitleVal) {
          const slug = seoTitleVal
            .toLowerCase()
            .replace(/[^a-z0-9]+/g, "-")
            .replace(/^-+|-+$/g, "");
          newCanonical = `${base}/${slug}/`;
        } else {
          const postTitle = $("#title").val()?.trim();
          if (postTitle) {
            const slug = postTitle
              .toLowerCase()
              .replace(/[^a-z0-9]+/g, "-")
              .replace(/^-+|-+$/g, "");
            newCanonical = `${base}/${slug}/`;
          } else if (postId) {
            newCanonical = `${base}/?p=${postId}`;
          } else {
            newCanonical = window.location.href;
          }
        }

        console.log("✅ Canonical refreshed:", newCanonical);
        $canonical.val(newCanonical);
      }

      // 🔁 NEW: force counters to recalc using the same listeners you already attached
      wordaiForceCounterRefresh();

      // Keep SERP preview update
      window.updateSerpPreview();
    };

    /* -----------------------------------------------------------
     * 6) Initialize counters and keyword circle
     * ----------------------------------------------------------- */
    attachCounter($("#wordaiSEOTitle"), 60, "title");
    attachCounter($("#wordaiSEOMetaDescription"), 160, "description");

    const $kw = $("#wordaiSEOFocusKeyword");
    if ($kw.length) {
      $kw
        .off("input.wordaiSEO keyup.wordaiSEO change.wordaiSEO")
        .on("input.wordaiSEO keyup.wordaiSEO change.wordaiSEO", function () {
          window.updateSeoRank("keyword", $(this).val() || "", 20);
        });
      window.updateSeoRank("keyword", $kw.val() || "", 20);
    }

    /* -----------------------------------------------------------
     * 7) Canonical Live Update on Manual Title Edit
     * ----------------------------------------------------------- */
    const $canonical = $("#wordaiSEOCannonical");
    $canonical.on("input change", function () {
      $(this).data("manual-edit", true); // Mark as manually edited
    });

    $("#wordaiSEOTitle").on("input change keyup", function () {
      const titleVal = $(this).val();
      if ($canonical.data("manual-edit") !== true) {
        const newCanonical = generateCanonicalFromTitle(titleVal);
        $canonical.val(newCanonical);
        console.log("🔄 Canonical updated from manual title input:", newCanonical);
        window.updateSerpPreview();
      }
    });

    /* -----------------------------------------------------------
     * 8) SERP View Toggle
     * ----------------------------------------------------------- */
    $(".wordai-seo-serp-preview .serp-view-toggle button").on("click", function () {
      const view = $(this).data("view");
      $(this).addClass("active").siblings().removeClass("active");
      const $preview = $(".wordai-seo-serp-preview .serp-preview-box");
      $preview.toggleClass("mobile-view", view === "mobile");
    });

    /* -----------------------------------------------------------
     * 9) Accordion Collapse
     * ----------------------------------------------------------- */
    $(".wordai-seo-header .toggle-seo-panel").on("click", function () {
      const $panel = $(".wordai-seo-body");
      const isOpen = $(this).attr("aria-expanded") === "true";
      $(this)
        .attr("aria-expanded", !isOpen)
        .find(".dashicons")
        .toggleClass("dashicons-arrow-up-alt2 dashicons-arrow-down-alt2");
      $panel.slideToggle(250);
    });

    /* -----------------------------------------------------------
     * 10) Live SERP Updates on Any Field Change
     * ----------------------------------------------------------- */
    $("#wordaiSEOTitle, #wordaiSEOMetaDescription, #wordaiSEOCannonical")
      .on("input change keyup", function () {
        window.updateSerpPreview();
      });

    // Initial setup
    window.updateSerpPreview();
  });


  /* -----------------------------------------------------------
   * 11) AJAX Helpers
   *     SEO Meta FieldS - Check/Uncheck SEO Social Meta Tags
   * ----------------------------------------------------------- */
  /* global ajaxurl, wp, sftcy_wordai_seo_metabox_script_obj */

    // Get nonce from hidden field (rendered in metabox)
    function getNonce() {
      // var f = $('#scwordai_wpnonce_field, input[name="scwordai_wpnonce"]');
      return sftcy_wordai_seo_metabox_script_obj.nonce;
    }

    // Get current post ID (Block Editor or Classic)
    function getCurrentPostId() {
      // Block Editor
      if (window.wp && wp.data && wp.data.select) {
        var id = wp.data.select('core/editor') && wp.data.select('core/editor').getCurrentPostId();
        if (id) return parseInt(id, 10);
      }
      // Classic fallback (hidden input)
      var manual = $('#sc-wordai-current-post-id').val();
      if (manual) return parseInt(manual, 10);
      return 0;
    }

    // AJAX helpers
    function ajaxCheck(postId){
      return $.post(ajaxurl, {
        action: 'sc_wordai_check_seo_social_meta_tags',
        security: getNonce(),
        post_id: postId
      });
    }
    function ajaxToggle(postId, op){
      return $.post(ajaxurl, {
        action: 'sc_wordai_add_remove_seo_social_meta_tags',
        security: getNonce(),
        post_id: postId,
        operation: op // 'add' | 'remove'
      });
    }

    // Sync UI checkbox with backend list
    function syncCheckbox(checked) {
      $('#sc-wordai-enable-social-meta').prop('checked', !!checked);
    }

    // Ensure default-on for new posts: as soon as postId exists, add it once if not present.
    function ensureDefaultOn(postId){
      ajaxCheck(postId).done(function(resp){
        if (resp && resp.status === 'success') {
          if (!resp.allowed) {
            ajaxToggle(postId, 'add'); // silently add
          }
          syncCheckbox(true);
        }
      });
    }

    // Init: wait until postId exists (Block Editor creates it after first autosave)
    function init(){
      var $cb = $('#sc-wordai-enable-social-meta');
      if (!$cb.length) return;

      var didBind = false;
      function bindHandlers(postId){
        if (didBind) return;
        didBind = true;

        // Initial sync with server
        ajaxCheck(postId).done(function(resp){
          if (resp && resp.status === 'success') {
            syncCheckbox(!!resp.allowed);
          }
        });

        // User toggle → add/remove
        $cb.on('change', function(){
          var enable = $(this).is(':checked');
          ajaxToggle(postId, enable ? 'add' : 'remove');
        });
      }

      // Try immediate get
      var pid = getCurrentPostId();
      if (pid > 0) {
        // For new posts, default ON (will add if not already allowed)
        ensureDefaultOn(pid);
        bindHandlers(pid);
        return;
      }

      // Block editor: subscribe to postId appearance
      if (window.wp && wp.data && wp.data.subscribe) {
        var unsub = wp.data.subscribe(function(){
          var newId = getCurrentPostId();
          if (newId > 0) {
            ensureDefaultOn(newId);
            bindHandlers(newId);
            if (unsub) unsub(); // stop listening
          }
        });
      }
    }

    $(document).ready(init);
  



})(jQuery);
