

<?php $__env->startSection('header-title', 'Yeni Blog Yazısı'); ?>

<?php $__env->startPush('styles'); ?>
<link href="https://cdn.quilljs.com/1.3.6/quill.snow.css" rel="stylesheet">
<style>
/* Editor Styles */
.editor-header { display: flex; justify-content: space-between; align-items: center; margin-bottom: 12px; }
.editor-label { font-weight: 600; color: var(--gray-900); font-size: 14px; }
.editor-mode-toggle { display: flex; gap: 0; border: 1px solid var(--gray-300); border-radius: 6px; overflow: hidden; }
.mode-btn { padding: 6px 12px; font-size: 12px; font-weight: 500; border: none; background: var(--gray-50); color: var(--gray-700); cursor: pointer; transition: all 0.2s ease; }
.mode-btn:not(:last-child) { border-right: 1px solid var(--gray-300); }
.mode-btn:hover { background: var(--gray-100); }
.mode-btn.mode-btn-active { background: var(--primary); color: white; }
.editor-wrapper { border: 1px solid var(--gray-300); border-radius: 8px; overflow: hidden; background: white; }
.quill-editor { min-height: 200px; max-height: 500px; overflow-y: auto; font-size: 14px; line-height: 1.6; }
.source-editor { display: none; width: 100%; min-height: 200px; max-height: 500px; padding: 12px; font-size: 13px; font-family: 'Courier New', monospace; border: none; background: #1e1e1e; color: #d4d4d4; resize: vertical; }
.field-error { color: var(--danger); font-size: 12px; margin-top: 8px; }

.tool-section { background: var(--gray-50); border: 1px solid var(--gray-200); border-radius: 8px; padding: 16px; margin-bottom: 16px; }
.tool-section h3 { font-size: 14px; font-weight: 600; color: var(--gray-900); margin-bottom: 12px; display: flex; align-items: center; gap: 8px; }
.tool-section h3 svg { width: 18px; height: 18px; color: var(--primary); }
.tool-btn { padding: 8px 16px; background: var(--primary); color: white; border: none; border-radius: 6px; font-size: 13px; font-weight: 500; cursor: pointer; transition: all 0.2s ease; display: inline-flex; align-items: center; gap: 6px; }
.tool-btn:hover { filter: brightness(0.9); }
.tool-btn:disabled { background: var(--gray-400); cursor: not-allowed; }
.tool-btn.secondary { background: var(--gray-200); color: var(--gray-900); }
.seo-score-badge { width: 60px; height: 60px; border-radius: 50%; display: flex; align-items: center; justify-content: center; font-size: 20px; font-weight: 700; color: white; }
.seo-score-badge.grade-a { background: #10b981; }
.seo-score-badge.grade-b { background: #3b82f6; }
.seo-score-badge.grade-c { background: #f59e0b; }
.seo-score-badge.grade-d { background: #f97316; }
.seo-score-badge.grade-e, .seo-score-badge.grade-f { background: #ef4444; }
.seo-breakdown-item { display: flex; align-items: center; justify-content: space-between; padding: 8px 0; border-bottom: 1px solid var(--gray-200); }
.seo-breakdown-item:last-child { border-bottom: none; }
.seo-breakdown-bar { width: 100px; height: 6px; background: var(--gray-200); border-radius: 3px; overflow: hidden; margin: 0 12px; }
.seo-breakdown-bar-fill { height: 100%; border-radius: 3px; transition: width 0.3s ease; }
.seo-suggestion { display: flex; align-items: flex-start; gap: 8px; padding: 8px; border-radius: 6px; margin-bottom: 8px; font-size: 12px; }
.seo-suggestion.error { background: #fef2f2; color: #991b1b; }
.seo-suggestion.warning { background: #fffbeb; color: #92400e; }
.seo-suggestion.info { background: #eff6ff; color: #1e40af; }
.duplicate-warning { background: #fef2f2; border: 1px solid #fecaca; border-radius: 6px; padding: 12px; margin-top: 8px; font-size: 13px; }
.duplicate-warning a { color: var(--primary); text-decoration: none; font-weight: 500; }
.checklist-item { display: flex; align-items: center; gap: 8px; padding: 6px 0; font-size: 13px; }
.checklist-item svg { width: 16px; height: 16px; flex-shrink: 0; }
.checklist-item.pass svg { color: #10b981; }
.checklist-item.fail svg { color: #ef4444; }
.adsense-zone-item { display: flex; align-items: center; gap: 8px; padding: 8px; border: 1px solid var(--gray-200); border-radius: 6px; margin-bottom: 8px; font-size: 13px; }
.overlay-controls { display: grid; grid-template-columns: 1fr 1fr; gap: 12px; margin-top: 12px; }
.overlay-controls label { font-size: 12px; font-weight: 500; color: var(--gray-700); margin-bottom: 4px; display: block; }
.overlay-controls select, .overlay-controls input[type="range"] { width: 100%; padding: 6px 10px; border: 1px solid var(--gray-300); border-radius: 6px; font-size: 13px; }
.loading-spinner { display: inline-block; width: 16px; height: 16px; border: 2px solid rgba(255,255,255,0.3); border-top-color: white; border-radius: 50%; animation: spin 0.8s linear infinite; }
@keyframes spin { to { transform: rotate(360deg); } }
</style>
<?php $__env->stopPush(); ?>

<?php $__env->startSection('content'); ?>
<div class="page-title-block">
    <h1>Yeni Blog Yazısı</h1>
    <p>Askeri platform için yeni içerik oluşturun</p>
</div>

<form action="<?php echo e(route('admin.blog.store')); ?>" method="POST" enctype="multipart/form-data" style="max-width: 960px;" id="blogForm">
    <?php echo csrf_field(); ?>
    <div style="display: grid; grid-template-columns: 2fr 1fr; gap: 24px;">

        
        <div>
            <div class="info-card" style="margin-bottom: 24px;">
                
                <div style="margin-bottom: 16px;">
                    <label style="display:block;font-weight:600;color:var(--gray-900);margin-bottom:8px;">Başlık</label>
                    <input type="text" name="title" id="post_title" value="<?php echo e(old('title')); ?>" required
                        placeholder="Blog yazısı başlığını girin"
                        style="width:100%;padding:10px 14px;border:1px solid var(--gray-300);border-radius:8px;font-size:14px;font-family:inherit;">
                    <?php $__errorArgs = ['title'];
$__bag = $errors->getBag($__errorArgs[1] ?? 'default');
if ($__bag->has($__errorArgs[0])) :
if (isset($message)) { $__messageOriginal = $message; }
$message = $__bag->first($__errorArgs[0]); ?><div style="color:var(--danger);font-size:12px;margin-top:4px;"><?php echo e($message); ?></div><?php unset($message);
if (isset($__messageOriginal)) { $message = $__messageOriginal; }
endif;
unset($__errorArgs, $__bag); ?>
                    <div id="duplicate_warning"></div>
                </div>

                
                <div style="margin-bottom: 16px;">
                    <label style="display:block;font-weight:600;color:var(--gray-900);margin-bottom:8px;">Özet</label>
                    <textarea name="excerpt" id="post_excerpt" rows="3"
                        placeholder="Kısa bir özet yazın (SEO için önemli)..."
                        style="width:100%;padding:10px 14px;border:1px solid var(--gray-300);border-radius:8px;font-size:14px;font-family:inherit;resize:vertical;"><?php echo e(old('excerpt')); ?></textarea>
                    <?php $__errorArgs = ['excerpt'];
$__bag = $errors->getBag($__errorArgs[1] ?? 'default');
if ($__bag->has($__errorArgs[0])) :
if (isset($message)) { $__messageOriginal = $message; }
$message = $__bag->first($__errorArgs[0]); ?><div style="color:var(--danger);font-size:12px;margin-top:4px;"><?php echo e($message); ?></div><?php unset($message);
if (isset($__messageOriginal)) { $message = $__messageOriginal; }
endif;
unset($__errorArgs, $__bag); ?>
                </div>

                
                <div>
                    <div class="editor-header">
                        <label class="editor-label">İçerik</label>
                        <div class="editor-mode-toggle">
                            <button type="button" id="btn_visual" onclick="switchToVisual()" class="mode-btn mode-btn-active">
                                👁️ Görsel
                            </button>
                            <button type="button" id="btn_source" onclick="switchToSource()" class="mode-btn">
                                &lt;/&gt; HTML
                            </button>
                        </div>
                    </div>
                    <input type="hidden" name="content" id="editor_hidden">
                    <div class="editor-wrapper">
                        <div id="editor" class="quill-editor"></div>
                        <textarea id="source_editor" class="source-editor" placeholder="HTML kodunu buraya yazın..."></textarea>
                    </div>
                    <?php $__errorArgs = ['content'];
$__bag = $errors->getBag($__errorArgs[1] ?? 'default');
if ($__bag->has($__errorArgs[0])) :
if (isset($message)) { $__messageOriginal = $message; }
$message = $__bag->first($__errorArgs[0]); ?><div class="field-error"><?php echo e($message); ?></div><?php unset($message);
if (isset($__messageOriginal)) { $message = $__messageOriginal; }
endif;
unset($__errorArgs, $__bag); ?>
                </div>
            </div>

            
            <div class="info-card">
                <h2 style="margin-bottom:16px;">SEO Ayarları</h2>
                <div style="margin-bottom:16px;">
                    <label style="display:block;font-weight:600;color:var(--gray-900);margin-bottom:8px;">Meta Başlığı</label>
                    <input type="text" name="meta_title" id="meta_title" value="<?php echo e(old('meta_title')); ?>"
                        placeholder="Arama motorları için başlık (max 60 karakter)..."
                        style="width:100%;padding:10px 14px;border:1px solid var(--gray-300);border-radius:8px;font-size:14px;font-family:inherit;">
                    <div style="font-size:11px;color:var(--gray-500);margin-top:4px;"><span id="meta_title_count">0</span>/60 karakter</div>
                    <?php $__errorArgs = ['meta_title'];
$__bag = $errors->getBag($__errorArgs[1] ?? 'default');
if ($__bag->has($__errorArgs[0])) :
if (isset($message)) { $__messageOriginal = $message; }
$message = $__bag->first($__errorArgs[0]); ?><div style="color:var(--danger);font-size:12px;margin-top:4px;"><?php echo e($message); ?></div><?php unset($message);
if (isset($__messageOriginal)) { $message = $__messageOriginal; }
endif;
unset($__errorArgs, $__bag); ?>
                </div>
                <div>
                    <label style="display:block;font-weight:600;color:var(--gray-900);margin-bottom:8px;">Meta Açıklaması</label>
                    <textarea name="meta_description" id="meta_description" rows="2"
                        placeholder="Arama sonuçlarında görünecek açıklama (max 160 karakter)..."
                        style="width:100%;padding:10px 14px;border:1px solid var(--gray-300);border-radius:8px;font-size:14px;font-family:inherit;resize:vertical;"><?php echo e(old('meta_description')); ?></textarea>
                    <div style="font-size:11px;color:var(--gray-500);margin-top:4px;"><span id="meta_desc_count">0</span>/160 karakter</div>
                    <?php $__errorArgs = ['meta_description'];
$__bag = $errors->getBag($__errorArgs[1] ?? 'default');
if ($__bag->has($__errorArgs[0])) :
if (isset($message)) { $__messageOriginal = $message; }
$message = $__bag->first($__errorArgs[0]); ?><div style="color:var(--danger);font-size:12px;margin-top:4px;"><?php echo e($message); ?></div><?php unset($message);
if (isset($__messageOriginal)) { $message = $__messageOriginal; }
endif;
unset($__errorArgs, $__bag); ?>
                </div>
            </div>
        </div>

        
        <div>
            
            <div class="tool-section">
                <h3>
                    <svg fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 19v-6a2 2 0 00-2-2H5a2 2 0 00-2 2v6a2 2 0 002 2h2a2 2 0 002-2zm0 0V9a2 2 0 012-2h2a2 2 0 012 2v10m-6 0a2 2 0 002 2h2a2 2 0 002-2m0 0V5a2 2 0 012-2h2a2 2 0 012 2v14a2 2 0 01-2 2h-2a2 2 0 01-2-2z"/></svg>
                    SEO Analizi
                </h3>
                <button type="button" class="tool-btn" id="check_seo_btn" onclick="checkSeo()">
                    <svg style="width:16px;height:16px;" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 12l2 2 4-4m6 2a9 9 0 11-18 0 9 9 0 0118 0z"/></svg>
                    SEO Puanı Hesapla
                </button>
                <div id="seo_result"></div>
            </div>

            
            <div class="tool-section">
                <h3>
                    <svg fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 12l2 2 4-4m6 2a9 9 0 11-18 0 9 9 0 0118 0z"/></svg>
                    Yayın Kontrol Listesi
                </h3>
                <button type="button" class="tool-btn secondary" id="check_publish_btn" onclick="checkPublish()">Kontrol Et</button>
                <div id="publish_checklist"></div>
            </div>

            
            <div class="info-card" style="margin-bottom:24px;">
                <h2 style="margin-bottom:16px;">Öne Çıkan Görsel</h2>
                <div style="border:2px dashed var(--gray-300);border-radius:8px;padding:20px;text-align:center;">
                    <input type="file" name="featured_image" accept="image/*" id="featured_image" style="display:none;">
                    <label for="featured_image" style="cursor:pointer;display:block;">
                        <svg style="width:40px;height:40px;margin:0 auto 8px;color:var(--gray-400);" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4 16l4.586-4.586a2 2 0 012.828 0L16 16m-2-2l1.586-1.586a2 2 0 012.828 0L20 14m-6-6h.01M6 20h12a2 2 0 002-2V6a2 2 0 00-2-2H6a2 2 0 00-2 2v12a2 2 0 002 2z"/>
                        </svg>
                        <div style="font-size:14px;color:var(--gray-600);">
                            <span style="color:var(--primary);font-weight:500;">Görsel seç</span> veya sürükle
                        </div>
                        <div style="font-size:12px;color:var(--gray-500);margin-top:4px;">JPEG, PNG, WebP (max 2MB)</div>
                    </label>
                </div>
                <div id="image-preview" style="margin-top:12px;"></div>

                
                <div id="overlay_tool" style="display:none;margin-top:16px;padding-top:16px;border-top:1px solid var(--gray-200);">
                    <h3 style="font-size:13px;font-weight:600;margin-bottom:12px;">Manşet Yazı Ekle</h3>
                    <div style="margin-bottom:16px;padding:12px;background:#f0f9ff;border:1px solid #bfdbfe;border-radius:8px;">
                        <p style="font-size:12px;color:#1e40af;margin:0;line-height:1.4;">💡 Yazı otomatik olarak görsele uyum sağlar. Fotoğraf boyutundan bağımsız olarak yazı daima uygun boyutlarda görüntülenir.</p>
                    </div>
                    <input type="text" id="overlay_text" placeholder="Manşet şeklinde büyük yazı (örn: BAŞLIK, ÖNEMLİ HABER)"
                        style="width:100%;padding:10px 14px;border:1px solid var(--gray-300);border-radius:6px;font-size:14px;margin-bottom:12px;font-weight:500;">
                    <div class="overlay-controls">
                        <div>
                            <label>Pozisyon</label>
                            <select id="overlay_position">
                                <option value="top-left">Üst Sol</option>
                                <option value="top-center">Üst Orta</option>
                                <option value="top-right">Üst Sağ</option>
                                <option value="center">Orta (Manşet)</option>
                                <option value="bottom-left">Alt Sol</option>
                                <option value="bottom-center" selected>Alt Orta</option>
                                <option value="bottom-right">Alt Sağ</option>
                            </select>
                        </div>
                        <div>
                            <label>Arka Plan Şeffaflığı: <span id="opacity_value">60</span>%</label>
                            <input type="range" id="overlay_opacity" min="30" max="90" value="60"
                                oninput="document.getElementById('opacity_value').textContent=this.value">
                            <p style="font-size:11px;color:#6b7280;margin-top:4px;">30% = Açık (yazı belirgin), 90% = Koyu (daha kapalı)</p>
                        </div>
                        <div>
                            <label>Yazı Boyutu</label>
                            <select id="overlay_font_size">
                                <option value="24">Küçük</option>
                                <option value="32" selected>Orta (Önerilen)</option>
                                <option value="40">Büyük</option>
                                <option value="48">Çok Büyük</option>
                            </select>
                            <p style="font-size:11px;color:#6b7280;margin-top:4px;">Yazı boyutunu görsele uyacak şekilde seçin</p>
                        </div>
                    </div>
                    <div style="display:flex;gap:8px;margin-top:16px;">
                        <button type="button" class="tool-btn" onclick="previewOverlay()">
                            <svg style="width:14px;height:14px;" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15 12a3 3 0 11-6 0 3 3 0 016 0z"/><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M2.458 12C3.732 7.943 7.523 5 12 5c4.478 0 8.268 2.943 9.542 7-1.274 4.057-5.064 7-9.542 7-4.477 0-8.268-2.943-9.542-7z"/></svg>
                            Önizle
                        </button>
                        <button type="button" class="tool-btn secondary" onclick="applyOverlay()">Uygula</button>
                    </div>
                </div>
            </div>

            
            <div class="info-card" style="margin-bottom:24px;">
                <div style="display:flex;justify-content:space-between;align-items:center;margin-bottom:16px;">
                    <h2 style="margin:0;border:none;padding:0;">AdSense Alanları</h2>
                    <a href="<?php echo e(route('admin.adsense.index')); ?>" target="_blank"
                        style="font-size:13px;color:var(--secondary);text-decoration:none;">Yönet →</a>
                </div>
                <?php if($adSenseZones->count() > 0): ?>
                    <?php $__currentLoopData = $adSenseZones; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $zone): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
                        <div class="adsense-zone-item">
                            <input type="checkbox" name="adsense_zones[]" value="<?php echo e($zone->id); ?>" id="zone_<?php echo e($zone->id); ?>">
                            <label for="zone_<?php echo e($zone->id); ?>" style="flex:1;cursor:pointer;">
                                <strong><?php echo e($zone->name); ?></strong>
                                <span style="color:var(--gray-500);font-size:11px;">(<?php echo e($zone->location); ?>)</span>
                            </label>
                        </div>
                    <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>
                <?php else: ?>
                    <div style="padding:16px;text-align:center;background:var(--gray-50);border-radius:8px;border:1px dashed var(--gray-300);">
                        <p style="color:var(--gray-600);font-size:13px;margin:0;">Henüz aktif AdSense alanı yok.</p>
                    </div>
                <?php endif; ?>
            </div>

            
            <div class="info-card" style="margin-bottom:24px;">
                <h2 style="margin-bottom:16px;">Kategori</h2>
                <select name="category_id" required style="width:100%;padding:10px 14px;border:1px solid var(--gray-300);border-radius:8px;font-size:14px;font-family:inherit;">
                    <option value="">Kategori seçin</option>
                    <?php $__currentLoopData = $categories; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $category): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
                        <option value="<?php echo e($category->id); ?>" <?php echo e(old('category_id') == $category->id ? 'selected' : ''); ?>><?php echo e($category->name); ?></option>
                    <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>
                </select>
                <?php $__errorArgs = ['category_id'];
$__bag = $errors->getBag($__errorArgs[1] ?? 'default');
if ($__bag->has($__errorArgs[0])) :
if (isset($message)) { $__messageOriginal = $message; }
$message = $__bag->first($__errorArgs[0]); ?><div style="color:var(--danger);font-size:12px;margin-top:4px;"><?php echo e($message); ?></div><?php unset($message);
if (isset($__messageOriginal)) { $message = $__messageOriginal; }
endif;
unset($__errorArgs, $__bag); ?>
                <a href="<?php echo e(route('admin.blog-categories.create')); ?>" style="display:inline-block;margin-top:8px;font-size:12px;color:var(--primary);">+ Yeni kategori ekle</a>
            </div>

            
            <div class="info-card" style="margin-bottom:24px;">
                <h2 style="margin-bottom:16px;">Durum</h2>
                <div style="display:flex;flex-direction:column;gap:12px;">
                    <label style="display:flex;align-items:center;gap:8px;cursor:pointer;font-size:14px;">
                        <input type="radio" name="status" value="draft" <?php echo e(old('status','draft')==='draft'?'checked':''); ?>>
                        <span>📝 Taslak</span>
                    </label>
                    <label style="display:flex;align-items:center;gap:8px;cursor:pointer;font-size:14px;">
                        <input type="radio" name="status" value="published" <?php echo e(old('status')==='published'?'checked':''); ?> id="status_published">
                        <span>🌐 Yayında</span>
                    </label>
                    <label style="display:flex;align-items:center;gap:8px;cursor:pointer;font-size:14px;">
                        <input type="radio" name="status" value="archived" <?php echo e(old('status')==='archived'?'checked':''); ?>>
                        <span>📦 Arşiv</span>
                    </label>
                </div>
            </div>

            
            <div style="display:flex;gap:12px;">
                <button type="submit" style="flex:1;padding:12px 20px;background:var(--primary);color:white;border:none;border-radius:8px;font-weight:600;font-size:14px;cursor:pointer;">
                    Oluştur
                </button>
                <a href="<?php echo e(route('admin.blog.index')); ?>" style="flex:1;padding:12px 20px;background:var(--gray-200);color:var(--gray-900);border-radius:8px;font-weight:600;font-size:14px;text-decoration:none;text-align:center;">
                    İptal
                </a>
            </div>
        </div>
    </div>
</form>

<script src="https://cdn.quilljs.com/1.3.6/quill.js"></script>
<script>
let currentImageFile = null;
let duplicateCheckTimeout = null;
let quillEditor = null;

document.addEventListener('DOMContentLoaded', function() {
    quillEditor = new Quill('#editor', {
        theme: 'snow',
        modules: {
            toolbar: [
                [{ header: [1, 2, 3, 4, 5, 6, false] }],
                ['bold', 'italic', 'underline', 'strike'],
                [{ align: [] }],
                [{ list: 'ordered' }, { list: 'bullet' }],
                ['blockquote', 'code-block'],
                ['link', 'image'],
                [{ color: [] }, { background: [] }],
                ['clean']
            ]
        },
        placeholder: 'Blog yazısının içeriğini yazın...'
    });
});

let editorMode = 'visual'; // 'visual' or 'source'

function switchToVisual() {
    if (editorMode === 'visual') return;
    const sourceEditor = document.getElementById('source_editor');
    const editor = document.getElementById('editor');
    const btnVisual = document.getElementById('btn_visual');
    const btnSource = document.getElementById('btn_source');
    
    // Kaynaktan Quill'e aktar
    quillEditor.clipboard.dangerouslyPasteHTML(sourceEditor.value);
    
    // UI güncelle
    sourceEditor.style.display = 'none';
    editor.style.display = 'block';
    btnVisual.classList.add('mode-btn-active');
    btnSource.classList.remove('mode-btn-active');
    
    editorMode = 'visual';
}

function switchToSource() {
    if (editorMode === 'source') return;
    const sourceEditor = document.getElementById('source_editor');
    const editor = document.getElementById('editor');
    const btnVisual = document.getElementById('btn_visual');
    const btnSource = document.getElementById('btn_source');
    
    // Quill'den kaynağa aktar
    sourceEditor.value = quillEditor.root.innerHTML;
    
    // UI güncelle
    editor.style.display = 'none';
    sourceEditor.style.display = 'block';
    btnVisual.classList.remove('mode-btn-active');
    btnSource.classList.add('mode-btn-active');
    
    editorMode = 'source';
}

document.getElementById('meta_title').addEventListener('input', function() {
    document.getElementById('meta_title_count').textContent = this.value.length;
});
document.getElementById('meta_description').addEventListener('input', function() {
    document.getElementById('meta_desc_count').textContent = this.value.length;
});

document.getElementById('post_title').addEventListener('input', function() {
    clearTimeout(duplicateCheckTimeout);
    const title = this.value.trim();
    if (title.length < 5) { document.getElementById('duplicate_warning').innerHTML = ''; return; }
    duplicateCheckTimeout = setTimeout(() => checkDuplicate(title), 500);
});

async function checkDuplicate(title) {
    try {
        const res = await fetch('<?php echo e(route('admin.blog.check_duplicate')); ?>', {
            method: 'POST',
            headers: { 'Content-Type': 'application/json', 'X-CSRF-TOKEN': '<?php echo e(csrf_token()); ?>' },
            body: JSON.stringify({ title, exclude_id: null })
        });
        const result = await res.json();
        if (result.success && result.has_duplicates) {
            let html = '<div class="duplicate-warning"><strong>⚠️ Benzer başlıklar bulundu:</strong><ul style="margin:8px 0 0 20px;padding:0;">';
            result.duplicates.forEach(d => { html += `<li><a href="/admin/blog/${d.id}/edit" target="_blank">${d.title}</a> (${d.similarity}%)</li>`; });
            html += '</ul></div>';
            document.getElementById('duplicate_warning').innerHTML = html;
        } else { document.getElementById('duplicate_warning').innerHTML = ''; }
    } catch(e) { console.error(e); }
}

document.getElementById('featured_image').addEventListener('change', function(e) {
    const file = e.target.files[0];
    if (file) {
        currentImageFile = file;
        const reader = new FileReader();
        reader.onload = function(e) {
            document.getElementById('image-preview').innerHTML =
                '<img src="' + e.target.result + '" style="width:100%;max-width:100%;height:auto;border-radius:8px;margin-bottom:12px;display:block;object-fit:contain;">' +
                '<button type="button" onclick="removeImage()" style="width:100%;padding:8px 12px;background:rgba(239,68,68,0.1);color:var(--danger);border:none;border-radius:6px;font-size:13px;font-weight:500;cursor:pointer;">Kaldır</button>';
            document.getElementById('overlay_tool').style.display = 'block';
        };
        reader.readAsDataURL(file);
    }
});

function removeImage() {
    document.getElementById('featured_image').value = '';
    document.getElementById('image-preview').innerHTML = '';
    document.getElementById('overlay_tool').style.display = 'none';
    currentImageFile = null;
}

async function checkSeo() {
    const btn = document.getElementById('check_seo_btn');
    const resultDiv = document.getElementById('seo_result');
    btn.disabled = true;
    btn.innerHTML = '<span class="loading-spinner"></span> Analiz ediliyor...';
    const data = {
        title: document.getElementById('post_title').value,
        excerpt: document.getElementById('post_excerpt').value,
        content: quillEditor.root.innerHTML,
        meta_title: document.getElementById('meta_title').value,
        meta_description: document.getElementById('meta_description').value
    };
    try {
        const res = await fetch('<?php echo e(route('admin.tools.seo_score')); ?>', {
            method: 'POST',
            headers: { 'Content-Type': 'application/json', 'X-CSRF-TOKEN': '<?php echo e(csrf_token()); ?>' },
            body: JSON.stringify(data)
        });
        const result = await res.json();
        if (result.success) {
            displaySeoResult(result.data);
            if (result.data.meta_suggestions) {
                const mt = document.getElementById('meta_title');
                const md = document.getElementById('meta_description');
                if (!mt.value.trim()) { mt.value = result.data.meta_suggestions.meta_title; document.getElementById('meta_title_count').textContent = mt.value.length; }
                if (!md.value.trim()) { md.value = result.data.meta_suggestions.meta_description; document.getElementById('meta_desc_count').textContent = md.value.length; }
            }
        } else { resultDiv.innerHTML = '<div style="color:var(--danger);font-size:13px;">Hata: ' + result.message + '</div>'; }
    } catch(e) { resultDiv.innerHTML = '<div style="color:var(--danger);font-size:13px;">Hata: ' + e.message + '</div>'; }
    btn.disabled = false;
    btn.innerHTML = `<svg style="width:16px;height:16px;" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 12l2 2 4-4m6 2a9 9 0 11-18 0 9 9 0 0118 0z"/></svg> SEO Puanı Hesapla`;
}

function displaySeoResult(data) {
    const resultDiv = document.getElementById('seo_result');
    let sg = '';
    if (data.suggestions && data.suggestions.length > 0) {
        sg = '<div style="margin-top:12px;padding-top:12px;border-top:1px solid var(--gray-200);"><h4 style="font-size:12px;font-weight:600;margin-bottom:8px;">Öneriler:</h4>';
        data.suggestions.forEach(s => {
            const icon = s.level === 'error' ? '❌' : s.level === 'warning' ? '⚠️' : 'ℹ️';
            sg += `<div class="seo-suggestion ${s.level}">${icon} ${s.message}</div>`;
        });
        sg += '</div>';
    }
    const gc = 'grade-' + data.grade.toLowerCase();
    resultDiv.innerHTML = `
        <div style="background:white;border-radius:8px;padding:16px;margin-top:12px;">
            <div style="display:flex;align-items:center;justify-content:space-between;margin-bottom:12px;">
                <div><div style="font-size:12px;color:var(--gray-600);font-weight:500;">Toplam Skor</div><div style="font-size:28px;font-weight:700;margin-top:4px;">${data.score}</div></div>
                <div class="seo-score-badge ${gc}">${data.grade}</div>
            </div>
            <div>
                <div class="seo-breakdown-item"><div style="font-size:13px;color:var(--gray-700);">Başlık</div><div style="display:flex;align-items:center;gap:8px;"><div class="seo-breakdown-bar"><div class="seo-breakdown-bar-fill" style="width:${data.breakdown.title}%;background:${data.breakdown.title>60?'#10b981':'#f59e0b'};"></div></div><span style="font-size:13px;">${data.breakdown.title}%</span></div></div>
                <div class="seo-breakdown-item"><div style="font-size:13px;color:var(--gray-700);">İçerik</div><div style="display:flex;align-items:center;gap:8px;"><div class="seo-breakdown-bar"><div class="seo-breakdown-bar-fill" style="width:${data.breakdown.content}%;background:${data.breakdown.content>60?'#10b981':'#f59e0b'};"></div></div><span style="font-size:13px;">${data.breakdown.content}%</span></div></div>
                <div class="seo-breakdown-item"><div style="font-size:13px;color:var(--gray-700);">Meta</div><div style="display:flex;align-items:center;gap:8px;"><div class="seo-breakdown-bar"><div class="seo-breakdown-bar-fill" style="width:${data.breakdown.meta}%;background:${data.breakdown.meta>60?'#10b981':'#f59e0b'};"></div></div><span style="font-size:13px;">${data.breakdown.meta}%</span></div></div>
            </div>
            ${sg}
        </div>`;
}

async function checkPublish() {
    const btn = document.getElementById('check_publish_btn');
    const resultDiv = document.getElementById('publish_checklist');
    btn.disabled = true;
    btn.innerHTML = '<span class="loading-spinner"></span>';
    const data = {
        title: document.getElementById('post_title').value,
        content: quillEditor.root.innerHTML,
        excerpt: document.getElementById('post_excerpt').value,
        meta_title: document.getElementById('meta_title').value,
        meta_description: document.getElementById('meta_description').value,
        featured_image: currentImageFile ? 'selected' : null,
    };
    try {
        const res = await fetch('<?php echo e(route('admin.blog.publish_checklist')); ?>', {
            method: 'POST',
            headers: { 'Content-Type': 'application/json', 'X-CSRF-TOKEN': '<?php echo e(csrf_token()); ?>' },
            body: JSON.stringify(data)
        });
        const result = await res.json();
        if (result.success) { displayPublishChecklist(result); }
        else { resultDiv.innerHTML = '<div style="color:var(--danger);font-size:13px;">Hata olustu</div>'; }
    } catch(e) { resultDiv.innerHTML = '<div style="color:var(--danger);font-size:13px;">' + e.message + '</div>'; }
    btn.disabled = false;
    btn.innerHTML = 'Kontrol Et';
}

function displayPublishChecklist(result) {
    const resultDiv = document.getElementById('publish_checklist');
    const cl = result.checklist;
    const bg = result.can_publish ? '#f0fdf4' : '#fef2f2';
    const border = result.can_publish ? '#bbf7d0' : '#fecaca';
    const msg = result.can_publish ? '✅ Yazı yayınlamaya hazır!' : '⚠️ Düzeltmeler gerekli';
    const items = [
        { key: 'title', label: 'Başlık (min 10 karakter)' },
        { key: 'content', label: 'İçerik (min 300 kelime)' },
        { key: 'excerpt', label: 'Özet' },
        { key: 'meta_title', label: 'Meta Başlığı' },
        { key: 'meta_description', label: 'Meta Açıklaması' },
        { key: 'featured_image', label: 'Öne Çıkan Görsel' },
        { key: 'headings', label: 'H1/H2 Başlıkları' },
    ];
    let itemsHtml = '';
    items.forEach(item => {
        const pass = cl[item.key];
        const icon = pass
            ? `<svg fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M5 13l4 4L19 7"/></svg>`
            : `<svg fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12"/></svg>`;
        itemsHtml += `<div class="checklist-item ${pass?'pass':'fail'}">${icon} ${item.label}</div>`;
    });
    resultDiv.innerHTML = `<div style="background:${bg};border:1px solid ${border};border-radius:6px;padding:12px;margin-top:12px;"><div style="font-size:13px;font-weight:600;margin-bottom:8px;">${msg}</div>${itemsHtml}</div>`;
}

async function previewOverlay() {
    if (!currentImageFile) { alert('Lutfen once gorsel secin.'); return; }
    const text = document.getElementById('overlay_text').value;
    if (!text) { alert('Lutfen gorusel yazisi girin.'); return; }
    
    const btn = event.target;
    btn.disabled = true;
    const origText = btn.textContent;
    btn.textContent = 'Onizleme Yükleniyor...';
    
    const fd = new FormData();
    fd.append('image', currentImageFile);
    fd.append('text', text);
    fd.append('position', document.getElementById('overlay_position').value);
    fd.append('bg_opacity', document.getElementById('overlay_opacity').value);
    fd.append('font_size', document.getElementById('overlay_font_size').value);
    
    try {
        const res = await fetch('<?php echo e(route('admin.tools.img_preview')); ?>', { method: 'POST', headers: { 'X-CSRF-TOKEN': '<?php echo e(csrf_token()); ?>' }, body: fd });
        const result = await res.json();
        if (result.success) {
            document.getElementById('image-preview').innerHTML = `<img src="${result.data.preview}" style="width:100%;max-width:100%;height:auto;border-radius:8px;margin-bottom:12px;object-fit:contain;"><button type="button" onclick="removeImage()" style="width:100%;padding:8px 12px;background:rgba(239,68,68,0.1);color:var(--danger);border:none;border-radius:6px;font-size:13px;cursor:pointer;">Kaldir</button>`;
        } else { alert('Hata: ' + result.message); }
    } catch(e) { alert('Hata: ' + e.message); }
    finally {
        btn.disabled = false;
        btn.textContent = origText;
    }
}

async function applyOverlay() {
    if (!currentImageFile) { alert('Lutfen once gorsel secin.'); return; }
    const text = document.getElementById('overlay_text').value;
    if (!text) { alert('Lutfen yazı girin.'); return; }
    
    const btn = event.target;
    btn.disabled = true;
    const origText = btn.textContent;
    btn.textContent = 'Uygulanıyor...';
    
    const fd = new FormData();
    fd.append('image', currentImageFile);
    fd.append('text', text);
    fd.append('position', document.getElementById('overlay_position').value);
    fd.append('bg_opacity', document.getElementById('overlay_opacity').value);
    fd.append('font_size', document.getElementById('overlay_font_size').value);
    
    try {
        const res = await fetch('<?php echo e(route('admin.tools.img_overlay')); ?>', { method: 'POST', headers: { 'X-CSRF-TOKEN': '<?php echo e(csrf_token()); ?>' }, body: fd });
        const result = await res.json();
        if (result.success) {
            document.getElementById('image-preview').innerHTML = `
                <input type="hidden" name="overlayed_image_path" value="${result.data.path}">
                <div style="position:relative;display:inline-block;width:100%;">
                    <img src="${result.data.url}" style="width:100%;max-width:100%;height:auto;border-radius:8px;margin-bottom:8px;object-fit:contain;">
                    <span style="position:absolute;top:8px;right:8px;background:#10b981;color:#fff;font-size:11px;font-weight:700;padding:3px 8px;border-radius:12px;">✓ Yazı Eklendi</span>
                </div>
                <button type="button" onclick="removeImage()" style="width:100%;padding:8px 12px;background:rgba(239,68,68,0.1);color:var(--danger);border:none;border-radius:6px;font-size:13px;cursor:pointer;">Kaldir</button>`;
        } else { alert('Hata: ' + result.message); }
    } catch(e) { alert('Hata: ' + e.message); }
    finally {
        btn.disabled = false;
        btn.textContent = origText;
    }
}

document.getElementById('blogForm').addEventListener('submit', function(e) {
    // Source modundaysa önce Quill'e senkronize et
    if (editorMode === 'source') {
        quillEditor.clipboard.dangerouslyPasteHTML(document.getElementById('source_editor').value);
    }
    
    const statusPublished = document.getElementById('status_published');
    if (statusPublished && statusPublished.checked) {
        const title = document.getElementById('post_title').value.trim();
        const content = quillEditor.getText().trim();
        const wordCount = content.split(/\s+/).filter(w => w.length > 0).length;
        if (!title || wordCount < 300) {
            e.preventDefault();
            alert('Yayinlamak icin baslik girilmeli ve icerik en az 300 kelime olmalidir.\nMevcut: ' + wordCount + ' kelime');
            return false;
        }
    }
    document.getElementById('editor_hidden').value = quillEditor.root.innerHTML;
});
</script>
<?php $__env->stopSection(); ?>

<?php echo $__env->make('admin.layout', array_diff_key(get_defined_vars(), ['__data' => 1, '__path' => 1]))->render(); ?><?php /**PATH C:\xampp\htdocs\askeribilgiler\resources\views\admin\blog\create.blade.php ENDPATH**/ ?>