/* global jQuery, scwordai_agent_chat */
(function($){
  'use strict';

  // Color picker
  $(function(){
    if ($.fn.wpColorPicker) {
      $('.wa-color-field').wpColorPicker();
    }

    syncOpenaiChatModelHint();
    syncXaiChatModelHint();
  });

  function syncOpenaiChatModelHint() {
    const $select = $("#wa-chat-model");
    const $hint = $("#wa-chat-openai-model-hint");
    if (!$select.length || !$hint.length) {
      return;
    }

    const hint = $select.find("option:selected").data("model-hint") || "";
    if (hint) {
      $hint.text(hint);
    }
  }

  $(document).on("change", "#wa-chat-model", syncOpenaiChatModelHint);

  function syncXaiChatModelHint() {
    const $select = $("#wa-chat-xai-model");
    const $hint = $("#wa-chat-xai-model-hint");
    if (!$select.length || !$hint.length) {
      return;
    }

    const hint = $select.find("option:selected").data("model-hint") || "";
    if (hint) {
      $hint.text(hint);
    }
  }

  $(document).on("change", "#wa-chat-xai-model", syncXaiChatModelHint);


  // ===========================================================
  // 💾 Save Chat Settings (Admin AJAX)
  // ===========================================================
  jQuery(document).on("click", "#wa-chat-save", function (e) {
    e.preventDefault();

    const $btn = jQuery(this)
      .prop("disabled", true)
      .html('<span class="dashicons dashicons-update spin"></span> Saving…');

    // ✅ Collect form data
    const payload = {
      action: "sc_wordai_agent_save_chat_settings",
      security: scwordai_agent_chat.nonce,

      enabled: jQuery("#wa-chat-enabled").is(":checked") ? 1 : 0, // always enabled by default
      assistant_name: jQuery("#wa-chat-name").val(),
      welcome_message: jQuery("#wa-chat-welcome").val(),
      bubble_label: jQuery("#wa-chat-label").val(),
      theme: jQuery('input[name="wa-chat-theme"]:checked').val(),
      bubble_color: jQuery("#wa-chat-color").val(),
      avatar_style: jQuery('input[name="wa-chat-avatar"]:checked').val(),
      avatar_color: jQuery("#wa-chat-avatar-color").val(),
      chat_font_size: jQuery("#wa-chat-font-size").val(),
      temperature: jQuery("#wa-chat-temp").val(),
      auto_display: jQuery("#wa-chat-auto").is(":checked") ? 1 : 0,
      position: jQuery('input[name="wa-chat-position"]:checked').val(),
      reply_mode: "nonstream",
      visibility: jQuery('input[name="wa-chat-visibility"]:checked').val(),
      prompt_prefix: jQuery("#wa-chat-prefix").val(),
      analytics_enabled: jQuery("#wa-chat-analytics-enabled").is(":checked") ? 1 : 0,
      feedback_enabled: jQuery("#wa-chat-feedback-enabled").is(":checked") ? 1 : 0,
      show_source_citations: jQuery("#wa-chat-source-citations").is(":checked") ? 1 : 0,
      retention_days: jQuery("#wa-chat-retention-days").val(),
      handoff_enabled: jQuery("#wa-chat-handoff-enabled").is(":checked") ? 1 : 0,
      handoff_email: jQuery("#wa-chat-handoff-email").val(),
      handoff_label: jQuery("#wa-chat-handoff-label").val(),
      lead_capture_mode: jQuery("#wa-chat-lead-mode").val(),
      lead_intro_text: jQuery("#wa-chat-lead-intro").val(),
      lead_consent_text: jQuery("#wa-chat-lead-consent-text").val(),
      lead_privacy_url: jQuery("#wa-chat-lead-privacy-url").val(),
      lead_consent_required: jQuery("#wa-chat-lead-consent-required").is(":checked") ? 1 : 0,
      lead_notify_admin: jQuery("#wa-chat-lead-notify-admin").is(":checked") ? 1 : 0,
      lead_name_enabled: jQuery("#wa-chat-lead-name-enabled").is(":checked") ? 1 : 0,
      lead_name_required: jQuery("#wa-chat-lead-name-required").is(":checked") ? 1 : 0,
      lead_email_enabled: jQuery("#wa-chat-lead-email-enabled").is(":checked") ? 1 : 0,
      lead_email_required: jQuery("#wa-chat-lead-email-required").is(":checked") ? 1 : 0,
      lead_phone_enabled: jQuery("#wa-chat-lead-phone-enabled").is(":checked") ? 1 : 0,
      lead_phone_required: jQuery("#wa-chat-lead-phone-required").is(":checked") ? 1 : 0,
      lead_company_enabled: jQuery("#wa-chat-lead-company-enabled").is(":checked") ? 1 : 0,
      lead_company_required: jQuery("#wa-chat-lead-company-required").is(":checked") ? 1 : 0,
      lead_message_enabled: jQuery("#wa-chat-lead-message-enabled").is(":checked") ? 1 : 0,
      lead_message_required: jQuery("#wa-chat-lead-message-required").is(":checked") ? 1 : 0,
    };

    const provider = jQuery("#wa-active-provider").val() || "openai";
    
    if (provider === "google") {
      payload.google_model = jQuery("#wa-chat-google-model").val();
      payload.fallback_google = jQuery("#wa-chat-fallback-google").val();
      payload.google_embedding_source = jQuery('input[name="wa-chat-embedding-source"]:checked').val() || "google";
    } else if (provider === "anthropic") {
      payload.anthropic_model = jQuery("#wa-chat-anthropic-model").val();
      payload.fallback_anthropic = jQuery("#wa-chat-fallback-anthropic").val();
      payload.anthropic_embedding_source = jQuery('input[name="wa-chat-embedding-source"]:checked').val() || "anthropic";
    } else if (provider === "xai") {
      payload.xai_model = jQuery("#wa-chat-xai-model").val();
      payload.fallback_xai = jQuery("#wa-chat-fallback-xai").val();
      payload.xai_embedding_source = jQuery('input[name="wa-chat-embedding-source"]:checked').val() || "xai";
    } else {
      payload.model = jQuery("#wa-chat-model").val();
      payload.fallback_openai = jQuery("#wa-chat-fallback-openai").val();
      payload.openai_embedding_source = jQuery('input[name="wa-chat-embedding-source"]:checked').val() || "openai";
    }

    // ✅ Set active provider
    payload.active_provider = provider;
    payload.provider = provider;

    // ✅ Submit via AJAX
    jQuery
      .post(scwordai_agent_chat.adminajax_url, payload)
      .done(function (resp) {
        if (resp && resp.status === "success") {
          showWordAIGlobalNotice("success", resp.feedbackMsg || "Chat settings saved successfully.");
          setTimeout(() => location.reload(), 900);
        } else {
          showWordAIGlobalNotice("error", (resp && resp.feedbackMsg) || "Save failed.");
        }
      })
      .fail(function () {
        showWordAIGlobalNotice("error", "Request failed.");
      })
      .always(function () {
        $btn
          .prop("disabled", false)
          .html('<span class="dashicons dashicons-yes-alt"></span> Save Chat Settings');
      });
  });


  // ===========================================================
  // 🔁 Reset Chat Settings (WordPress Modal Dialog)
  // ===========================================================
  jQuery(document).on("click", "#wa-chat-reset", function (e) {
    e.preventDefault();

    // ✅ Create modal dialog if missing
    let $dialog = jQuery("#wordai-reset-confirm-dialog");
    if (!$dialog.length) {
      jQuery("body").append(`
        <div id="wordai-reset-confirm-dialog" title="Reset to Defaults" style="display:none;">
          <p style="font-size:14px;">
            <span class="dashicons dashicons-warning" style="color:#d63638;vertical-align:middle;margin-right:6px;"></span>
            Are you sure you want to reset <strong>all AI Chat settings</strong> to their default values?
          </p>
        </div>
      `);
      $dialog = jQuery("#wordai-reset-confirm-dialog");
    }

    // ✅ Launch modal
    $dialog.dialog({
      modal: true,
      resizable: false,
      draggable: false,
      width: 400,
      buttons: {
        "Reset Settings": function () {
          const $modal = jQuery(this);
          const $btn = jQuery("#wa-chat-reset")
            .prop("disabled", true)
            .html('<span class="dashicons dashicons-update spin"></span> Resetting…');

          // 🔄 AJAX: Reset to defaults
          jQuery
            .post(scwordai_agent_chat.adminajax_url, {
              action: "sc_wordai_agent_reset_chat_settings",
              security: scwordai_agent_chat.nonce,
            })
            .done(function (resp) {
              if (resp && resp.status === "success") {
                showWordAIGlobalNotice("success", resp.feedbackMsg || "Chat settings reset to defaults.");
                setTimeout(() => location.reload(), 1000);
              } else {
                showWordAIGlobalNotice("error", (resp && resp.feedbackMsg) || "Reset failed.");
              }
            })
            .fail(function () {
              showWordAIGlobalNotice("error", "Request failed.");
            })
            .always(function () {
              $btn
                .prop("disabled", false)
                .html('<span class="dashicons dashicons-image-rotate"></span> Reset to Defaults');
              $modal.dialog("close");
            });
        },
        Cancel: function () {
          jQuery(this).dialog("close");
        },
      },
      open: function () {
        // 🔴 Style "Reset Settings" button red
        jQuery(".ui-dialog-buttonpane button:contains('Reset Settings')").css({
          background: "#d63638",
          color: "#fff",
          border: "none",
          fontWeight: "600",
        });
      },
    });
  });


  /** AI Agent Menu - Tabs & Navigation */
  // lightweight tabs without extra markup (use nav-tab UI)
  $('#sc-wordai-ai-agent-tabs .nav-tab-wrapper .nav-tab').on('click', function(e){
    e.preventDefault();
    const target = $(this).attr('href');
    $('#sc-wordai-ai-agent-tabs .nav-tab').removeClass('nav-tab-active');
    $(this).addClass('nav-tab-active');
    $('#sc-wordai-ai-agent-tabs .sc-wordai-tab-panel').hide();
    $(target).show();
    // persist selected tab in hash
    history.replaceState(null, '', target);
  });
  // open from hash if present
  const hash = window.location.hash;
  if(hash && $(hash).length){
    $('#sc-wordai-ai-agent-tabs .nav-tab-wrapper .nav-tab[href="'+hash+'"]').trigger('click');
  }


  // ----------------------------------------------------------
  // 🔗 Handle "Contents Embedding" link click → switch tab
  // ----------------------------------------------------------
  $("#wa-go-to-embedding").on("click", function (e) {
    e.preventDefault();
    const $embedTab = $('#sc-wordai-ai-agent-tabs .nav-tab-wrapper .nav-tab[href="#tab-embedding"]');
    if ($embedTab.length) {
      $embedTab.trigger("click");
      $("html, body").animate(
        { scrollTop: $(".nav-tab-wrapper").offset().top - 60 },
        400
      );
    }
  });

  $(document).on("click", ".wordai-lead-status-save", function(e){
    e.preventDefault();
    const $btn = $(this);
    const $row = $btn.closest("tr");
    const leadId = $row.data("lead-id");
    const leadStatus = $row.find(".wordai-lead-status-select").val();
    if (!leadId || !leadStatus) return;

    $btn.prop("disabled", true).addClass("is-busy");
    $.post(scwordai_agent_chat.adminajax_url, {
      action: "sc_wordai_agent_update_lead_status",
      security: scwordai_agent_chat.nonce,
      lead_id: leadId,
      lead_status: leadStatus
    }).done(function(resp){
      if (resp && resp.status === "success") {
        showWordAIGlobalNotice("success", resp.feedbackMsg || "Lead status updated.");
      } else {
        showWordAIGlobalNotice("error", (resp && resp.feedbackMsg) || "Lead status update failed.");
      }
    }).fail(function(){
      showWordAIGlobalNotice("error", "Lead status update request failed.");
    }).always(function(){
      $btn.prop("disabled", false).removeClass("is-busy");
    });
  });

  $(document).on("click", ".wordai-lead-delete", function(e){
    e.preventDefault();
    const $btn = $(this);
    const $row = $btn.closest("tr");
    const leadId = $row.data("lead-id");
    if (!leadId || !window.confirm("Delete this captured lead? Conversation history will remain.")) return;

    $btn.prop("disabled", true).addClass("is-busy");
    $.post(scwordai_agent_chat.adminajax_url, {
      action: "sc_wordai_agent_delete_lead",
      security: scwordai_agent_chat.nonce,
      lead_id: leadId
    }).done(function(resp){
      if (resp && resp.status === "success") {
        $row.fadeOut(180, function(){ $(this).remove(); });
        showWordAIGlobalNotice("success", resp.feedbackMsg || "Lead deleted.");
      } else {
        showWordAIGlobalNotice("error", (resp && resp.feedbackMsg) || "Lead delete failed.");
      }
    }).fail(function(){
      showWordAIGlobalNotice("error", "Lead delete request failed.");
    }).always(function(){
      $btn.prop("disabled", false).removeClass("is-busy");
    });
  });

  



})(jQuery); // Main (function($) End
