// Manşet önizleme fonksiyonları
(function($) {
  'use strict';

  function updateHeadlinePreview() {
    var style = $('.csf-field-image_select input[name="kanews_options[headline-style]"]:checked').val();
    var titlePosition = $('.csf-field-select select[name="kanews_options[headline-title-position]"]').val();
    var titleSize = $('.csf-field-slider input[name="kanews_options[headline-title-size]"]').val();
    var showMeta = $('.csf-field-switcher input[name="kanews_options[headline-meta]"]').is(':checked');
    
    var $preview = $('.kan-headline-preview-container');
    var $content = $('.kanews-slide-content');
    var $meta = $('.kan-headline-preview-meta');
    
    // Stil güncelleme
    $preview.removeClass('style-1 style-2 style-3 style-4').addClass('style-' + style);
    
    // Pozisyon güncelleme
    $content.addClass(titlePosition);
    
    // Başlık boyutu güncelleme
    $('.kanews-slide-headline').css('font-size', titleSize + 'px');
    
    // Tipografi ayarlarını güncelle
    var mansetTitleTypography = getMansetTitleTypography();
    $('.kanews-slide-headline').css({
      'font-size': mansetTitleTypography.font_size,
      'font-weight': mansetTitleTypography.font_weight,
      'line-height': mansetTitleTypography.line_height,
      'letter-spacing': mansetTitleTypography.letter_spacing,
      'text-transform': mansetTitleTypography.text_transform
    });

    // Meta gösterimi
    $meta.toggle(showMeta);

    // Manşet etiketi kontrolü
    var mansetTagTitle = $('[name="kanews_post_options[manset_tag_title]"]').val();
    if (mansetTagTitle) {
      $('.kanews-manset-tag').text(mansetTagTitle).show();
    } else {
      $('.kanews-manset-tag').hide();
    }
  }

  function getMansetTitleTypography() {
    return {
      font_size: $('[name="kanews_post_options[manset_title_typography][font-size]"]').val() + 'px' || '',
      font_weight: $('[name="kanews_post_options[manset_title_typography][font-weight]"]').val() || '',
      line_height: $('[name="kanews_post_options[manset_title_typography][line-height]"]').val() || '',
      letter_spacing: $('[name="kanews_post_options[manset_title_typography][letter-spacing]"]').val() + 'px' || '',
      text_transform: $('[name="kanews_post_options[manset_title_typography][text-transform]"]').val() || ''
    };
  }

  // Ayarlar değiştiğinde önizlemeyi güncelle
  $(document).on('change', '.csf-field input, .csf-field select', function() {
    updateHeadlinePreview();
  });

  // Sayfa yüklendiğinde önizlemeyi başlat
  $(document).ready(function() {
    updateHeadlinePreview();
  });

  // Initialize preview when document is ready
  $(document).ready(function() {
    initMansetPreview();
  });

  function initMansetPreview() {
    const preview = $('#kanews-manset-preview');
    if (!preview.length) return;

    // Watch for changes in relevant fields
    const fields = {
      title: $('[name="kanews_post_options[kanews_manset_title]"]'),
      excerpt: $('[name="kanews_post_options[kanews_manset_excerpt]"]'),
      tagTitle: $('[name="kanews_post_options[manset_tag_title]"]'),
      tagPosition: $('[name="kanews_post_options[manset_tag]"]'),
      tagStyle: $('[name="kanews_post_options[manset_tag_style]"]'),
      tagBg: $('[name="kanews_post_options[manset_tag_bg]"]'),
      tagColor: $('[name="kanews_post_options[manset_tag_color]"]'),
      detailPosition: $('[name="kanews_post_options[manset_detail_position]"]'),
      overlayColor: $('[name="kanews_post_options[manset_color]"]'),
      titleColor: $('[name="kanews_post_options[manset_title_color]"]'),
      descColor: $('[name="kanews_post_options[manset_desc_color]"]'),
      desktopImage: $('[name="kanews_post_options[manset_desktop][url]"]'),
      mobileImage: $('[name="kanews_post_options[manset_mobile][url]"]'),
      hideContent: $('[name="kanews_post_options[post_detail]"]')
    };

    // Get post title from WordPress editor
    const getPostTitle = () => {
      const gutenbergTitle = wp.data?.select('core/editor')?.getEditedPostAttribute('title');
      if (gutenbergTitle) return gutenbergTitle;
      return $('#title').val() || '';
    };

    // Get featured image URL
    const getFeaturedImageUrl = () => {
      // Try Gutenberg
      const featuredImage = wp.data?.select('core/editor')?.getEditedPostAttribute('featured_media');
      if (featuredImage) {
        const mediaObj = wp.data.select('core').getMedia(featuredImage);
        return mediaObj?.source_url;
      }
      // Try classic editor
      return $('#set-post-thumbnail img').attr('src') || '';
    };

    // Update preview when fields change
    Object.values(fields).forEach(field => {
      field.on('change keyup', updatePreview);
    });

    // Watch media uploads
    $('.csf-field-media').on('csf.change', updatePreview);

    // Watch featured image changes
if (wp.data && wp.data.subscribe) {
  wp.data.subscribe(() => {
    // Check if the editor store exists before accessing it
    const editor = wp.data.select('core/editor');
    if (editor) {
      const featuredImageId = editor.getEditedPostAttribute('featured_media');
      if (featuredImageId !== lastFeaturedImageId) {
        lastFeaturedImageId = featuredImageId;
        updatePreview();
      }
    }
  });
}
    $('#postimagediv').on('click', '#remove-post-thumbnail', updatePreview);
    $('#postimagediv').on('DOMSubtreeModified', '#set-post-thumbnail img', updatePreview);

    // Watch post title changes
    $('#title').on('change keyup', updatePreview);
    if (wp.data && wp.data.subscribe) {
      wp.data.subscribe(() => {
        const newTitle = wp.data.select('core/editor')?.getEditedPostAttribute('title');
        if (newTitle !== lastTitle) {
          lastTitle = newTitle;
          updatePreview();
        }
      });
    }

    let lastTitle = getPostTitle();
    let lastFeaturedImageId = wp.data?.select('core/editor')?.getEditedPostAttribute('featured_media');

    function updatePreview() {
      const previewWrapper = preview.find('.kanews-slide');
      const previewTag = preview.find('.kanews-manset-tag');
      const previewContent = preview.find('.kanews-slide-content');
      const previewOverlay = preview.find('.kanews-slide-overlay');
      const previewImage = preview.find('.kanews-slide-thumb');
      
      // Update text content
      const mansetTitle = fields.title.val();
      const postTitle = getPostTitle();
      const cleanTitle = (mansetTitle || postTitle).replace(/&quot;/g, '"').replace(/&#039;/g, "'");
      preview.find('.kanews-slide-headline').text(cleanTitle);
      preview.find('.kanews-slide-spot').text(fields.excerpt.val());
      
      // Update image - use manset image if available, otherwise use featured image
      const desktopImageUrl = fields.desktopImage.val();
      const mobileImageUrl = fields.mobileImage.val();
      const featuredImageUrl = getFeaturedImageUrl();
      
      if (window.innerWidth <= 768 && mobileImageUrl) {
        previewImage.attr('src', mobileImageUrl);
      } else if (desktopImageUrl) {
        previewImage.attr('src', desktopImageUrl);
      } else if (featuredImageUrl) {
        previewImage.attr('src', featuredImageUrl);
      }
      
      // Toggle content visibility based on post_detail checkbox
      const hideContentCheckbox = fields.hideContent;
      const hideContent = hideContentCheckbox.val() === '1';
      
      if (hideContent) {
        previewContent.css('display', 'none');
        previewOverlay.css('display', 'none');
      } else {
        previewContent.css('display', '');
        previewOverlay.css('display', '');
      }
      
      // Update tag
      const mansetTagTitle = fields.tagTitle.val();
      if (mansetTagTitle) {
        previewTag.html("<span></span><span></span><span></span>" + mansetTagTitle);
        previewTag.css({
          'background-color': fields.tagBg.val(),
          'color': fields.tagColor.val()
        }).show();
      } else {
        previewTag.hide();
      }

      // Update tag position and style with classes
      previewTag
        .removeClass('kanews-manset-tag-position-top-left kanews-manset-tag-position-top-right kanews-manset-tag-position-bottom-left kanews-manset-tag-position-bottom-right')
        .removeClass('kanews-manset-tag-style-1 kanews-manset-tag-style-2 kanews-manset-tag-style-3')
        .addClass('kanews-manset-tag-position-' + fields.tagPosition.val())
        .addClass('kanews-manset-tag-style-' + fields.tagStyle.val());

      // Update content position with classes
      previewWrapper
        .removeClass('kanews-mansetd-bottom kanews-mansetd-left kanews-mansetd-right')
        .addClass('kanews-mansetd-' + fields.detailPosition.val());

      // Update overlay position with classes
      previewOverlay
        .removeClass('overlay-bottom overlay-left overlay-right')
        .addClass('overlay-' + fields.detailPosition.val())
        .css('--gradient-start-color', fields.overlayColor.val());

      // Update colors
      preview.find('.kanews-slide-headline').css('color', fields.titleColor.val());
      preview.find('.kanews-slide-spot').css('color', fields.descColor.val());

      // Başlık için inline düzenleme
      preview.find('.kanews-slide-headline').on('click', function() {
        const currentText = $(this).text();
        const currentClasses = $(this).attr('class');
        const $editable = $('<div contenteditable="true" class="inline-edit"></div>').text(currentText);
        $(this).replaceWith($editable);
        $editable.focus();

        $editable.on('blur', function() {
          const newText = $(this).text();
          const $headline = $('<div>').addClass(currentClasses).text(newText);
          $(this).replaceWith($headline);
          fields.title.val(newText);
          updatePreview();
        });
      });

      // Açıklama için inline düzenleme
      preview.find('.kanews-slide-spot').on('click', function() {
        const currentText = $(this).text();
        const currentClasses = $(this).attr('class');
        const $editable = $('<div contenteditable="true" class="inline-edit"></div>').text(currentText);
        $(this).replaceWith($editable);
        $editable.focus();

        $editable.on('blur', function() {
          const newText = $(this).text();
          const $spot = $('<div>').addClass(currentClasses).text(newText);
          $(this).replaceWith($spot);
          fields.excerpt.val(newText);
          updatePreview();
        });
      });

      // Etiket için inline düzenleme
      previewTag.on('click', function() {
        const currentText = $(this).text();
        const currentClasses = $(this).attr('class');
        const $editable = $('<div contenteditable="true" class="inline-edit"></div>').text(currentText);
        $(this).replaceWith($editable);
        $editable.focus();

        $editable.on('blur', function() {
          const newText = $(this).text();
          const $tag = $('<div>').addClass(currentClasses).html("<span></span><span></span><span></span>" + newText);
          $(this).replaceWith($tag);
          fields.tagTitle.val(newText);
          updatePreview();
        });
      });

    

      // Açıklama için tipografi ayarlarını güncelle
      const mansetDescTypography = getMansetDescTypography();
      preview.find('.kanews-slide-spot').css({
        'font-size': mansetDescTypography.font_size,
        'font-weight': mansetDescTypography.font_weight,
        'line-height': mansetDescTypography.line_height,
        'letter-spacing': mansetDescTypography.letter_spacing,
        'text-transform': mansetDescTypography.text_transform
      });
    }

    // Watch checkbox changes specifically
    fields.hideContent.on('change', function() {
      updatePreview();
    });

    // Watch all CSF field changes
    $('.csf-field').on('change keyup', function() {
      updatePreview();
    });

    // Handle window resize for responsive preview
    $(window).on('resize', updatePreview);

    // Initial update
    updatePreview();
  }

  // Yeni tipografi ayarlarını almak için fonksiyon
  function getMansetDescTypography() {
    return {
      font_size: $('[name="kanews_post_options[manset_desc_typography][font-size]"]').val() + 'px' || '',
      font_weight: $('[name="kanews_post_options[manset_desc_typography][font-weight]"]').val() || '',
      line_height: $('[name="kanews_post_options[manset_desc_typography][line-height]"]').val() || '',
      letter_spacing: $('[name="kanews_post_options[manset_desc_typography][letter-spacing]"]').val() + 'px' || '',
      text_transform: $('[name="kanews_post_options[manset_desc_typography][text-transform]"]').val() || ''
    };
  }

})(jQuery);

// KAI Page: Minimal page-switcher (hero collapse + section show)
(function() {
  'use strict';
  function collapseHero() {
    var hero = document.querySelector('.kai-hero');
    if (hero && !hero.classList.contains('is-collapsed')) {
      hero.classList.add('is-collapsed');
    }
    var features = document.getElementById('kaiFeatures');
    if (features) {
      features.classList.add('is-hidden');
    }
  }
  function showSectionById(id) {
    var settings = document.getElementById('kai-settings');
    var feeds = document.getElementById('kai-feeds');
    if (settings) settings.classList.add('is-hidden');
    if (feeds) feeds.classList.add('is-hidden');
    var target = document.getElementById(id);
    if (target) target.classList.remove('is-hidden');
  }
  function initKaiPage() {
    var btnSettings = document.getElementById('kaiSettingsBtn');
    var btnFeeds = document.getElementById('kaiFeedsBtn');
    var btnTasksToggle = document.getElementById('kaiHeroTasksBtn');
    var tasksMenu = document.getElementById('kaiHeroTasksMenu');
    var settingsId = (btnSettings && btnSettings.dataset && btnSettings.dataset.target) ? btnSettings.dataset.target : 'kai-settings';
    var feedsId = (btnFeeds && btnFeeds.dataset && btnFeeds.dataset.target) ? btnFeeds.dataset.target : 'kai-feeds';

    if (btnSettings) {
      btnSettings.addEventListener('click', function(e) {
        e.preventDefault();
        collapseHero();
        showSectionById(settingsId);
        history.replaceState(null, '', '#' + settingsId);
      });
    }
    if (btnFeeds) {
      btnFeeds.addEventListener('click', function(e) {
        e.preventDefault();
        collapseHero();
        showSectionById(feedsId);
        if (tasksMenu) tasksMenu.classList.remove('is-open');
        history.replaceState(null, '', '#' + feedsId);
      });
    }

    // Toggle tasks dropdown
    if (btnTasksToggle && tasksMenu) {
      btnTasksToggle.addEventListener('click', function(e) {
        e.preventDefault();
        tasksMenu.classList.toggle('is-open');
      });
      // Close when clicking outside
      document.addEventListener('click', function(e) {
        if (!tasksMenu.contains(e.target) && e.target !== btnTasksToggle) {
          tasksMenu.classList.remove('is-open');
        }
      });
    }

    // If page opened with a hash, apply it and collapse hero
    if (location.hash) {
      var id = location.hash.replace('#', '');
      if (document.getElementById(id)) {
        collapseHero();
        showSectionById(id);
      }
    }

    // React to hash changes (back/forward navigation)
    window.addEventListener('hashchange', function() {
      var id = location.hash.replace('#', '');
      if (id && document.getElementById(id)) {
        collapseHero();
        showSectionById(id);
      }
    });
  }

  if (document.readyState === 'loading') {
    document.addEventListener('DOMContentLoaded', initKaiPage);
  } else {
    initKaiPage();
  }
})();

(function($) {
  'use strict';

  function initApiTestButtons() {
    const config = window.kanewsAdminConfig || {};
    const ajaxUrl = config.ajaxUrl || (typeof ajaxurl !== 'undefined' ? ajaxurl : '');
    const nonce = config.testNonce || '';

    if (!ajaxUrl || !nonce) {
      return;
    }

    $(document).on('click', '.kanews-ai-test-api', function(e) {
      e.preventDefault();
      const $button = $(this);
      const provider = $button.data('provider');
      if (!provider || $button.prop('disabled')) {
        return;
      }

      const originalText = $button.data('original-text') || $button.text();
      $button.data('original-text', originalText);
      $button.prop('disabled', true).text('Test ediliyor...');

      const $status = $('.kanews-ai-test-status[data-provider="' + provider + '"]');
      updateStatus($status, 'Test ediliyor...', 'info');

      $.ajax({
        url: ajaxUrl,
        method: 'POST',
        dataType: 'json',
        data: {
          action: 'kanews_test_ai_provider',
          provider: provider,
          nonce: nonce
        },
        success: function(response) {
          const ok = response && response.success;
          const message = response && response.data && response.data.message
            ? response.data.message
            : (ok ? 'Bağlantı başarılı.' : 'Bağlantı başarısız.');
          updateStatus($status, message, ok ? 'success' : 'error');
        },
        error: function(xhr) {
          let message = 'Bağlantı başarısız.';
          if (xhr && xhr.responseJSON && xhr.responseJSON.data && xhr.responseJSON.data.message) {
            message = xhr.responseJSON.data.message;
          }
          updateStatus($status, message, 'error');
        },
        complete: function() {
          $button.prop('disabled', false).text(originalText);
        }
      });
    });
  }

  function updateStatus($el, text, state) {
    if (!$el || !$el.length) {
      return;
    }
    $el.removeClass('success error info');
    if (state) {
      $el.addClass(state);
    }
    $el.text(text || '');
  }

  if (document.readyState === 'loading') {
    document.addEventListener('DOMContentLoaded', initApiTestButtons);
  } else {
    initApiTestButtons();
  }
})(jQuery);

// Anniversary Modal Logic
(function($) {
  'use strict';

  $(document).ready(function() {
    // Helper: Get Modal
    function getModal() {
      return $('#kanews-anniversary-modal');
    }

    // Modal'ı kapat
    function closeModal() {
      var $modal = getModal();
      $modal.removeClass('kanews-modal--show');
      setTimeout(function() {
        $modal.remove();
      }, 300);
    }

    // Tamamen tamamlandı
    function completeModal(nonce) {
      if (typeof ajaxurl === 'undefined') {
        closeModal();
        return;
      }
      
      // Butonu disable et
      $('.kanews-anniversary-complete').prop('disabled', true).addClass('disabled');
      
      $.post(ajaxurl, {
        action: 'kanews_complete_anniversary_modal',
        nonce: nonce
      }).always(function() {
        closeModal(); // Her durumda kapat
      });
    }

    // Step göster/gizle
    function showStep(step) {
      var $modal = getModal();
      if ($modal.length === 0) return;

      var totalSteps = 4;
      
      // Tüm step'leri gizle
      $modal.find('.kanews-modal__step').removeClass('kanews-modal__step--active').css('display', 'none');
      
      // Seçilen step'i göster
      var $targetStep = $modal.find('.kanews-modal__step[data-step="' + step + '"]');
      if ($targetStep.length > 0) {
        $targetStep.addClass('kanews-modal__step--active').css('display', 'block');
      }
      
      // Progress bar güncelle
      var progress = (step / totalSteps) * 100;
      $modal.find('.kanews-modal__progress-fill').css('width', progress + '%');
      
      // Progress steps güncelle
      $modal.find('.kanews-modal__progress-step').removeClass('active');
      $modal.find('.kanews-modal__progress-step').each(function(index) {
        if (index + 1 <= step) {
          $(this).addClass('active');
        }
      });
      
      $modal.data('current-step', step);
    }

    // Initial Setup
    var $modal = getModal();
    if ($modal.length > 0) {
      showStep(1);
      $modal.addClass('kanews-modal--show');
      $modal.data('current-step', 1);
    }

    // Event Delegation - İleri Butonu
    $(document).on('click', '.kanews-modal__next', function(e) {
      e.preventDefault();
      var $modal = getModal();
      var currentStep = $modal.data('current-step') || 1;
      var nextStep = currentStep + 1;
      if (nextStep <= 4) {
        showStep(nextStep);
      }
    });

    // Event Delegation - Geri Butonu
    $(document).on('click', '.kanews-modal__prev', function(e) {
      e.preventDefault();
      var $modal = getModal();
      var currentStep = $modal.data('current-step') || 1;
      var prevStep = currentStep - 1;
      if (prevStep >= 1) {
        showStep(prevStep);
      }
    });

    // Event Delegation - Tamamla Butonu
    $(document).on('click', '.kanews-anniversary-complete', function(e) {
      e.preventDefault();
      var nonce = $(this).data('nonce');
      if (nonce) {
        completeModal(nonce);
      } else {
        closeModal();
      }
    });

    // Event Delegation - Overlay Tıklama
    $(document).on('click', '#kanews-anniversary-modal', function(e) {
      if ($(e.target).is('.kanews-modal-overlay')) {
        e.preventDefault();
        closeModal();
      }
    });
    
    // Event Delegation - Skip/Daha Sonra
    $(document).on('click', '.kanews-anniversary-skip', function(e) {
      e.preventDefault();
      var nonce = $(this).data('nonce');
      if (nonce) {
        completeModal(nonce);
      } else {
        closeModal();
      }
    });

  });
})(jQuery);

// Manşet Görseli Oluştur
(function($) {
  'use strict';

  $(document).ready(function() {
    const $generateDesktopBtn = $('#kanews-generate-hero-desktop');
    const $generateMobileBtn = $('#kanews-generate-hero-mobile');
    const $statusDiv = $('#kanews-hero-image-status');

    if (!$generateDesktopBtn.length && !$generateMobileBtn.length) {
      return;
    }

    function getPostId() {
      // Gutenberg editor
      if (wp.data && wp.data.select('core/editor')) {
        return wp.data.select('core/editor').getCurrentPostId();
      }
      // Classic editor
      const postIdInput = $('#post_ID');
      return postIdInput.length ? parseInt(postIdInput.val(), 10) : 0;
    }

    function getFieldValue(fieldName) {
      // Önce direkt name attribute ile dene
      let $field = $('[name="kanews_post_options[' + fieldName + ']"]');
      
      // Eğer bulunamazsa, textarea olabilir
      if ($field.length === 0) {
        $field = $('textarea[name="kanews_post_options[' + fieldName + ']"]');
      }
      
      // Hala bulunamazsa, input olarak dene
      if ($field.length === 0) {
        $field = $('input[name="kanews_post_options[' + fieldName + ']"]');
      }
      
      if ($field.length === 0) {
        return '';
      }

      // Media field
      if ($field.closest('.csf-field-media').length) {
        const $hiddenInput = $field.closest('.csf-field-media').find('input[type="hidden"]');
        if ($hiddenInput.length) {
          const value = $hiddenInput.val();
          if (value) {
            try {
              const parsed = JSON.parse(value);
              return parsed.id || parsed.url || value;
            } catch (e) {
              return value;
            }
          }
        }
        return '';
      }

      // Color field
      if ($field.closest('.csf-field-color').length) {
        return $field.val() || '';
      }

      // Slider field
      if ($field.closest('.csf-field-slider').length) {
        return $field.val() || '';
      }

      // Select field
      if ($field.is('select') || $field.closest('.csf-field-select').length) {
        return $field.val() || '';
      }

      // Textarea field
      if ($field.is('textarea')) {
        return $field.val() ? $field.val().trim() : '';
      }

      // Regular input (text, etc.)
      return $field.val() ? $field.val().trim() : '';
    }

    function getMediaFieldId(fieldName) {
      // CSF media field'ı ayrı input'lar kullanıyor: [id], [url], [thumbnail] vb.
      // Önce direkt [id] input'unu bul
      const $idInput = $('[name="kanews_post_options[' + fieldName + '][id]"]');
      if ($idInput.length) {
        const idValue = $idInput.val();
        if (idValue) {
          const numValue = parseInt(idValue, 10);
          if (!isNaN(numValue) && numValue > 0) {
            return numValue;
          }
        }
      }
      
      // Eğer [id] input'u bulunamazsa, field container'ı bul ve içindeki .csf--id input'unu ara
      const $field = $('[name="kanews_post_options[' + fieldName + '][url]"]').closest('.csf-field-media');
      if ($field.length) {
        const $idInputInField = $field.find('input.csf--id');
        if ($idInputInField.length) {
          const idValue = $idInputInField.val();
          if (idValue) {
            const numValue = parseInt(idValue, 10);
            if (!isNaN(numValue) && numValue > 0) {
              return numValue;
            }
          }
        }
      }
      
      return null;
    }

    // Masaüstü görseli oluştur
    $generateDesktopBtn.on('click', function(e) {
      e.preventDefault();
      generateHeroImage('manset_desktop', $generateDesktopBtn);
    });

    // Mobil görseli oluştur
    $generateMobileBtn.on('click', function(e) {
      e.preventDefault();
      generateHeroImage('manset_mobile', $generateMobileBtn);
    });

    function generateHeroImage(targetField, $button) {
      const postId = getPostId();
      if (!postId) {
        showStatus('Yazı ID\'si bulunamadı. Lütfen önce yazıyı kaydedin.', 'error');
        return;
      }

      // Hedef alanın görselini kontrol et, yoksa öne çıkarılan görseli kullanmayı dene
      let imageId = getMediaFieldId(targetField);
      let sourceField = targetField;
      
      // Eğer hedef alanda görsel yoksa, öne çıkarılan görseli kullanmayı dene
      if (!imageId) {
        // Öne çıkarılan görseli kontrol et (backend'de kontrol edilecek)
        imageId = null; // Backend'de kontrol edilecek
      }

      // Mevcut alanları kullan
      const title = getFieldValue('kanews_manset_title');
      // Subtitle için Vurgulanan Başlık alanını kullan
      const subtitle = getFieldValue('kanews_manset_highlight');
      const textColor = getFieldValue('manset_title_color') || '#ffffff';
      const bgColor = getFieldValue('manset_color') || '#000000';
      const bgOpacity = 70; // Varsayılan şeffaflık

      // İmza / logo ayarları
      const signatureImageId = getMediaFieldId('kanews_hero_signature_image');
      const signaturePosition = getFieldValue('kanews_hero_signature_position') || 'top_right';

      // Kırpma ayarları
      const cropWidth = parseInt(getFieldValue('kanews_hero_crop_width') || '0', 10) || 0;
      const cropHeight = parseInt(getFieldValue('kanews_hero_crop_height') || '0', 10) || 0;

      // İçerik hizalama (KAIHero görseli için)
      const textAlign = getFieldValue('kanews_hero_text_align') || 'center';

      if (!title && !subtitle) {
        showStatus('Lütfen "Manşet Başlığı" veya "Vurgulanan Başlık" alanlarından en az birini doldurun.', 'error');
        return;
      }

      // Butonu devre dışı bırak
      const originalButtonText = $button.html();
      $button.prop('disabled', true).html('<span class="dashicons dashicons-update" style="animation: spin 1s linear infinite; margin-top: 3px;"></span> Oluşturuluyor...');
      showStatus('Görsel oluşturuluyor, lütfen bekleyin...', 'info');

      const ajaxUrl = typeof ajaxurl !== 'undefined' ? ajaxurl : (window.kanewsAdminConfig && window.kanewsAdminConfig.ajaxUrl) || '/wp-admin/admin-ajax.php';
      const nonce = (window.kanewsAdminConfig && window.kanewsAdminConfig.aiNonce) || '';

      $.ajax({
        url: ajaxUrl,
        method: 'POST',
        dataType: 'json',
        data: {
          action: 'generate_hero_image',
          post_id: postId,
          image_id: imageId,
          source_field: sourceField, // Hangi alandan alındığını gönder
          title: title,
          subtitle: subtitle,
          text_color: textColor,
          bg_color: bgColor,
          bg_opacity: bgOpacity,
          signature_image_id: signatureImageId,
          signature_position: signaturePosition,
          crop_width: cropWidth,
          crop_height: cropHeight,
          text_align: textAlign,
          nonce: nonce
        },
        success: function(response) {
          if (response.success) {
            showStatus('Manşet görseli başarıyla oluşturuldu!', 'success');
            
            // Oluşturulan görseli kaynak alana (manset_desktop veya manset_mobile) kaydet
            const generatedImageId = response.data.image_id;
            const generatedImageUrl = response.data.image_url;
            const targetField = response.data.source_field || sourceField; // PHP'den dönen alan adı
            
            // CSF media field'ı güncelle (kaynak alan)
            const $targetField = $('[name="kanews_post_options[' + targetField + '][id]"]').closest('.csf-field-media');
            if ($targetField.length) {
              // ID input'unu güncelle
              $targetField.find('input.csf--id').val(generatedImageId);
              // URL input'unu güncelle
              $targetField.find('input.csf--url').val(generatedImageUrl);
              // Thumbnail input'unu güncelle
              $targetField.find('input.csf--thumbnail').val(generatedImageUrl);
              // Preview'ı güncelle
              $targetField.find('.csf--preview img').attr('src', generatedImageUrl).show();
              $targetField.find('.csf--preview').show();
              $targetField.find('.csf--button').text('Değiştir');
              
              // CSF'yi tetikle
              if (typeof csf !== 'undefined' && csf.funcs) {
                csf.funcs.notify();
              }

              // Manşet önizlemeyi canlı güncelle (kanews-manset-preview)
              // İlgili URL input'una change tetikleyerek updatePreview fonksiyonunu koştur
              const $urlInput = $('[name="kanews_post_options[' + targetField + '][url]"]');
              if ($urlInput.length) {
                // Bu görselin KAI ile otomatik oluşturulduğunu global flag ile işaretle
                window.kanewsKAIHeroGenerated = true;
                $urlInput.val(generatedImageUrl).trigger('change');
              }
            }
            
            // Oluşturulan görseli ayrı bir alana da kaydet (opsiyonel)
            const $generatedField = $('[name="kanews_post_options[kanews_hero_generated_image]"]').closest('.csf-field-media');
            if ($generatedField.length) {
              const mediaData = {
                id: generatedImageId,
                url: generatedImageUrl,
                thumbnail: generatedImageUrl
              };
              
              $generatedField.find('input.csf--id').val(generatedImageId);
              $generatedField.find('input.csf--url').val(generatedImageUrl);
              $generatedField.find('input.csf--thumbnail').val(generatedImageUrl);
              $generatedField.find('.csf--preview img').attr('src', generatedImageUrl).show();
              $generatedField.find('.csf--preview').show();
            }
            
            // Sayfayı yenilemeden, sadece status göster
            showStatus('Manşet görseli oluşturuldu ve alana işlendi. Değişiklikleri kaydetmek için yazıyı güncelleyebilirsiniz.', 'success');
          } else {
            const message = response.data && response.data.message 
              ? response.data.message 
              : 'Görsel oluşturulamadı.';
            showStatus(message, 'error');
          }
        },
        error: function(xhr) {
          let message = 'Bir hata oluştu.';
          if (xhr.responseJSON && xhr.responseJSON.data && xhr.responseJSON.data.message) {
            message = xhr.responseJSON.data.message;
          }
          showStatus(message, 'error');
        },
        complete: function() {
          // Buton metnini geri yükle
          if (targetField === 'manset_desktop') {
            $button.prop('disabled', false).html('<span class="dashicons dashicons-desktop" style="margin-top: 3px;"></span> Masaüstü Oluştur');
          } else {
            $button.prop('disabled', false).html('<span class="dashicons dashicons-smartphone" style="margin-top: 3px;"></span> Mobil Oluştur');
          }
        }
      });
    }

    function showStatus(message, type) {
      $statusDiv
        .removeClass('success error info')
        .addClass(type)
        .html(message)
        .show();
    }
  });
})(jQuery);