@extends('layouts.public')

@section('title', $scenarioName)

@section('content')
<style>
    .sc-page { max-width: 800px; margin: 0 auto; padding: 32px 20px; display: flex; flex-direction: column; min-height: 100vh; }

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

    .sc-progress { margin-bottom: 24px; }
    .sc-progress-bar { display: flex; align-items: center; justify-content: space-between; margin-bottom: 8px; }
    .sc-progress-text { font-size: 11px; font-weight: 600; color: #6b7280; }
    .sc-time { font-size: 11px; font-weight: 600; color: #6b7280; display: flex; align-items: center; gap: 4px; }
    .sc-time svg { width: 14px; height: 14px; }
    .sc-progress-track { width: 100%; height: 4px; background: #e5e7eb; border-radius: 2px; overflow: hidden; }
    .sc-progress-fill { height: 100%; background: linear-gradient(90deg, #a855f7, #9333ea); transition: width .3s; }

    .sc-card { flex: 1; background: #fff; border-radius: 16px; border: 1px solid #e5e7eb; padding: 32px; margin-bottom: 24px; box-shadow: 0 1px 4px rgba(0,0,0,.05); }

    .sc-question h2 { font-size: 20px; font-weight: 700; color: #111827; margin-bottom: 20px; }
    .sc-textarea { width: 100%; padding: 12px 16px; 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; min-height: 160px; resize: none; }
    .sc-textarea:focus { border-color: #a855f7; box-shadow: 0 0 0 3px rgba(168,85,247,.1); }
    .sc-hint { font-size: 11px; color: #9ca3af; margin-top: 6px; }

    .sc-nav { display: flex; gap: 12px; justify-content: space-between; }
    .sc-btn { padding: 12px 22px; border-radius: 10px; font-size: 14px; font-weight: 600; border: none; cursor: pointer; transition: all .15s; font-family: inherit; }
    .sc-btn-prev { background: #f3f4f6; color: #374151; }
    .sc-btn-prev:hover { background: #e5e7eb; }
    .sc-btn-next { background: linear-gradient(135deg, #9333ea, #7e22ce); color: #fff; }
    .sc-btn-next:hover { background: linear-gradient(135deg, #7e22ce, #6b21a8); }
    .sc-btn-submit { background: linear-gradient(135deg, #059669, #047857); color: #fff; }
    .sc-btn-submit:hover { background: linear-gradient(135deg, #047857, #065f46); }
    .sc-spacer { flex: 1; }

    .sc-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; animation: scSlideIn .3s; }
    @keyframes scSlideIn { from { transform: translateX(100%); opacity: 0; } to { transform: translateX(0); opacity: 1; } }
    .sc-notification.error { background: #dc2626; }
    .sc-notification.success { background: #059669; }
    .sc-notification.info { background: #2563eb; }

    .sc-spinner { display: inline-block; width: 16px; height: 16px; border: 2px solid #fff; border-top-color: transparent; border-radius: 50%; animation: scSpin 1s linear infinite; margin-right: 8px; vertical-align: middle; }
    @keyframes scSpin { to { transform: rotate(360deg); } }

    @media (max-width: 640px) {
        .sc-page { padding: 20px 16px; }
        .sc-header h1 { font-size: 20px; }
        .sc-card { padding: 20px; }
        .sc-question h2 { font-size: 17px; }
        .sc-textarea { min-height: 140px; }
        .sc-nav { flex-wrap: wrap; }
        .sc-btn { flex: 1; min-width: 120px; }
        .sc-spacer { display: none; }
    }
</style>

<div class="sc-page">

    {{-- Header --}}
    <div class="sc-header">
        <a href="{{ route('ai.simulation') }}" class="sc-back">← Simülasyonlara Dön</a>
        <h1>{{ $scenarioName }}</h1>
    </div>

    {{-- Progress --}}
    <div class="sc-progress">
        <div class="sc-progress-bar">
            <span id="progress-text" class="sc-progress-text">Soru 1 / {{ count($questions) }}</span>
            <span id="time-text" class="sc-time">
                <svg fill="currentColor" viewBox="0 0 20 20"><path fill-rule="evenodd" d="M10 18a8 8 0 100-16 8 8 0 000 16zm1-12a1 1 0 10-2 0v4a1 1 0 00-.447.894l1.341 1.341a1 1 0 001.414-1.414L10 9.586V6z" clip-rule="evenodd"/></svg>
                <span>0:00</span>
            </span>
        </div>
        <div class="sc-progress-track">
            <div id="progress-fill" class="sc-progress-fill" style="width: 0%;"></div>
        </div>
    </div>

    {{-- Question Card --}}
    <div class="sc-card">
        <div id="question-container"></div>
    </div>

    {{-- Navigation --}}
    <div class="sc-nav">
        <button id="prev-btn" onclick="previousQuestion()" class="sc-btn sc-btn-prev" style="display:none;">← Önceki</button>
        <div class="sc-spacer"></div>
        <button id="next-btn" onclick="nextQuestion()" class="sc-btn sc-btn-next">Sonraki →</button>
        <button id="submit-btn" onclick="submitSimulation()" class="sc-btn sc-btn-submit" style="display:none;">✓ Gönder</button>
    </div>

</div>
@endsection

@section('scripts')
<script>
const questions = @json($questions);
const scenario = @json($scenario);
let currentQuestion = 0;
let responses = {};
let startTime = Date.now();

function initSimulation() {
    displayQuestion();
    updateProgress();
    startTimer();
}

function displayQuestion() {
    const question = questions[currentQuestion];
    const html = `
        <div class="sc-question">
            <h2>${question.question}</h2>
            <textarea id="answer-${currentQuestion}" class="sc-textarea" placeholder="Cevabınızı buraya yazın... (En az 50 karakter gereklidir)">${responses[question.id] || ''}</textarea>
            <p class="sc-hint">Minimum 50 karakter gereklidir. Anahtar kelimeleri kullanarak detaylı cevap verin.</p>
        </div>
    `;
    document.getElementById('question-container').innerHTML = html;
    document.getElementById(`answer-${currentQuestion}`).addEventListener('input', (e) => { responses[question.id] = e.target.value; });
    setTimeout(() => { document.getElementById(`answer-${currentQuestion}`).focus(); }, 100);
}

function updateProgress() {
    const progress = ((currentQuestion + 1) / questions.length) * 100;
    document.getElementById('progress-fill').style.width = progress + '%';
    document.getElementById('progress-text').textContent = `Soru ${currentQuestion + 1} / ${questions.length}`;
    document.getElementById('prev-btn').style.display = currentQuestion === 0 ? 'none' : 'inline-block';
    document.getElementById('next-btn').style.display = currentQuestion === questions.length - 1 ? 'none' : 'inline-block';
    document.getElementById('submit-btn').style.display = currentQuestion === questions.length - 1 ? 'inline-block' : 'none';
}

function nextQuestion() {
    const question = questions[currentQuestion];
    const answer = document.getElementById(`answer-${currentQuestion}`).value.trim();
    if (answer.length < 50) { showNotification('Lütfen en az 50 karakter yazın.', 'error'); return; }
    responses[question.id] = answer;
    if (currentQuestion < questions.length - 1) {
        currentQuestion++;
        displayQuestion();
        updateProgress();
        window.scrollTo({ top: 0, behavior: 'smooth' });
    }
}

function previousQuestion() {
    if (currentQuestion > 0) {
        const question = questions[currentQuestion];
        responses[question.id] = document.getElementById(`answer-${currentQuestion}`).value;
        currentQuestion--;
        displayQuestion();
        updateProgress();
        window.scrollTo({ top: 0, behavior: 'smooth' });
    }
}

function startTimer() {
    setInterval(() => {
        const elapsed = Math.floor((Date.now() - startTime) / 1000);
        const minutes = Math.floor(elapsed / 60);
        const seconds = elapsed % 60;
        document.getElementById('time-text').innerHTML = 
            `<svg fill="currentColor" viewBox="0 0 20 20" style="width:14px;height:14px"><path fill-rule="evenodd" d="M10 18a8 8 0 100-16 8 8 0 000 16zm1-12a1 1 0 10-2 0v4a1 1 0 00-.447.894l1.341 1.341a1 1 0 001.414-1.414L10 9.586V6z" clip-rule="evenodd"/></svg>
            <span>${minutes}:${seconds.toString().padStart(2,'0')}</span>`;
    }, 1000);
}

async function submitSimulation() {
    const question = questions[currentQuestion];
    const lastAnswer = document.getElementById(`answer-${currentQuestion}`).value.trim();
    if (lastAnswer.length < 50) { showNotification('Lütfen en az 50 karakter yazın.', 'error'); return; }
    responses[question.id] = lastAnswer;
    
    // Build responses array with question_id and answer
    const responsesArray = questions.map(q => ({
        question_id: q.id,
        answer: responses[q.id] || ''
    }));
    
    if (responsesArray.some(r => r.answer.length < 50)) { 
        showNotification('Lütfen tüm soruları en az 50 karakterle cevaplandırın.', 'error'); 
        return; 
    }

    const submitBtn = document.getElementById('submit-btn');
    submitBtn.disabled = true;
    submitBtn.innerHTML = '<span class="sc-spinner"></span>Gönderiliyor...';

    try {
        const response = await fetch('{{ route("ai.submit_simulation") }}', {
            method: 'POST',
            headers: { 'Content-Type': 'application/json', 'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').content },
            body: JSON.stringify({ scenario: scenario, responses: responsesArray })
        });
        const data = await response.json();
        if (data.success) { window.location.href = `/ai/simulasyon-sonuc/${data.simulation_id}`; }
        else { showNotification(data.error || 'Bir hata oluştu.', 'error'); submitBtn.disabled = false; submitBtn.textContent = '✓ Gönder'; }
    } catch (error) {
        console.error('Error:', error);
        showNotification('Bağlantı hatası.', 'error');
        submitBtn.disabled = false;
        submitBtn.textContent = '✓ Gönder';
    }
}

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

window.addEventListener('load', initSimulation);
</script>
@endsection
