(() => {
  document.querySelector('[data-admin-toggle]')?.addEventListener('click', () => document.querySelector('.sidebar')?.classList.toggle('open'));
  document.querySelectorAll('[data-confirm]').forEach(el => el.addEventListener('click', e => {
    if (!confirm(el.dataset.confirm || 'Emin misiniz?')) e.preventDefault();
  }));

  const slugify = value => value
    .toLocaleLowerCase('tr-TR')
    .replace(/ı/g, 'i').replace(/ğ/g, 'g').replace(/ü/g, 'u').replace(/ş/g, 's').replace(/ö/g, 'o').replace(/ç/g, 'c')
    .normalize('NFD').replace(/[\u0300-\u036f]/g, '')
    .replace(/[^a-z0-9]+/g, '-')
    .replace(/^-+|-+$/g, '')
    .slice(0, 180);

  document.querySelectorAll('[data-rich-editor]').forEach(editor => {
    const area = editor.querySelector('[data-editor-area]');
    const source = editor.querySelector('[data-editor-source]');
    const sourceToggle = editor.querySelector('[data-editor-source-toggle]');
    const form = editor.closest('form');
    let sourceMode = false;

    const syncSource = () => {
      if (!sourceMode) source.value = area.innerHTML.trim();
    };
    const syncVisual = () => {
      if (sourceMode) area.innerHTML = source.value;
    };
    const focusArea = () => {
      if (!sourceMode) area.focus();
    };

    area.addEventListener('input', syncSource);
    source.addEventListener('input', syncVisual);

    editor.querySelectorAll('[data-editor-command]').forEach(button => {
      button.addEventListener('click', () => {
        if (sourceMode) return;
        focusArea();
        document.execCommand(button.dataset.editorCommand, false, null);
        syncSource();
      });
    });

    editor.querySelector('[data-editor-block]')?.addEventListener('change', event => {
      if (sourceMode) return;
      focusArea();
      document.execCommand('formatBlock', false, event.target.value);
      syncSource();
      event.target.value = 'p';
    });

    editor.querySelector('[data-editor-link]')?.addEventListener('click', () => {
      if (sourceMode) return;
      const selection = window.getSelection();
      if (!selection || selection.isCollapsed) {
        alert('Önce bağlantı verilecek kelimeyi seçin.');
        return;
      }
      const href = prompt('Bağlantı adresini yazın. Site içi bağlantılar için /hizmetler gibi başlayabilirsiniz:');
      if (!href) return;
      const cleanHref = href.trim();
      if (!(cleanHref.startsWith('/') && !cleanHref.startsWith('//')) && !/^https?:\/\//i.test(cleanHref)) {
        alert('Bağlantı / ile başlamalı veya http:// ya da https:// içermelidir.');
        return;
      }
      focusArea();
      document.execCommand('createLink', false, cleanHref);
      syncSource();
    });

    sourceToggle?.addEventListener('click', () => {
      if (sourceMode) {
        area.innerHTML = source.value;
        source.hidden = true;
        area.hidden = false;
        sourceMode = false;
        sourceToggle.textContent = 'HTML Görünümü';
        area.focus();
      } else {
        source.value = area.innerHTML.trim();
        area.hidden = true;
        source.hidden = false;
        sourceMode = true;
        sourceToggle.textContent = 'Normal Editör';
        source.focus();
      }
    });

    form?.addEventListener('submit', event => {
      if (sourceMode) area.innerHTML = source.value;
      source.value = area.innerHTML.trim();
      if (!source.value.replace(/<[^>]*>/g, '').trim()) {
        event.preventDefault();
        alert('Makale içeriğini yazın.');
        (sourceMode ? source : area).focus();
      }
    });

    editor.richEditorApi = {
      setHtml(html) {
        area.innerHTML = html || '';
        source.value = html || '';
        if (sourceMode) source.value = html || '';
      },
      getHtml() {
        return sourceMode ? source.value : area.innerHTML.trim();
      }
    };
  });

  const writer = document.querySelector('[data-ai-writer]');
  if (writer) {
    const modeButtons = [...writer.querySelectorAll('[data-ai-mode]')];
    const panes = [...writer.querySelectorAll('[data-ai-pane]')];
    const generateButton = writer.querySelector('[data-ai-generate]');
    const status = writer.querySelector('[data-ai-status]');
    const keyword = writer.querySelector('[data-ai-keyword]');
    const promptField = writer.querySelector('[data-ai-prompt]');
    let mode = 'keyword';

    const setMode = newMode => {
      mode = newMode === 'prompt' ? 'prompt' : 'keyword';
      modeButtons.forEach(button => button.classList.toggle('active', button.dataset.aiMode === mode));
      panes.forEach(pane => { pane.hidden = pane.dataset.aiPane !== mode; });
      (mode === 'prompt' ? promptField : keyword)?.focus();
    };
    modeButtons.forEach(button => button.addEventListener('click', () => setMode(button.dataset.aiMode)));

    generateButton?.addEventListener('click', async () => {
      const request = (mode === 'prompt' ? promptField?.value : keyword?.value)?.trim() || '';
      if (!request) {
        alert(mode === 'prompt' ? 'Özel prompt alanını doldurun.' : 'Anahtar kelime veya konu yazın.');
        (mode === 'prompt' ? promptField : keyword)?.focus();
        return;
      }

      const titleInput = document.getElementById('content-title');
      const excerptInput = document.getElementById('content-excerpt');
      const metaTitleInput = document.getElementById('content-meta-title');
      const metaDescriptionInput = document.getElementById('content-meta-description');
      const slugInput = document.getElementById('content-slug');
      const editor = document.querySelector('[data-rich-editor]');
      const existingContent = editor?.richEditorApi?.getHtml()?.replace(/<[^>]*>/g, '').trim() || '';

      if ((titleInput?.value.trim() || existingContent) && !confirm('Editörde mevcut içerik var. Yapay zekâ çıktısıyla değiştirmek istiyor musunuz?')) return;

      generateButton.disabled = true;
      generateButton.textContent = 'Makale hazırlanıyor…';
      status.textContent = 'Gemini içeriği ve SEO alanlarını hazırlıyor. Sayfayı kapatmayın.';
      status.className = 'ai-writer-status muted loading';

      const body = new URLSearchParams({
        _csrf: writer.dataset.csrf || '',
        mode,
        request
      });

      try {
        const response = await fetch(writer.dataset.endpoint, {
          method: 'POST',
          credentials: 'same-origin',
          headers: {'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8'},
          body: body.toString()
        });
        const data = await response.json().catch(() => ({ok: false, message: 'Sunucu geçerli yanıt döndürmedi.'}));
        if (!response.ok || !data.ok) throw new Error(data.message || 'Makale oluşturulamadı.');

        const article = data.article || {};
        if (titleInput) titleInput.value = article.title || '';
        if (excerptInput) excerptInput.value = article.excerpt || '';
        if (metaTitleInput) metaTitleInput.value = article.meta_title || '';
        if (metaDescriptionInput) metaDescriptionInput.value = article.meta_description || '';
        if (slugInput && !slugInput.value.trim()) slugInput.value = slugify(article.title || '');
        editor?.richEditorApi?.setHtml(article.content_html || '');

        status.textContent = data.message || 'Makale taslağı hazırlandı.';
        status.className = 'ai-writer-status success-text';
        document.getElementById('content-title')?.scrollIntoView({behavior: 'smooth', block: 'center'});
      } catch (error) {
        status.textContent = error.message || 'Makale oluşturulamadı.';
        status.className = 'ai-writer-status error-text';
      } finally {
        generateButton.disabled = false;
        generateButton.textContent = 'Yapay Zekâya Yazdır';
      }
    });
  }
})();
