@extends('layouts.public')

@section('title', 'AI İçerik Üretici')

@section('content')
<style>
    .cg-page { max-width: 1100px; margin: 0 auto; padding: 40px 20px; }

    .cg-header { margin-bottom: 32px; }
    .cg-back { color: #6b7280; font-size: 13px; font-weight: 500; display: inline-flex; align-items: center; gap: 4px; margin-bottom: 8px; text-decoration: none; }
    .cg-back:hover { color: #374151; text-decoration: none; }
    .cg-header h1 { font-size: 26px; font-weight: 800; color: #111827; margin-bottom: 4px; }
    .cg-header p { font-size: 13px; color: #6b7280; }

    .cg-grid { display: grid; grid-template-columns: repeat(2, 1fr); gap: 24px; }
    @media (max-width: 768px) { .cg-grid { grid-template-columns: 1fr; } }

    .cg-card { background: #fff; border-radius: 16px; border: 1px solid #e5e7eb; padding: 26px; box-shadow: 0 1px 4px rgba(0,0,0,.05); }
    .cg-card h2 { font-size: 17px; font-weight: 700; color: #111827; margin-bottom: 22px; }

    .cg-form-group { margin-bottom: 18px; }
    .cg-label { display: block; font-size: 13px; font-weight: 600; color: #374151; margin-bottom: 8px; }
    .cg-label small { font-size: 11px; color: #9ca3af; font-weight: 400; margin-left: 4px; }
    .cg-input, .cg-select, .cg-textarea { width: 100%; padding: 11px 15px; border: 1.5px solid #d1d5db; border-radius: 12px; font-size: 14px; font-family: inherit; color: #111827; background: #fff; outline: none; transition: border-color .15s, box-shadow .15s; }
    .cg-input:focus, .cg-select:focus, .cg-textarea:focus { border-color: #a855f7; box-shadow: 0 0 0 3px rgba(168,85,247,.1); }
    .cg-textarea { min-height: 100px; resize: vertical; }

    .cg-btn { width: 100%; background: linear-gradient(135deg, #9333ea, #7e22ce); color: #fff; padding: 13px 22px; border-radius: 12px; font-size: 14px; font-weight: 600; border: none; cursor: pointer; transition: background .15s; display: flex; align-items: center; justify-content: center; gap: 8px; }
    .cg-btn:hover { background: linear-gradient(135deg, #7e22ce, #6b21a8); }
    .cg-btn:disabled { opacity: .6; cursor: not-allowed; }

    .cg-output { min-height: 380px; display: flex; flex-direction: column; }
    .cg-output-header { display: flex; align-items: center; justify-content: space-between; margin-bottom: 22px; }
    .cg-copy-btn { display: none; font-size: 11px; color: #7e22ce; border: 1px solid #e9d5ff; background: #faf5ff; padding: 6px 12px; border-radius: 8px; font-weight: 600; cursor: pointer; transition: all .15s; }
    .cg-copy-btn:hover { background: #f3e8ff; border-color: #d8b4fe; }

    .cg-empty { flex: 1; display: flex; flex-direction: column; align-items: center; justify-content: center; min-height: 240px; text-align: center; }
    .cg-empty-icon { font-size: 48px; margin-bottom: 14px; }
    .cg-empty-text { font-size: 13px; color: #9ca3af; }

    .cg-loading { flex: 1; display: flex; flex-direction: column; align-items: center; justify-content: center; min-height: 240px; text-align: center; }
    .cg-loading-icon { font-size: 48px; margin-bottom: 14px; animation: cgBounce 1s infinite; }
    @keyframes cgBounce { 0%,100% { transform: translateY(0); } 50% { transform: translateY(-10px); } }
    .cg-loading-text { font-size: 13px; color: #6b7280; }
    .cg-loading-dots { display: flex; gap: 6px; margin-top: 12px; }
    .cg-dot { width: 8px; height: 8px; background: #a855f7; border-radius: 50%; animation: cgPulse 1.2s infinite; }
    .cg-dot:nth-child(2) { animation-delay: .2s; }
    .cg-dot:nth-child(3) { animation-delay: .4s; }
    @keyframes cgPulse { 0%,100% { opacity: .3; transform: scale(.8); } 50% { opacity: 1; transform: scale(1.2); } }

    .cg-error { background: #fef2f2; border: 1px solid #fecaca; color: #b91c1c; padding: 12px 16px; border-radius: 12px; font-size: 13px; }

    .cg-result-label { display: block; font-size: 11px; font-weight: 600; color: #6b7280; margin-bottom: 6px; text-transform: uppercase; letter-spacing: .5px; }
    .cg-result-input { width: 100%; padding: 10px 13px; border: 1px solid #e5e7eb; border-radius: 10px; font-size: 13px; font-family: inherit; color: #111827; background: #fff; outline: none; transition: border-color .15s; }
    .cg-result-input:focus { border-color: #a855f7; box-shadow: 0 0 0 3px rgba(168,85,247,.1); }
    .cg-result-textarea { min-height: 80px; resize: vertical; }
    .cg-result-textarea-lg { min-height: 180px; }
    .cg-result-field { margin-bottom: 16px; }
    .cg-result-field:last-child { margin-bottom: 0; }
    .cg-char-count { font-size: 11px; color: #9ca3af; margin-top: 4px; }

    .cg-keywords { display: flex; flex-wrap: wrap; gap: 7px; margin-top: 8px; }
    .cg-keyword-tag { background: #faf5ff; color: #7e22ce; border: 1px solid #e9d5ff; padding: 5px 13px; border-radius: 20px; font-size: 12px; font-weight: 500; }
    .cg-keyword-tag.blue { background: #eff6ff; color: #1d4ed8; border-color: #bfdbfe; }

    .cg-notification { position: fixed; top: 16px; right: 16px; padding: 12px 18px; border-radius: 10px; color: #fff; font-size: 13px; font-weight: 500; box-shadow: 0 4px 12px rgba(0,0,0,.15); z-index: 100; }
    .cg-notification.error { background: #dc2626; }
    .cg-notification.success { background: #059669; }
    .cg-notification.info { background: #2563eb; }
</style>

<div class="cg-page">

    {{-- Header --}}
    <div class="cg-header">
        <a href="{{ route('ai.index') }}" class="cg-back">← AI Asistan</a>
        <h1>✍️ AI İçerik Üretici</h1>
        <p>Blog yazıları ve SEO içeriği için AI destekli içerik oluşturun</p>
    </div>

    <div class="cg-grid">

        {{-- Input Form --}}
        <div class="cg-card">
            <h2>İçerik Ayarları</h2>
            <form id="contentForm" onsubmit="generateContent(event)">
                @csrf

                <div class="cg-form-group">
                    <label class="cg-label">İçerik Türü</label>
                    <select id="contentType" name="type" class="cg-select">
                        <option value="blog">📝 Blog Yazısı</option>
                        <option value="seo">📊 SEO Analizi</option>
                        <option value="keywords">🏷️ Anahtar Kelimeler</option>
                    </select>
                </div>

                <div class="cg-form-group">
                    <label class="cg-label">Konu / Başlık <span style="color:#ef4444">*</span></label>
                    <input type="text" id="topic" name="topic" placeholder="Örn: Subay nasıl olunur?" required class="cg-input">
                </div>

                <div class="cg-form-group">
                    <label class="cg-label">Kategori <small>(Opsiyonel)</small></label>
                    <input type="text" id="category" name="category" placeholder="Örn: Kariyer, Sınavlar" class="cg-input">
                </div>

                <button type="submit" id="generateBtn" class="cg-btn">
                    <span>🤖</span>
                    <span id="generateBtnText">İçerik Oluştur</span>
                </button>
            </form>
        </div>

        {{-- Output --}}
        <div class="cg-card cg-output">
            <div class="cg-output-header">
                <h2>Oluşturulan İçerik</h2>
                <button id="copyBtn" onclick="copyOutput()" class="cg-copy-btn">📋 Kopyala</button>
            </div>

            <div id="outputArea">
                {{-- Empty State --}}
                <div class="cg-empty">
                    <div class="cg-empty-icon">📝</div>
                    <p class="cg-empty-text">İçerik oluşturmak için formu doldurun ve "İçerik Oluştur" butonuna tıklayın</p>
                </div>
            </div>
        </div>

    </div>
</div>
@endsection

@section('scripts')
<script>
async function generateContent(e) {
    e.preventDefault();

    const topic = document.getElementById('topic').value.trim();
    const category = document.getElementById('category').value.trim();
    const type = document.getElementById('contentType').value;

    if (!topic) {
        showNotification('Lütfen bir konu girin.', 'error');
        return;
    }

    const btn = document.getElementById('generateBtn');
    const btnText = document.getElementById('generateBtnText');
    const output = document.getElementById('outputArea');
    const copyBtn = document.getElementById('copyBtn');

    btn.disabled = true;
    btnText.textContent = 'Oluşturuluyor...';
    copyBtn.style.display = 'none';

    output.innerHTML = `
        <div class="cg-loading">
            <div class="cg-loading-icon">🤖</div>
            <p class="cg-loading-text">AI içerik oluşturuyor...</p>
            <div class="cg-loading-dots">
                <span class="cg-dot"></span>
                <span class="cg-dot"></span>
                <span class="cg-dot"></span>
            </div>
        </div>
    `;

    try {
        const response = await fetch('{{ route("ai.generate_content") }}', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
                'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').content
            },
            body: JSON.stringify({ topic, category, type })
        });

        const data = await response.json();

        if (data.success) {
            displayResult(data.result, type);
            copyBtn.style.display = 'inline-block';
        } else {
            output.innerHTML = `<div class="cg-error">❌ ${data.error || 'Bir hata oluştu.'}</div>`;
        }
    } catch (error) {
        console.error('Error:', error);
        output.innerHTML = `<div class="cg-error">❌ Bağlantı hatası. Lütfen tekrar deneyin.</div>`;
    } finally {
        btn.disabled = false;
        btnText.textContent = 'İçerik Oluştur';
    }
}

function displayResult(result, type) {
    const output = document.getElementById('outputArea');
    let html = '';

    if (type === 'blog') {
        html = `
            <div class="cg-result-field">
                <label class="cg-result-label">Başlık</label>
                <input type="text" value="${escHtml(result.title || '')}" class="cg-result-input">
            </div>
            <div class="cg-result-field">
                <label class="cg-result-label">Özet</label>
                <textarea class="cg-result-input cg-result-textarea" rows="3">${escHtml(result.excerpt || '')}</textarea>
            </div>
            <div class="cg-result-field">
                <label class="cg-result-label">İçerik</label>
                <textarea class="cg-result-input cg-result-textarea-lg" rows="8">${escHtml(result.content || '')}</textarea>
            </div>
            <div>
                <label class="cg-result-label">Anahtar Kelimeler</label>
                <div class="cg-keywords">
                    ${(result.keywords || []).map(kw => `<span class="cg-keyword-tag">${escHtml(kw)}</span>`).join('')}
                </div>
            </div>
        `;
    } else if (type === 'seo') {
        html = `
            <div class="cg-result-field">
                <label class="cg-result-label">Meta Title</label>
                <input type="text" value="${escHtml(result.meta_title || '')}" class="cg-result-input">
                <p class="cg-char-count">${(result.meta_title || '').length} / 60 karakter</p>
            </div>
            <div class="cg-result-field">
                <label class="cg-result-label">Meta Description</label>
                <textarea class="cg-result-input cg-result-textarea" rows="3">${escHtml(result.meta_description || '')}</textarea>
                <p class="cg-char-count">${(result.meta_description || '').length} / 160 karakter</p>
            </div>
            <div>
                <label class="cg-result-label">Anahtar Kelimeler</label>
                <div class="cg-keywords">
                    ${(result.keywords || []).map(kw => `<span class="cg-keyword-tag blue">${escHtml(kw)}</span>`).join('')}
                </div>
            </div>
        `;
    } else {
        html = `
            <div>
                <label class="cg-result-label">Anahtar Kelimeler</label>
                <div class="cg-keywords">
                    ${(result.keywords || []).map(kw => `<span class="cg-keyword-tag">${escHtml(kw)}</span>`).join('')}
                </div>
            </div>
        `;
    }

    output.innerHTML = html;
}

function escHtml(text) {
    return String(text)
        .replace(/&/g, '&amp;')
        .replace(/</g, '&lt;')
        .replace(/>/g, '&gt;')
        .replace(/"/g, '&quot;');
}

function copyOutput() {
    const text = Array.from(document.querySelectorAll('#outputArea input, #outputArea textarea'))
        .map(el => el.value)
        .join('\n\n');

    if (!text.trim()) return;

    navigator.clipboard.writeText(text).then(() => {
        showNotification('İçerik panoya kopyalandı!', 'success');
    }).catch(() => {
        showNotification('Kopyalama başarısız.', 'error');
    });
}

function showNotification(message, type = 'info') {
    const notif = document.createElement('div');
    notif.className = `cg-notification ${type}`;
    notif.textContent = message;
    document.body.appendChild(notif);
    setTimeout(() => notif.remove(), 3000);
}
</script>
@endsection
