/**
 * Virtual Files Settings JavaScript
 */

jQuery(document).ready(function ($) {
  "use strict"

  // Initialize settings page
  initSettingsPage()

  /**
   * Initialize settings page functionality
   */
  function initSettingsPage() {
    // Handle settings form submission (remove any existing handlers first to prevent duplicates)
    $("#virtual-files-settings-form")
      .off("submit")
      .on("submit", function (e) {
        e.preventDefault()
        saveSettings()
      })

    // Handle flush rewrite rules
    $("#vf-flush-rewrite")
      .off("click")
      .on("click", function (e) {
        e.preventDefault()
        e.stopPropagation()
        flushRewriteRules()
      })

    // Handle reset plugin data
    $("#vf-reset-plugin-data")
      .off("click")
      .on("click", function (e) {
        e.preventDefault()
        e.stopPropagation()
        resetPluginData()
      })

    // Handle clear Freemius data
    $("#vf-clear-freemius-data")
      .off("click")
      .on("click", function (e) {
        e.preventDefault()
        e.stopPropagation()
        clearFreemiusData()
      })

    // Handle backup creation
    $("#vf-export-files")
      .off("click")
      .on("click", function (e) {
        e.preventDefault()
        e.stopPropagation()
        createBackup()
      })

    // Handle backup restore
    $("#vf-import-files-button")
      .off("click")
      .on("click", function (e) {
        e.preventDefault()
        e.stopPropagation()
        $("#vf-import-files").click()
      })

    $("#vf-import-files")
      .off("change")
      .on("change", function (e) {
        const file = e.target.files[0]
        if (file) {
          // Show selected file name
          $(".vf-file-selected").text(file.name).show()

          // Update button text
          $("#vf-import-files-button").text("Change File")

          // Automatically start restore
          restoreBackup(file)
        }
      })

    // Handle advanced settings toggle
    $(".vf-advanced-toggle").on("click", function () {
      toggleAdvancedSettings($(this))
    })

    // Handle file type checkboxes
    $(".vf-file-type-checkbox").on("change", function () {
      updateFileTypesList()
    })

    // Handle numeric input validation
    $(".vf-numeric-input").on("input", function () {
      validateNumericInput($(this))
    })

    // Handle range inputs
    $(".vf-range-input").on("input", function () {
      updateRangeValue($(this))
    })

    // Initialize tooltips if available
    initTooltips()

    // Handle tabs if present
    initTabs()

    // Handle confirmation dialogs
    initConfirmations()

    // Initialize extension chips for all users (both free and pro)
    initExtensionChips()

    // Initialize AI Settings logic
    initAiSettings()

    // Initialize Pro features if Pro user
    if (typeof intentdeepVfData !== "undefined" && intentdeepVfData.isPro) {
      initCacheManagement()
      initProFeatures()
    }
  }

  /**
   * Initialize AI Settings dynamic UI
   */
  function initAiSettings() {
    const $providerSelect = $("#vf-ai-provider")
    if (!$providerSelect.length) return

    const models = {
      openrouter: [
        { id: "openai/gpt-5.2", name: "OpenAI: GPT-5.2" },
        { id: "openai/gpt-5-mini", name: "OpenAI: GPT-5 Mini" },
        { id: "openai/gpt-4o", name: "OpenAI: GPT-4o" },
        { id: "openai/gpt-4o-mini", name: "OpenAI: GPT-4o Mini" },
        {
          id: "anthropic/claude-sonnet-4.6",
          name: "Anthropic: Claude Sonnet 4.6",
        },
        { id: "anthropic/claude-opus-4.6", name: "Anthropic: Claude Opus 4.6" },
        {
          id: "anthropic/claude-haiku-4.6",
          name: "Anthropic: Claude Haiku 4.6",
        },
        {
          id: "google/gemini-3.1-pro-preview",
          name: "Google: Gemini 3.1 Pro Preview",
        },
        {
          id: "google/gemini-3-flash-preview",
          name: "Google: Gemini 3 Flash Preview",
        },
        { id: "google/gemini-2.5-flash", name: "Google: Gemini 2.5 Flash" },
        {
          id: "google/gemini-2.5-flash-lite",
          name: "Google: Gemini 2.5 Flash-Lite",
        },
        { id: "z-ai/glm-4.7", name: "Z.AI: GLM-4.7" },
        { id: "z-ai/glm-4.6", name: "Z.AI: GLM-4.6" },
        { id: "z-ai/glm-4.5", name: "Z.AI: GLM-4.5" },
        { id: "moonshotai/kimi-k2-0905", name: "Moonshot: Kimi K2" },
        {
          id: "moonshotai/kimi-k2-thinking",
          name: "Moonshot: Kimi K2 Thinking",
        },
        { id: "qwen/qwen3-32b", name: "Qwen: Qwen3 32B" },
        { id: "qwen/qwen3-14b", name: "Qwen: Qwen3 14B" },
        { id: "x-ai/grok-code-fast-1", name: "xAI: Grok Code Fast" },
        { id: "x-ai/grok-4-fast", name: "xAI: Grok 4 Fast" },
        { id: "x-ai/grok-3-mini", name: "xAI: Grok 3 Mini" },
      ],
      openai: [
        { id: "gpt-5.2", name: "GPT-5.2" },
        { id: "gpt-5-mini", name: "GPT-5 Mini" },
        { id: "gpt-5-nano", name: "GPT-5 Nano" },
        { id: "gpt-4o", name: "GPT-4o" },
      ],
      anthropic: [
        { id: "claude-sonnet-4-5-20250929", name: "Claude Sonnet 4.5" },
        { id: "claude-haiku-4-5-20251001", name: "Claude Haiku 4.5" },
        { id: "claude-opus-4-5-20251101", name: "Claude Opus 4.5" },
      ],
      google: [
        { id: "gemini-3.1-pro-preview", name: "Gemini 3.1 Pro Preview" },
        { id: "gemini-3-pro-preview", name: "Gemini 3 Pro Preview" },
        { id: "gemini-3-flash-preview", name: "Gemini 3 Flash Preview" },
        { id: "gemini-2.5-flash", name: "Gemini 2.5 Flash" },
        { id: "gemini-2.5-flash-lite", name: "Gemini 2.5 Flash-Lite" },
        { id: "gemini-2.5-pro", name: "Gemini 2.5 Pro" },
        { id: "gemini-2.0-flash", name: "Gemini 2.0 Flash" },
        { id: "gemini-2.0-flash-lite", name: "Gemini 2.0 Flash-Lite" },
      ],
    }

    const $modelSelect = $("#vf-ai-model")
    const currentModel = $modelSelect.data("current")

    // Handle Provider Change
    $providerSelect.on("change", function () {
      const provider = $(this).val()

      // Show/Hide API Key fields
      $(".vf-api-key-row").hide()
      $('.vf-api-key-row[data-provider="' + provider + '"]').show()

      // Update Model Dropdown
      $modelSelect.empty()
      if (models[provider]) {
        models[provider].forEach(function (model) {
          const isSelected = model.id === currentModel ? "selected" : ""
          $modelSelect.append(
            `<option value="${model.id}" ${isSelected}>${model.name}</option>`,
          )
        })
      }
    })

    // Trigger change on init
    $providerSelect.trigger("change")
  }

  /**
   * Save settings via AJAX
   */
  let isSaving = false

  function saveSettings() {
    // Prevent double-click / double-submission
    if (isSaving) {
      console.warn(
        "Settings save already in progress, ignoring duplicate request",
      )
      return
    }

    isSaving = true
    const $form = $("#virtual-files-settings-form")
    const $button = $form.find('button[type="submit"]')
    const originalText = $button.text()

    // Immediately disable button to prevent further clicks
    $button.prop("disabled", true).addClass("vf-saving")

    // Debug: Check if form exists
    if (!$form.length) {
      console.error("Settings form not found")
      showNotice("Settings form not found", "error")
      $button.prop("disabled", false).removeClass("vf-saving")
      isSaving = false
      return
    }

    // Debug: Check nonce
    const nonce = $("#vf-settings-nonce").val()
    if (!nonce) {
      console.error("Nonce not found")
      showNotice("Security nonce not found", "error")
      $button.prop("disabled", false).removeClass("vf-saving")
      isSaving = false
      return
    }

    // Validate form before submission
    if (!validateSettingsForm()) {
      $button.prop("disabled", false).removeClass("vf-saving")
      isSaving = false
      return
    }

    // Show loading state
    showLoadingState($button, "Saving...")

    // Serialize form data
    const formData = new FormData($form[0])
    formData.append("action", "intentdeep_vf_save_options")
    formData.append("nonce", nonce)

    // Debug: Log form data
    // console.log("Saving settings with data:", Object.fromEntries(formData))

    $.ajax({
      url:
        typeof intentdeepVfData !== "undefined" && intentdeepVfData.ajaxUrl
          ? intentdeepVfData.ajaxUrl
          : ajaxurl,
      type: "POST",
      data: formData,
      processData: false,
      contentType: false,
      success: function (response) {
        // console.log("Settings save response:", response)

        if (response.success) {
          // Show success notification
          showBetterNotice("Settings saved successfully!", "success", 5000)

          // Update any live statistics
          if (response.data.stats) {
            updateStatistics(response.data.stats)
          }

          // Show any additional messages
          if (response.data.messages) {
            response.data.messages.forEach(function (message) {
              showBetterNotice(message.text, message.type || "info", 5000)
            })
          }

          // Refresh cache stats if cache settings were changed
          if (
            typeof intentdeepVfData !== "undefined" &&
            intentdeepVfData.isPro
          ) {
            setTimeout(loadCacheStats, 1000)
          }

          // Optional: Brief flash to indicate success
          $form.addClass("save-success")
          setTimeout(() => {
            $form.removeClass("save-success")
          }, 1000)
        } else {
          console.error("Settings save failed:", response.data)
          showBetterNotice(
            response.data.message || "Error saving settings",
            "error",
            7000,
          )
        }
      },
      error: function (xhr, status, error) {
        console.error("Settings save XHR error:", {
          status: status,
          error: error,
          responseText: xhr.responseText,
          statusCode: xhr.status,
        })

        let errorMessage =
          "An error occurred while saving settings. Please try again."
        if (xhr.responseText) {
          try {
            const response = JSON.parse(xhr.responseText)
            errorMessage = response.data.message || errorMessage
          } catch (e) {
            console.error("Could not parse error response")
          }
        }

        showBetterNotice(errorMessage, "error", 7000)
      },
      complete: function () {
        // Re-enable button regardless of success or error
        hideLoadingState($button, originalText)
        $button.prop("disabled", false).removeClass("vf-saving")

        // Reset saving flag only here, after everything is done
        isSaving = false
      },
    })
  }

  /**
   * Flush rewrite rules via AJAX
   */
  function flushRewriteRules() {
    const $button = $("#vf-flush-rewrite")
    const originalText = $button.text()

    showLoadingState($button, "Flushing...")

    $.ajax({
      url:
        typeof intentdeepVfData !== "undefined" && intentdeepVfData.ajaxUrl
          ? intentdeepVfData.ajaxUrl
          : ajaxurl,
      type: "POST",
      data: {
        action: "intentdeep_vf_flush_rewrite",
        nonce: $("#vf-settings-nonce").val(),
      },
      success: function (response) {
        if (response.success) {
          showBetterNotice(
            "Rewrite rules flushed successfully!",
            "success",
            5000,
          )

          // Update flush button status
          $button.removeClass("button-primary").addClass("button-secondary")
          setTimeout(() => {
            $button.removeClass("button-secondary").addClass("button-primary")
          }, 30000) // Re-enable after 30 seconds
        } else {
          showBetterNotice(
            response.data.message || "Error flushing rewrite rules",
            "error",
            7000,
          )
        }
      },
      error: function () {
        showBetterNotice(
          "An error occurred while flushing rewrite rules",
          "error",
          7000,
        )
      },
      complete: function () {
        hideLoadingState($button, originalText)
      },
    })
  }

  /**
   * Reset all plugin data
   */
  function resetPluginData() {
    if (
      !confirm(
        "⚠️ WARNING: This will permanently delete ALL virtual files, settings, and plugin data. This action CANNOT be undone!\n\nAre you absolutely sure you want to proceed?",
      )
    ) {
      return
    }

    const $button = $("#vf-reset-plugin-data")
    const originalText = $button.text()

    showLoadingState($button, "Resetting...")

    $.ajax({
      url:
        typeof intentdeepVfData !== "undefined" && intentdeepVfData.ajaxUrl
          ? intentdeepVfData.ajaxUrl
          : ajaxurl,
      type: "POST",
      data: {
        action: "intentdeep_vf_reset_plugin_data",
        nonce:
          typeof intentdeepVfData !== "undefined" && intentdeepVfData.nonce
            ? intentdeepVfData.nonce
            : $("#vf-settings-nonce").val(),
      },
      success: function (response) {
        if (response.success) {
          const summary = response.data.summary || {}
          const message = `Plugin data has been reset successfully!\n\nDeleted:\n- ${summary.posts || 0} virtual files\n- ${summary.post_meta || 0} post meta entries\n- ${summary.options || 0} options\n- ${summary.transients || 0} transients`

          showBetterNotice(message.replace(/\n/g, "<br>"), "success", 10000)

          // Update stats in the sidebar
          if (response.data.stats) {
            updateStats(response.data.stats)
          }

          // Reload page after 2 seconds to reflect changes
          setTimeout(() => {
            window.location.reload()
          }, 2000)
        } else {
          showBetterNotice(
            response.data.message || "Error resetting plugin data",
            "error",
            7000,
          )
        }
      },
      error: function () {
        showBetterNotice(
          "An error occurred while resetting plugin data",
          "error",
          7000,
        )
      },
      complete: function () {
        hideLoadingState($button, originalText)
      },
    })
  }

  /**
   * Clear Freemius license data
   */
  function clearFreemiusData() {
    if (
      !confirm(
        "⚠️ WARNING: This will remove all Virtual Files license and activation data from Freemius.\n\nThis is for TESTING ONLY. Use this to verify that only Virtual Files data is removed without affecting other Freemius plugins.\n\nAre you sure you want to proceed?",
      )
    ) {
      return
    }

    const $button = $("#vf-clear-freemius-data")
    const originalText = $button.text()

    showLoadingState($button, "Clearing...")

    $.ajax({
      url:
        typeof intentdeepVfData !== "undefined" && intentdeepVfData.ajaxUrl
          ? intentdeepVfData.ajaxUrl
          : ajaxurl,
      type: "POST",
      data: {
        action: "intentdeep_vf_clear_freemius_data",
        nonce:
          typeof intentdeepVfData !== "undefined" && intentdeepVfData.nonce
            ? intentdeepVfData.nonce
            : $("#vf-settings-nonce").val(),
      },
      success: function (response) {
        if (response.success) {
          const summary = response.data.summary || {}
          const before = response.data.before || {}
          const after = response.data.after || {}

          let message =
            "Freemius data has been cleared successfully!\n\nRemoved:\n"
          message += `- ${summary.fs_accounts_entries || 0} fs_accounts entries\n`
          message += `- ${summary.fs_api_cache_entries || 0} API cache entries\n`
          message += `- ${summary.fs_cache_options || 0} cache options\n`
          message += `- ${summary.fs_active_plugins_entries || 0} active plugin entries\n\n`
          message += `Verification:\n`
          message += `- Before: ${JSON.stringify(before)}\n`
          message += `- After: ${JSON.stringify(after)}`

          showBetterNotice(message.replace(/\n/g, "<br>"), "success", 15000)
        } else {
          showBetterNotice(
            response.data.message || "Error clearing Freemius data",
            "error",
            7000,
          )
        }
      },
      error: function () {
        showBetterNotice(
          "An error occurred while clearing Freemius data",
          "error",
          7000,
        )
      },
      complete: function () {
        hideLoadingState($button, originalText)
      },
    })
  }

  /**
   * Create backup of virtual files (Pro feature)
   */
  function createBackup() {
    if (!isProFeature("export")) {
      return
    }

    const $button = $("#vf-export-files")
    const originalText = $button.text()

    showLoadingState($button, "Creating backup...")

    // Create download link
    const exportUrl =
      typeof intentdeepVfData !== "undefined" && intentdeepVfData.ajaxUrl
        ? intentdeepVfData.ajaxUrl +
          "?action=intentdeep_vf_export&nonce=" +
          $("#vf-settings-nonce").val()
        : ajaxurl +
          "?action=intentdeep_vf_export&nonce=" +
          $("#vf-settings-nonce").val()

    // Create hidden iframe to trigger download
    const $iframe = $('<iframe style="display:none;"></iframe>')
    $("body").append($iframe)

    // Handle iframe load/error events
    $iframe.on("load", function () {
      setTimeout(() => {
        $iframe.remove()
        hideLoadingState($button, originalText)
        showBetterNotice(
          "Backup created successfully! Check your downloads folder.",
          "success",
          6000,
        )
      }, 1000)
    })

    $iframe.on("error", function () {
      $iframe.remove()
      hideLoadingState($button, originalText)
      showBetterNotice("Backup failed. Please try again.", "error", 7000)
    })

    // Start the download
    $iframe.attr("src", exportUrl)

    // Fallback timeout in case iframe doesn't load
    setTimeout(() => {
      if ($("#vf-export-files").hasClass("vf-loading")) {
        $iframe.remove()
        hideLoadingState($button, originalText)
        showBetterNotice(
          "Backup created successfully! Check your downloads folder.",
          "success",
          6000,
        )
      }
    }, 3000)
  }

  /**
   * Restore backup of virtual files (Pro feature)
   */
  function restoreBackup(file) {
    if (!file) return

    if (!isProFeature("import")) {
      // Reset file input
      $("#vf-import-files").val("")
      $(".vf-file-selected").hide()
      $("#vf-import-files-button").text("Choose Backup File")
      return
    }

    const $importButton = $("#vf-import-files-button")
    const originalLabel = $importButton.text()

    // Validate file type
    const allowedTypes = [
      "application/zip",
      "application/x-zip-compressed",
      "text/plain",
      "application/json",
    ]
    if (
      !allowedTypes.includes(file.type) &&
      !file.name.match(/\.(zip|json|txt)$/i)
    ) {
      showBetterNotice(
        "Please select a valid file (ZIP, JSON, or TXT)",
        "error",
        7000,
      )
      // Reset file input
      $("#vf-import-files").val("")
      $(".vf-file-selected").hide()
      $importButton.text("Choose Backup File")
      return
    }

    // Validate file size (max 10MB)
    const maxSize = 10 * 1024 * 1024 // 10MB
    if (file.size > maxSize) {
      showBetterNotice("File size must be less than 10MB", "error", 7000)
      // Reset file input
      $("#vf-import-files").val("")
      $(".vf-file-selected").hide()
      $importButton.text("Choose Backup File")
      return
    }

    // Confirm restore
    if (
      !confirm(
        `Restore backup from "${file.name}"?\n\nThis will add virtual files from the backup to your site. Existing files with the same name will be skipped.`,
      )
    ) {
      // Reset file input if user cancels
      $("#vf-import-files").val("")
      $(".vf-file-selected").hide()
      $importButton.text("Choose Backup File")
      return
    }

    // Show progress
    showLoadingState($importButton, "Restoring backup...")
    showProgress(0)

    const formData = new FormData()
    formData.append("action", "intentdeep_vf_import")
    formData.append("nonce", $("#vf-settings-nonce").val())
    formData.append("import_file", file)

    $.ajax({
      url:
        typeof intentdeepVfData !== "undefined" && intentdeepVfData.ajaxUrl
          ? intentdeepVfData.ajaxUrl
          : ajaxurl,
      type: "POST",
      data: formData,
      processData: false,
      contentType: false,
      xhr: function () {
        const xhr = new window.XMLHttpRequest()
        xhr.upload.addEventListener(
          "progress",
          function (e) {
            if (e.lengthComputable) {
              const percentComplete = (e.loaded / e.total) * 100
              showProgress(percentComplete)
            }
          },
          false,
        )
        return xhr
      },
      success: function (response) {
        hideProgress()

        // Reset file input
        $("#vf-import-files").val("")
        $(".vf-file-selected").hide()
        $importButton.text("Choose Backup File")

        if (response.success) {
          showBetterNotice(
            response.data.message || "Backup restored successfully!",
            "success",
            6000,
          )

          // Update statistics
          if (response.data.stats) {
            updateStatistics(response.data.stats)
          }

          // Show import summary
          if (response.data.summary) {
            showImportSummary(response.data.summary)
          }

          // Reload page after a delay to show new files
          setTimeout(() => location.reload(), 2000)
        } else {
          showBetterNotice(
            response.data.message || "Error importing files",
            "error",
            7000,
          )
        }
      },
      error: function (xhr, status) {
        hideProgress()
        console.error("Import error:", status)

        // Reset file input
        $("#vf-import-files").val("")
        $(".vf-file-selected").hide()
        $importButton.text("Choose Backup File")

        let errorMessage = "An error occurred while importing files"
        if (xhr.responseText) {
          try {
            const response = JSON.parse(xhr.responseText)
            errorMessage = response.data.message || errorMessage
          } catch (e) {
            console.error("Could not parse error response")
          }
        }
        showBetterNotice(errorMessage, "error", 7000)
      },
      complete: function () {
        hideLoadingState($importButton, originalLabel)
      },
    })
  }

  /**
   * Toggle advanced settings visibility
   */
  function toggleAdvancedSettings($button) {
    const $advancedSettings = $(".vf-advanced-settings")
    const isVisible = $advancedSettings.is(":visible")

    $advancedSettings.slideToggle(300)
    $button.text(
      isVisible ? "Show Advanced Settings" : "Hide Advanced Settings",
    )

    // Save preference
    $.post(ajaxurl, {
      action: "intentdeep_vf_save_preference",
      preference: "advanced_settings_visible",
      value: !isVisible,
      nonce: $("#vf-settings-nonce").val(),
    })
  }

  /**
   * Update file types list based on checkboxes
   */
  function updateFileTypesList() {
    const $checkboxes = $(".vf-file-type-checkbox:checked")
    const extensions = []

    $checkboxes.each(function () {
      extensions.push($(this).val())
    })

    $("#vf-allowed-extensions-list").val(extensions.join(", "))
  }

  /**
   * Validate numeric input
   */
  function validateNumericInput($input) {
    const value = parseInt($input.val())
    const min = parseInt($input.attr("min")) || 0
    const max = parseInt($input.attr("max")) || Infinity

    if (isNaN(value) || value < min) {
      $input.val(min)
    } else if (value > max) {
      $input.val(max)
    }
  }

  /**
   * Update range input value display
   */
  function updateRangeValue($input) {
    const $valueDisplay = $input.siblings(".vf-range-value")
    if ($valueDisplay.length) {
      $valueDisplay.text($input.val())
    }
  }

  /**
   * Initialize tooltips
   */
  function initTooltips() {
    if (typeof $.fn.tooltipster === "undefined") {
      return
    }

    $(".vf-tooltip").tooltipster({
      theme: ["tooltipster-borderless", "tooltipster-shadow"],
      contentAsHTML: true,
      maxWidth: 300,
      delay: 200,
    })
  }

  /**
   * Initialize tabs functionality
   */
  function initTabs() {
    $(".vf-tabs").on("click", ".vf-tab", function (e) {
      e.preventDefault()

      const $tab = $(this)
      const $target = $($tab.attr("href"))

      // Update active states
      $(".vf-tab").removeClass("active")
      $tab.addClass("active")

      $(".vf-tab-pane").removeClass("active")
      $target.addClass("active")

      // Save active tab preference
      $.post(ajaxurl, {
        action: "intentdeep_vf_save_preference",
        preference: "active_tab",
        value: $tab.data("tab"),
        nonce: $("#vf-settings-nonce").val(),
      })
    })
  }

  /**
   * Initialize confirmation dialogs
   */
  function initConfirmations() {
    // Dangerous actions
    $(".vf-dangerous-action").on("click", function (e) {
      const message =
        $(this).data("confirm") ||
        "Are you sure you want to perform this action?"
      if (!confirm(message)) {
        e.preventDefault()
        return false
      }
    })

    // Reset settings
    $("#vf-reset-settings")
      .off("click")
      .on("click", function (e) {
        if (
          !confirm(
            "This will reset all settings to their default values. This action cannot be undone. Are you sure?",
          )
        ) {
          e.preventDefault()
          e.stopPropagation()
          return false
        }
      })
  }

  /**
   * Validate settings form before submission
   */
  function validateSettingsForm() {
    let isValid = true
    const errors = []

    // console.log("Validating settings form...")

    // Validate required fields (only those with vf-required class)
    $(".vf-required").each(function () {
      const $field = $(this)
      const value = $field.val()
      if (!value || value.trim() === "") {
        isValid = false
        const label =
          $field.prev("label").text() || $field.attr("name") || "Required field"
        errors.push(label + " is required")
        $field.addClass("error")
        console.error(
          "Validation failed for required field:",
          $field.attr("name"),
        )
      } else {
        $field.removeClass("error")
      }
    })

    // Validate email fields
    $(".vf-email").each(function () {
      const $field = $(this)
      const email = $field.val()
      if (email && !isValidEmail(email)) {
        isValid = false
        const label =
          $field.prev("label").text() || $field.attr("name") || "Email field"
        errors.push(label + " must be a valid email address")
        $field.addClass("error")
        console.error("Validation failed for email field:", email)
      }
    })

    // Validate numeric fields
    $('input[type="number"]').each(function () {
      const $field = $(this)
      const value = $field.val()
      const min = parseFloat($field.attr("min"))
      const max = parseFloat($field.attr("max"))

      if (value && !isNaN(value)) {
        const numValue = parseFloat(value)
        if (!isNaN(min) && numValue < min) {
          isValid = false
          errors.push($field.attr("name") + " must be at least " + min)
          console.error("Validation failed: number too small", numValue, min)
        }
        if (!isNaN(max) && numValue > max) {
          isValid = false
          errors.push($field.attr("name") + " must be no more than " + max)
          console.error("Validation failed: number too large", numValue, max)
        }
      }
    })

    // console.log("Validation result:", isValid, "errors:", errors)

    // Show validation errors only if there are any
    if (!isValid && errors.length > 0) {
      showNotice(
        "Please fix the following errors:\n" + errors.join("\n"),
        "error",
      )
    }

    return isValid
  }

  /**
   * Check if feature requires Pro version
   */
  function isProFeature(feature) {
    if (typeof intentdeepVfData !== "undefined" && intentdeepVfData.isPro) {
      return true
    }

    const featureMessages = {
      export: "Export is a Pro feature. Would you like to upgrade?",
      import: "Import is a Pro feature. Would you like to upgrade?",
      analytics: "Analytics is a Pro feature. Would you like to upgrade?",
      caching: "Advanced caching is a Pro feature. Would you like to upgrade?",
    }

    if (
      confirm(
        featureMessages[feature] ||
          "This is a Pro feature. Would you like to upgrade?",
      )
    ) {
      if (typeof FS !== "undefined") {
        FS.upgrade(true)
      }
    }

    return false
  }

  /**
   * Show loading state on a button
   */
  function showLoadingState($button, text) {
    const originalText = $button.text()
    $button.data("original-text", originalText)
    $button.prop("disabled", true).addClass("vf-loading vf-saving").html(text)

    // Add subtle loading animation to the form
    $button.closest("form").addClass("vf-form-loading")
  }

  /**
   * Hide loading state on a button
   */
  function hideLoadingState($button, text) {
    if (text) {
      $button.text(text)
    } else {
      $button.text($button.data("original-text") || $button.text())
    }
    $button.prop("disabled", false).removeClass("vf-loading vf-saving")

    // Remove loading animation from the form
    $button.closest("form").removeClass("vf-form-loading")
  }

  /**
   * Show progress bar
   */
  function showProgress(percent) {
    let $progress = $(".vf-progress")
    if (!$progress.length) {
      $progress = $(
        '<div class="vf-progress"><div class="vf-progress-bar"></div></div>',
      )
      $(".vf-import-export").after($progress)
    }

    $progress.find(".vf-progress-bar").css("width", percent + "%")
    $progress.show()
  }

  /**
   * Hide progress bar
   */
  function hideProgress() {
    $(".vf-progress").fadeOut(() => $(".vf-progress").remove())
  }

  /**
   * Update statistics display
   */
  function updateStatistics(stats) {
    $.each(stats, function (key, value) {
      const $stat = $(".vf-stat-" + key + " .number")
      if ($stat.length) {
        // Don't format "Unlimited" with toLocaleString
        if (value === "Unlimited" || value === "unlimited") {
          $stat.text("Unlimited")
        } else {
          $stat.text(value.toLocaleString())
        }
      }
    })
  }

  /**
   * Show import summary
   */
  function showImportSummary(summary) {
    const $summary = $(`
            <div class="vf-notice success">
                <h4>Import Summary</h4>
                <ul>
                    <li>Files processed: ${summary.processed}</li>
                    <li>Files imported: ${summary.imported}</li>
                    <li>Files skipped: ${summary.skipped}</li>
                    ${summary.errors ? `<li>Errors: ${summary.errors}</li>` : ""}
                </ul>
            </div>
        `)

    $(".virtual-files-settings h1").after($summary)
    setTimeout(() => $summary.fadeOut(() => $summary.remove()), 10000)
  }

  /**
   * Show admin notice
   */
  function showNotice(message, type) {
    const $notice = $(`
            <div class="vf-notice ${type}">
                <p>${message}</p>
                <button type="button" class="notice-dismiss"><span class="screen-reader-text">Dismiss this notice.</span></button>
            </div>
        `)

    $(".virtual-files-settings h1").after($notice)

    // Auto-hide success notices after 5 seconds
    if (type === "success") {
      setTimeout(() => $notice.fadeOut(() => $notice.remove()), 5000)
    }

    // Handle dismiss
    $notice.on("click", ".notice-dismiss", function () {
      $notice.fadeOut(() => $notice.remove())
    })
  }

  /**
   * Show better notification (bottom right corner)
   */
  function showBetterNotice(message, type = "info", duration = 3000) {
    // Create notification element with progress bar
    const $notification = $(`
            <div class="vf-better-notice vf-better-notice--${type}">
                <div class="vf-better-notice__content">
                    <div class="vf-better-notice__icon">
                        ${type === "success" ? "✓" : type === "error" ? "✕" : type === "warning" ? "⚠" : "ℹ"}
                    </div>
                    <div class="vf-better-notice__message">${message}</div>
                </div>
                <button type="button" class="vf-better-notice__close" title="Dismiss notice">×</button>
                ${duration > 0 ? '<div class="vf-better-notice__progress"></div>' : ""}
            </div>
        `)

    // Add to container or create one
    let $container = $("#vf-better-notices-container")
    if (!$container.length) {
      $container = $('<div id="vf-better-notices-container"></div>')
      $("body").append($container)
    }

    // Add to container
    $container.append($notification)

    // Animate in
    setTimeout(() => {
      $notification.addClass("vf-better-notice--show")
    }, 10)

    // Handle progress bar animation
    if (duration > 0) {
      const $progress = $notification.find(".vf-better-notice__progress")
      if ($progress.length) {
        // Delay slightly so animation starts after notification appears
        setTimeout(() => {
          $progress.css({
            width: "100%",
            transform: "scaleX(0)",
            transition: `transform ${duration}ms linear`,
          })
        }, 100)
      }
    }

    // Handle close button
    $notification.find(".vf-better-notice__close").on("click", function () {
      closeBetterNotice($notification)
    })

    // Auto-dismiss after duration (0 = no auto-dismiss)
    if (duration > 0) {
      let dismissTimer
      let remainingTime = duration
      let startTime = Date.now()
      let isPaused = false

      // Start dismiss timer
      function startDismissTimer() {
        startTime = Date.now()
        isPaused = false
        dismissTimer = setTimeout(() => {
          closeBetterNotice($notification)
        }, remainingTime)
      }

      // Pause dismiss timer on hover
      $notification.on("mouseenter", function () {
        if (!isPaused && dismissTimer) {
          clearTimeout(dismissTimer)
          remainingTime -= Date.now() - startTime
          isPaused = true

          // Pause progress bar animation
          const $progress = $notification.find(".vf-better-notice__progress")
          if ($progress.length) {
            $progress.css("transition", "none")
          }
        }
      })

      // Resume dismiss timer on mouse leave
      $notification.on("mouseleave", function () {
        if (isPaused && remainingTime > 0) {
          // Resume progress bar animation
          const $progress = $notification.find(".vf-better-notice__progress")
          if ($progress.length) {
            $progress.css("transition", `transform ${remainingTime}ms linear`)
          }
          startDismissTimer()
        }
      })

      // Start initial timer
      startDismissTimer()
    }

    return $notification
  }

  /**
   * Close better notification with animation
   */
  function closeBetterNotice($notification) {
    $notification.removeClass("vf-better-notice--show")
    $notification.css({
      transform: "translateX(480px) scale(0.95)",
      opacity: "0",
    })
    setTimeout(() => {
      $notification.remove()

      // If no more notifications, remove container
      const $container = $("#vf-better-notices-container")
      if ($container.find(".vf-better-notice").length === 0) {
        $container.remove()
      }
    }, 400)
  }

  /**
   * Validate email address
   */
  function isValidEmail(email) {
    const pattern = /^[^\s@]+@[^\s@]+\.[^\s@]+$/
    return pattern.test(email)
  }

  /**
   * Initialize cache management functionality
   */
  function initCacheManagement() {
    // Load initial cache statistics
    loadCacheStats()

    // Handle cache warming
    $("#vf-warm-up-cache")
      .off("click")
      .on("click", function (e) {
        e.preventDefault()
        e.stopPropagation()
        warmUpCache()
      })

    // Handle cache clearing
    $("#vf-clear-cache")
      .off("click")
      .on("click", function (e) {
        e.preventDefault()
        e.stopPropagation()
        clearCache()
      })

    // Auto-refresh cache stats every 30 seconds
    setInterval(loadCacheStats, 30000)
  }

  /**
   * Load cache statistics via AJAX
   */
  function loadCacheStats() {
    if (!intentdeepVfData.isPro) return

    $.ajax({
      url: intentdeepVfData.ajaxUrl,
      type: "POST",
      data: {
        action: "intentdeep_vf_get_cache_stats",
        nonce: intentdeepVfData.nonce,
      },
      success: function (response) {
        if (response.success && response.data.stats) {
          updateCacheStatsDisplay(response.data.stats)
        }
      },
      error: function () {
        // Silently fail to avoid spamming console
        // console.log("Failed to load cache statistics")
      },
    })
  }

  /**
   * Update cache statistics display
   */
  function updateCacheStatsDisplay(stats) {
    $("#vf-cached-files").text(stats.cached_files || 0)
    $("#vf-cache-size").text(stats.cache_size_formatted || "0 B")

    // Update button states based on cache status
    const $warmUpBtn = $("#vf-warm-up-cache")
    const $clearBtn = $("#vf-clear-cache")

    if (stats.cache_enabled) {
      $warmUpBtn.prop("disabled", false)
      $clearBtn.prop("disabled", stats.cached_files === 0)
    } else {
      $warmUpBtn.prop("disabled", true)
      $clearBtn.prop("disabled", true)
    }
  }

  /**
   * Warm up cache via AJAX
   */
  function warmUpCache() {
    const $button = $("#vf-warm-up-cache")
    const originalText = $button.text()

    showLoadingState(
      $button,
      intentdeepVfData.strings.cacheWarmingUp || "Warming up cache...",
    )

    $.ajax({
      url: intentdeepVfData.ajaxUrl,
      type: "POST",
      data: {
        action: "intentdeep_vf_warm_up_cache",
        nonce: intentdeepVfData.nonce,
      },
      success: function (response) {
        if (response.success) {
          showBetterNotice(
            response.data.message || "Cache warmed up successfully!",
            "success",
            5000,
          )
          // Refresh cache stats to show updated numbers
          setTimeout(loadCacheStats, 1000)
        } else {
          showBetterNotice(
            response.data.message || "Error warming up cache",
            "error",
            7000,
          )
        }
      },
      error: function () {
        showBetterNotice(
          "An error occurred while warming up cache",
          "error",
          7000,
        )
      },
      complete: function () {
        hideLoadingState($button, originalText)
      },
    })
  }

  /**
   * Clear all cache via AJAX
   */
  function clearCache() {
    const $button = $("#vf-clear-cache")
    const originalText = $button.text()

    // Show confirmation dialog
    if (
      !confirm(
        "Are you sure you want to clear all cached virtual files? This may temporarily slow down file access.",
      )
    ) {
      return
    }

    showLoadingState(
      $button,
      intentdeepVfData.strings.cacheClearing || "Clearing cache...",
    )

    $.ajax({
      url: intentdeepVfData.ajaxUrl,
      type: "POST",
      data: {
        action: "intentdeep_vf_clear_cache",
        nonce: intentdeepVfData.nonce,
      },
      success: function (response) {
        if (response.success) {
          showBetterNotice(
            response.data.message || "Cache cleared successfully!",
            "success",
            5000,
          )
          // Refresh cache stats to show updated numbers
          setTimeout(loadCacheStats, 1000)
        } else {
          showBetterNotice(
            response.data.message || "Error clearing cache",
            "error",
            7000,
          )
        }
      },
      error: function () {
        showBetterNotice(
          "An error occurred while clearing cache",
          "error",
          7000,
        )
      },
      complete: function () {
        hideLoadingState($button, originalText)
      },
    })
  }

  /**
   * Initialize Pro-specific features
   */
  function initProFeatures() {
    // Extension chips are now display-only (not configurable)
    // No Pro-specific interactive features needed
  }

  /**
   * Initialize extension chips interactive functionality
   * Extension chips are now display-only (not interactive)
   */
  function initExtensionChips() {
    // Extension chips are now display-only
    // Checkboxes are disabled and cannot be toggled
    // Appearance is set by PHP based on user type
  }
})

// Pass data from PHP to JavaScript
if (typeof intentdeepVfData === "undefined") {
  window.intentdeepVfData = {
    isPro: false,
    nonce: "",
    ajaxUrl: typeof ajaxurl !== "undefined" ? ajaxurl : "",
    strings: {
      confirmDangerous: "Are you sure you want to perform this action?",
      confirmReset:
        "This will reset all settings to their default values. This action cannot be undone.",
      upgradeRequired: "This is a Pro feature. Would you like to upgrade?",
    },
  }
}
