'use strict';
(function($){
  $(function(){
    const T = window.knsdd_settings_i18n || {};
    const $tabs = $('.knsdd-tab');
    const $panels = $('.knsdd-tab-panel');

    function activate(hash){
      if(!hash){ hash = '#tab-general'; }
      $tabs.removeClass('is-active').attr('aria-selected','false');
      $panels.removeClass('is-active');
      const $tab = $tabs.filter(`[href="${hash}"]`);
      const $panel = $(hash);
      if($tab.length && $panel.length){
        $tab.addClass('is-active').attr('aria-selected','true');
        $panel.addClass('is-active');
        $panel.focus();
      } else {
        // Fallback: hedef sekme yoksa genel sekmeye dön
        if(hash !== '#tab-general'){
          activate('#tab-general');
        }
      }
    }

    // If URL has knsdd_tab param (coming back from save), honor it
    (function(){
      try{
        const params = new URLSearchParams(window.location.search);
        const savedTab = params.get('knsdd_tab');
        // If activation flags exist, clean URL and hide their notices
        const hadActivationFlags = params.has('activate') || params.has('activate-multi') || params.has('deactivate');
        if(hadActivationFlags){
          params.delete('activate');
          params.delete('activate-multi');
          params.delete('deactivate');
          const cleaned = window.location.pathname + (params.toString() ? ('?' + params.toString()) : '') + window.location.hash;
          if(window.history && window.history.replaceState){ window.history.replaceState(null, document.title, cleaned); }
          // Hide already-rendered activation notices (language-agnostic contains check)
          jQuery('.notice, #message').filter(function(){
            const t = jQuery(this).text().toLowerCase();
            return t.includes('aktif') || t.includes('activated') || t.includes('deactivated');
          }).remove();
        }
        if(savedTab){ window.location.hash = '#' + savedTab; }
      } catch(_e){}
    })();

    // Initial
    activate(window.location.hash);

    // Click
    $tabs.on('click', function(e){
      e.preventDefault();
      const hash = $(this).attr('href');
      history.replaceState(null,'',hash);
      activate(hash);
    });

    // From raw sections: move sections to their panels
    const $raw = $('#knsdd-settings-sections-raw');
    function getSectionTable(id){
      const key = String(id).replace(/^#/, '');
      let $anchor = $raw.find(id);
      if(!$anchor.length) {
        // Try new data marker
        $anchor = $raw.find('[data-knsdd-section="' + key + '"]');
      }
      if(!$anchor.length) { return $(); }

      // Collect ALL tables that belong to this section (until the next section marker)
      const $nextSection = $anchor.nextAll('[data-knsdd-section]').first();
      let $tables = $();
      if ($nextSection.length) {
        $tables = $anchor.nextUntil($nextSection, 'table');
      } else {
        $tables = $anchor.nextAll('table');
      }
      if ($tables.length) { return $tables; }

      // Alt fallback: sometimes WP may wrap differently
      const $altTables = $anchor.parent().nextAll('table');
      if ($altTables.length) { return $altTables; }

      // Fallback: if markup differs, try closest table
      const $closest = $anchor.closest('table');
      if($closest.length) return $closest;
      return $();
    }


    // General panel
    const $generalSection = getSectionTable('#knsdd_general_section');
    if($generalSection.length){
      const $body = $('#tab-general .knsdd-tab-body');
      $body.append($generalSection);
      $body.children('p.description').first().remove();
    }
    // Dil Ayarları paneli (i18n sekmesi)
    const $langSection = getSectionTable('#knsdd_language_section');
    if($langSection.length){
      const $body = $('#tab-i18n .knsdd-tab-body');
      $body.append($langSection);
      $body.children('p.description').first().remove();
    }
    // Tarih Yönetimi paneli
    const $datesSection = getSectionTable('#knsdd_dates_section');
    if($datesSection.length){
      const $body = $('#tab-dates .knsdd-tab-body');
      $body.append($datesSection);
      $body.children('p.description').first().remove();
    }
    // UI & Accessibility panel
    const $uiSection = getSectionTable('#knsdd_ui_section');
    if($uiSection.length){
      const $body = $('#tab-ui .knsdd-tab-body');
      $body.append($uiSection);
      $body.children('p.description').first().remove();

      // --- Group UI fields into three boxes: Warnings, Focus, Accessibility ---
      try {
        const $warningsBox = $('<div class="knsdd-settings-box"><h3>' + (T.warnings_title || 'Uyarılar') + '</h3><table class="form-table"><tbody></tbody></table></div>');
        const $focusBox    = $('<div class="knsdd-settings-box"><h3>' + (T.focus_title || 'Son Odak') + '</h3><table class="form-table"><tbody></tbody></table></div>');
        const $a11yBox     = $('<div class="knsdd-settings-box"><h3>' + (T.a11y_title || 'Erişilebilirlik') + '</h3><table class="form-table"><tbody></tbody></table></div>');
        const $promoBox    = $('<div class="knsdd-settings-box"><h3>' + (T.promo_title || 'Ürün Mesajı') + '</h3><table class="form-table"><tbody></tbody></table></div>');
        const $tierBox     = $('<div class="knsdd-settings-box"><h3>' + (T.tier_title || 'Kademe İndirim Tablosu') + '</h3><table class="form-table"><tbody></tbody></table></div>');
        const $cartMsgsBox = $('<div class="knsdd-settings-box"><h3>' + (T.cart_msgs_title || 'Mini Sepet & Sepet & Ödeme Mesajları') + '</h3><table class="form-table"><tbody></tbody></table></div>');

        const $area = $('#tab-ui .knsdd-tab-body');
        // Place boxes: final order top->bottom should be [Warnings, Focus, Product Message, Cart Messages, Tier, A11y]
        // With prepend, push in reverse: A11y (last), then Tier, then Cart Messages, then Product Message, then Focus, then Warnings
        $area.prepend($a11yBox);
        $area.prepend($tierBox);
        $area.prepend($cartMsgsBox);
        $area.prepend($promoBox);
        $area.prepend($focusBox);
        $area.prepend($warningsBox);

        const moveByName = function(fieldName, $targetBox){
          const nameSel = 'knsdd_global_settings[' + fieldName + ']';
          let $row = $('[name="' + nameSel + '"]').closest('tr').first();
          
          if ($row.length) {
            $row.detach();
            $targetBox.find('tbody').append($row);
          }
        };

        // Move rows by field name (100% language-independent)
        moveByName('warning_theme', $warningsBox);
        moveByName('warning_location', $warningsBox);
        moveByName('inline_warning_ms', $warningsBox);
        moveByName('focus_theme', $focusBox);
        moveByName('last_highlight_ms', $focusBox);
        moveByName('a11y_alert_role', $a11yBox);
        moveByName('cart_msg_under_item', $cartMsgsBox); // cart_msg_positions row
        moveByName('special_msg_under_item', $cartMsgsBox);
        moveByName('strikethrough_price_enabled', $cartMsgsBox); // Üstü çizili fiyat
        moveByName('product_message_location', $promoBox);
        moveByName('product_message_force', $promoBox);
        moveByName('tier_table_location', $tierBox);
        moveByName('tier_table_force', $tierBox);
        moveByName('tier_theme_use_custom', $tierBox);
        moveByName('tier_theme_preset', $tierBox);

        // Tier table enabled checkbox - use name-based search
        (function(){
          const nameSel = 'knsdd_global_settings[tier_table_enabled]';
          let $row = $('[name="' + nameSel + '"]').closest('tr').first();
          if($row.length){
            $row.detach();
            $tierBox.find('tbody').prepend($row);
          }
        })();

        // 'Ürün Mesajı Konumunu Zorla' satırını konum seçiminin HEMEN ALTINA getir (name tabanlı, sade)
        (function(){
          const $msgLoc   = $promoBox.find('tr:has([name="knsdd_global_settings[product_message_location]"])').first();
          const $msgForce = $promoBox.find('tr:has([name="knsdd_global_settings[product_message_force]"])').first();
          if($msgLoc.length && $msgForce.length){
            $msgForce.detach();
            $msgLoc.after($msgForce);
          }
        })();

        // 'Konumu zorla' satırını konum seçiminin HEMEN ALTINA getir (name tabanlı, sade)
        (function(){
          const $locRow   = $tierBox.find('tr:has([name="knsdd_global_settings[tier_table_location]"])').first();
          const $forceRow = $tierBox.find('tr:has([name="knsdd_global_settings[tier_table_force]"])').first();
          if($locRow.length && $forceRow.length){
            $forceRow.detach();
            $locRow.after($forceRow);
          }
        })();

        // Note: Dropdown'larda 'force_*' seçenekleri kaldırıldığı için otomatik tikleme mantığına gerek yok.

        // Clean up: remove any empty tables left behind in UI area
        $area.find('table.form-table').each(function(){
          if (jQuery(this).find('tr').length === 0) { jQuery(this).remove(); }
        });
      } catch(_e) {}
    }
    // Rules Behavior panel
    const $rulesSection = getSectionTable('#knsdd_rules_section');
    if($rulesSection.length){
      const $body = $('#tab-rules .knsdd-tab-body');
      $body.append($rulesSection);
      $body.children('p.description').first().remove();
    }
    // Notifications panel
    const $notificationsSection = getSectionTable('#knsdd_notifications_section');
    if($notificationsSection.length){
      const $body = $('#tab-notifications .knsdd-tab-body');
      $body.append($notificationsSection);
      $body.children('p.description').first().remove();
    }
    // Advanced panel
    const $advSection = getSectionTable('#knsdd_advanced_section');
    if($advSection.length){
      const $body = $('#tab-advanced .knsdd-tab-body');
      $body.append($advSection);
      $body.children('p.description').first().remove();
    }

    // Persist active tab on form submit by injecting knsdd_tab into _wp_http_referer
    $('#knsdd-settings-form').on('submit', function(){
      const activeHash = $('.knsdd-tabs a.is-active').attr('href') || window.location.hash || '#tab-general';
      const tabKey = String(activeHash).replace(/^#/, '');
      const $ref = $(this).find('input[name="_wp_http_referer"]');
      const updateUrl = function(url){
        try{
          const base = new URL(url, window.location.origin);
          // Remove activation-related params that can trigger wrong admin notices
          base.searchParams.delete('activate');
          base.searchParams.delete('activate-multi');
          base.searchParams.delete('deactivate');
          base.searchParams.set('knsdd_tab', tabKey);
          return base.pathname + base.search;
        } catch(_e){
          const noHash = String(url).split('#')[0];
          // strip activate/activate-multi/deactivate params manually
          let cleaned = noHash
            .replace(/([?&])activate(?:=[^&]*)?(?=&|$)/,'$1')
            .replace(/([?&])activate-multi(?:=[^&]*)?(?=&|$)/,'$1')
            .replace(/([?&])deactivate(?:=[^&]*)?(?=&|$)/,'$1')
            .replace(/[?&]$/,'');
          if(/([?&])knsdd_tab=/.test(cleaned)){
            return cleaned.replace(/([?&])knsdd_tab=[^&]*/, '$1knsdd_tab=' + encodeURIComponent(tabKey));
          }
          const sep = cleaned.includes('?') ? '&' : '?';
          return cleaned + sep + 'knsdd_tab=' + encodeURIComponent(tabKey);
        }
      };
      if($ref.length){
        $ref.val(updateUrl($ref.val()));
      } else {
        $('<input>', {type:'hidden', name:'_wp_http_referer', value: updateUrl(window.location.pathname + window.location.search)}).appendTo(this);
      }
    });

    // Live theme preview (supports: rose, blue, gray, sage, lavender, amber)
    $(document).on('change', '#knsdd-warning-theme', function(){
      const val = $(this).val();
      const $wrap = $(this).closest('td').find('.knsdd-theme-preview');
      $wrap.removeClass('theme-rose theme-blue theme-gray theme-sage theme-lavender theme-amber')
           .addClass('theme-' + val);
    });

    // Live focus theme preview (same palette as warning theme)
    $(document).on('change', '#knsdd-focus-theme', function(){
      const val = $(this).val();
      const $wrap = $(this).closest('td').find('.knsdd-theme-preview');
      $wrap.removeClass('theme-rose theme-blue theme-gray theme-sage theme-lavender theme-amber')
           .addClass('theme-' + val);
    });

    // Reset to defaults (placeholder – server side to be implemented later)
    $('.knsdd-reset-to-defaults').on('click', function(){
      if(!confirm(T.confirm_reset || 'Varsayılanlara dönmek istediğinize emin misiniz? Bu işlem kaydedilmeden uygulanmaz.')) return;
      // Clear fields to defaults client-side if needed; server-side will finalize on save.
    });


    // --- Tier Table: custom color controls (checkbox-driven) ---
    (function(){
      const $checkbox = $('input[name="knsdd_global_settings[tier_theme_use_custom]"]');
      const $controls = $('.knsdd-tier-custom-controls');
      const $row      = $('#knsdd-tier-custom-row');
      const $color    = $('#knsdd-tier-theme-color');
      const $hex      = $('#knsdd-tier-theme-hex');
      const $reset    = $('.knsdd-tier-color-reset');
      const $preset   = $('#knsdd-tier-theme-preset');
      const $preview  = $('.knsdd-palette-preview');
      const $tierBox  = $('.knsdd-tier-theme-preview');

      if(!$checkbox.length) return; // field may not be present in some contexts

      // Satır her zaman görünür; önceki toggle mantığı kaldırıldı

      const normHex = function(v){
        if(!v) return '';
        v = String(v).trim();
        if(!v.startsWith('#')) v = '#' + v;
        return v;
      };
      const isValidHex = function(v){
        return /^#([0-9a-fA-F]{3}|[0-9a-fA-F]{6})$/.test(v);
      };

      // Preset -> Hex tohumlama (checkbox açık ve hex boşsa)
      const palette = {
        rose: '#f43f5e',
        blue: '#3b82f6',
        gray: '#6b7280',
        sage: '#10b981',
        lavender: '#8b5cf6',
        amber: '#f59e0b'
      };
      const applyPresetToCustom = function(){
        if(!$checkbox.is(':checked')) return;
        // Sadece hex alanı boşsa preset'ten renk yükle
        // Kullanıcı zaten bir renk seçmişse onu koru
        const currentHex = normHex($hex.val());
        if(currentHex && isValidHex(currentHex)) return;
        
        const key = ($preset.val() || 'blue');
        const clr = palette[key] || palette.blue;
        $hex.val(clr);
        $color.val(clr);
      };

      // Palette preview updater
      const updatePalettePreview = function(){
        const key = ($preset.val() || 'blue');
        const clr = palette[key] || palette.blue;
        if($preview.length){
          $preview.find('.swatch').css('background-color', clr);
          $preview.find('.hex').text(clr);
        }
        // Tier theme preview kutusu için theme sınıfını uygula ve i18n metnini güncelle
        if($tierBox.length){
          $tierBox.removeClass('theme-rose theme-blue theme-gray theme-sage theme-lavender theme-amber')
                 .addClass('theme-' + key);
          // i18n metnini güncelle
          const $previewBox = $tierBox.find('.preview-box[data-i18n-key]');
          if($previewBox.length && T.sample_table_tone){
            $previewBox.text(T.sample_table_tone);
          }
        }
      };
      updatePalettePreview();
      // İlk yüklemede preset'i uygula (özel renk aktifse)
      applyPresetToCustom();
      // Checkbox açıldığında preset'i uygula
      $checkbox.on('change', function(){ if($checkbox.is(':checked')){ applyPresetToCustom(); } });
      // Palet değişince preset'i uygula ve önizlemeyi güncelle
      $preset.on('change', function(){ applyPresetToCustom(); updatePalettePreview(); });

      // color input -> hex
      $color.on('input change', function(){
        const v = normHex($(this).val());
        if(isValidHex(v)) { $hex.val(v); }
      });

      // hex -> color input
      $hex.on('input change', function(){
        const v = normHex($(this).val());
        if(isValidHex(v)) { $color.val(v); }
      });

      // reset: sadece hex alanını temizle (checkbox ve color'a dokunma)
      $reset.on('click', function(){
        $hex.val('');
      });
    })();

  });
})(jQuery);