@extends('layout')

@section('content')
    @if (session('import_success') || session('test_success'))
        <div class="floating-alert success">
            {{ session('import_success') ?? session('test_success') }}
        </div>
    @endif

    <section class="premium-dashboard dashboard-red-theme">
        <aside class="premium-sidebar">
            <div class="dashboard-brand-card">
                <img src="{{ asset('images/neutro-pharma-logo.svg') }}" alt="Neutro Pharma logo">
                <div>
                    <strong>Neutro Pharma</strong>
                    <small>(Pvt) Ltd.</small>
                </div>
            </div>

            <div class="sidebar-top">
                <button id="openTestModal" class="create-icon-button" type="button" aria-label="Create test" title="Create test">
                    +
                </button>
                <div>
                    <p class="eyebrow">Test Studio</p>
                    <h2>Tests</h2>
                </div>
            </div>

            <div class="sidebar-list-heading">
                <span>All Tests</span>
                <span class="sidebar-menu-icon" aria-hidden="true">&#9776;</span>
            </div>

            <div class="test-list">
                @foreach ($quizzes as $managedQuiz)
                    <div class="test-item @if ($quiz->id === $managedQuiz->id) is-selected @endif">
                        <a class="test-link" href="{{ route('admin.quiz', ['quiz' => $managedQuiz->id]) }}">
                            <span class="test-type">{{ $managedQuiz->test_type }}</span>
                            <strong>{{ $managedQuiz->title }}</strong>
                            <small>{{ $managedQuiz->questions_count }} questions &middot; {{ $managedQuiz->participants_count }} players</small>
                        </a>
                        <form method="POST" action="{{ route('admin.tests.toggle', ['quiz' => $managedQuiz->id]) }}">
                            @csrf
                            <button class="toggle-button @if (! $managedQuiz->is_enabled) is-off @endif" type="submit">
                                <span class="status-dot"></span>{{ $managedQuiz->is_enabled ? 'Active' : 'Inactive' }}
                            </button>
                        </form>
                    </div>
                @endforeach
            </div>

            <nav class="sidebar-nav" aria-label="Admin navigation">
                <a class="sidebar-nav-link is-active" href="{{ route('admin.quiz', ['quiz' => $quiz->id]) }}">
                    <span class="nav-icon" aria-hidden="true">&#9638;</span>
                    <span>Dashboard</span>
                </a>
                <button id="openQuestionsNav" class="sidebar-nav-link" type="button">
                    <span class="nav-icon" aria-hidden="true">&#9633;</span>
                    <span>Questions</span>
                </button>
                <a class="sidebar-nav-link" href="#participantsPanel">
                    <span class="nav-icon" aria-hidden="true">&#9675;</span>
                    <span>Participants</span>
                </a>
                <a class="sidebar-nav-link" href="{{ route('admin.reports.show', ['quiz' => $quiz->id]) }}">
                    <span class="nav-icon" aria-hidden="true">&#9616;</span>
                    <span>Reports</span>
                </a>
                <button id="openSettingsNav" class="sidebar-nav-link" type="button">
                    <span class="nav-icon" aria-hidden="true">&#9881;</span>
                    <span>Settings</span>
                </button>
            </nav>

            <div class="sidebar-user-card">
                <span class="admin-avatar" aria-hidden="true">A</span>
                <div>
                    <strong>Admin User</strong>
                    <small>admin@teststudio.com</small>
                </div>
            </div>
        </aside>

        <section class="dashboard-main">
            <header class="dashboard-header premium-hero">
                <div>
                    <div class="hero-brand-strip">
                        <img src="{{ asset('images/neutro-pharma-logo.svg') }}" alt="Neutro Pharma logo">
                        <div>
                            <strong>Neutro Pharma (Pvt) Ltd.</strong>
                            <span>Learning and assessment dashboard</span>
                        </div>
                    </div>
                    <p class="eyebrow">{{ $quiz->test_type }} &middot; {{ $quiz->is_enabled ? 'Active' : 'Inactive' }}</p>
                    <h1>{{ $quiz->title }}</h1>
                    @if ($quiz->is_enabled)
                        <p class="muted">Participant link: <a href="{{ route('quiz.join', ['quizSlug' => $quiz->slug]) }}">{{ route('quiz.join', ['quizSlug' => $quiz->slug]) }}</a></p>
                    @else
                        <p class="muted">Enable this test before sharing the participant link.</p>
                    @endif
                </div>
                <div class="admin-actions action-grid">
                    <button id="openImportModal" class="secondary-button action-button" type="button">
                        <span class="button-icon" aria-hidden="true">&#8679;</span>
                        <span>Import Questions</span>
                    </button>
                    <a class="secondary-button action-link action-button" href="{{ route('admin.reports.show', ['quiz' => $quiz->id]) }}">
                        <span class="button-icon" aria-hidden="true">&#9616;</span>
                        <span>Result Report</span>
                    </a>
                    <button id="startBtn" class="primary-button action-button start-action" @disabled(! $quiz->is_enabled || $quiz->questions->isEmpty() || $shouldShowFinalResult)>
                        <span class="button-icon" aria-hidden="true">&#9655;</span>
                        <span>Start Quiz</span>
                    </button>
                    <button id="nextBtn" class="secondary-button action-button" @disabled(! $quiz->is_enabled || $quiz->questions->isEmpty() || $shouldShowFinalResult)>
                        <span class="button-icon" aria-hidden="true">&#8594;</span>
                        <span>Next Question</span>
                    </button>
                    <button id="resetBtn" class="danger-button action-button">
                        <span class="button-icon" aria-hidden="true">&#8635;</span>
                        <span>Reset</span>
                    </button>
                    <form method="POST" action="{{ route('admin.logout') }}" class="inline-form">
                        @csrf
                        <button class="secondary-button action-button" type="submit">
                            <span class="button-icon" aria-hidden="true">&#10162;</span>
                            <span>Logout</span>
                        </button>
                    </form>
                </div>
            </header>

            @if (! $quiz->is_enabled || $quiz->questions->isEmpty())
                <section class="admin-notice-card">
                    <span class="notice-icon" aria-hidden="true">!</span>
                    <div>
                        <strong>
                            @if (! $quiz->is_enabled)
                                This test is inactive.
                            @else
                                This test has no questions.
                            @endif
                        </strong>
                        <p>
                            @if (! $quiz->is_enabled)
                                The selected test cannot be started and participants cannot join it until it is enabled.
                            @else
                                Add a question or import from the Excel template before clicking Start Quiz.
                            @endif
                        </p>
                    </div>

                    <div class="admin-notice-actions">
                        @if (! $quiz->is_enabled)
                            <form method="POST" action="{{ route('admin.tests.toggle', ['quiz' => $quiz->id]) }}">
                                @csrf
                                <button class="primary-button" type="submit">Enable Test</button>
                            </form>
                        @endif
                        <button id="openImportModalNotice" class="secondary-button" type="button">Import Questions</button>
                    </div>
                </section>
            @endif

            <section class="card status-card">
                <div>
                    <span class="status-card-icon" aria-hidden="true">&#10003;</span>
                    <div>
                        <p class="label">Quiz Status</p>
                        <span id="statusPill" class="pill">{{ strtoupper($dashboardStatus) }}</span>
                    </div>
                </div>
                <div>
                    <span class="status-card-icon muted-icon" aria-hidden="true">&#9711;</span>
                    <div>
                        <p class="label">Test Mode</p>
                        <strong class="big-number compact-number">{{ $quiz->is_enabled ? 'ON' : 'OFF' }}</strong>
                    </div>
                </div>
                <div>
                    <span class="status-card-icon" aria-hidden="true">&#9633;</span>
                    <div>
                        <p class="label">Questions</p>
                        <strong class="big-number">{{ $quiz->questions->count() }}</strong>
                    </div>
                </div>
                <div>
                    <span class="status-card-icon" aria-hidden="true">&#9675;</span>
                    <div>
                        <p class="label">Participants</p>
                        <strong id="participantCount" class="big-number">{{ count($participants) }}</strong>
                    </div>
                </div>
                <div>
                    <span class="status-card-icon muted-icon" aria-hidden="true">&#9716;</span>
                    <div>
                        <p class="label">Timer</p>
                        <strong id="timer" class="big-number">--</strong>
                    </div>
                </div>
            </section>

            <section class="card question-card @if ($shouldShowFinalResult) is-finished @endif">
                <p class="label">Current Question</p>
                <h2 id="questionTitle">{{ $shouldShowFinalResult ? 'Quiz finished. Result saved until reset.' : 'Waiting to start...' }}</h2>
                <div id="questionOptions" class="option-list"></div>
            </section>

            <section class="card top-three-card">
                <div class="section-title-row">
                    <div>
                        <p id="topThreeLabel" class="label">{{ $shouldShowFinalResult ? 'Final Result' : 'Fastest Correct Answers' }}</p>
                        <h2 id="topThreeTitle">{{ $shouldShowFinalResult ? 'Final Top 3' : 'Live Top 3' }}</h2>
                    </div>
                </div>
                <div id="topThree" class="podium">
                    <div class="podium-box second"><span>2nd</span><strong>Waiting</strong></div>
                    <div class="podium-box first"><span>1st</span><strong>Waiting</strong></div>
                    <div class="podium-box third"><span>3rd</span><strong>Waiting</strong></div>
                </div>
            </section>

            <section id="participantsPanel" class="card participants-card">
                <div class="section-title-row">
                    <div>
                        <p class="label">Live Participants</p>
                        <h2>Active list</h2>
                    </div>
                </div>
                <ul id="participantList" class="participant-list"></ul>
            </section>

            <section class="card overall-card">
                <p class="label">Cumulative Score</p>
                <h2>Overall Leaderboard</h2>
                <ol id="overallList" class="overall-list"></ol>
            </section>
        </section>
    </section>

    <div id="testModal" class="modal-backdrop @if ($errors->has('title') || $errors->has('test_type')) is-open @endif" aria-hidden="{{ ($errors->has('title') || $errors->has('test_type')) ? 'false' : 'true' }}">
        <section class="modal-panel builder-modal-panel" role="dialog" aria-modal="true" aria-labelledby="testModalTitle">
            <div class="section-title-row">
                <div>
                    <p class="label">New Quiz</p>
                    <h2 id="testModalTitle">Create Test</h2>
                </div>
                <button id="closeTestModal" class="icon-button" type="button" aria-label="Close test form">x</button>
            </div>

            @if ($errors->has('title') || $errors->has('test_type'))
                <div class="alert error">
                    {{ $errors->first() }}
                </div>
            @endif

            <form method="POST" action="{{ route('admin.tests.store') }}" class="new-quiz-card modal-new-quiz-form">
                @csrf
                <input type="hidden" name="test_type" value="General">
                <input type="hidden" name="is_enabled" value="1">
                <input id="test_title" name="title" value="{{ old('title') }}" required maxlength="160" placeholder="Quiz title">
                <textarea name="description" rows="3" maxlength="1000" placeholder="Description">{{ old('description') }}</textarea>
                <button class="builder-primary-button" type="submit"><span>+</span>Create</button>
            </form>
        </section>
    </div>

    <div id="importModal" class="modal-backdrop import-builder-backdrop @if ($errors->has('questions_import') || $errors->has('questions_file') || $errors->has('question_text')) is-open @endif" aria-hidden="{{ ($errors->has('questions_import') || $errors->has('questions_file') || $errors->has('question_text')) ? 'false' : 'true' }}">
        <section class="modal-panel import-builder-panel" role="dialog" aria-modal="true" aria-labelledby="importModalTitle">
            <div class="import-builder-header">
                <div>
                    <p class="label">Questions & Answers</p>
                    <h2 id="importModalTitle">Import Questions</h2>
                </div>
                <button id="closeImportModal" class="icon-button" type="button" aria-label="Close import form">x</button>
            </div>

            <section class="import-builder-shell">
                <aside class="quiz-builder-sidebar">
                    <form method="POST" action="{{ route('admin.tests.store') }}" class="builder-card new-quiz-card">
                        @csrf
                        <input type="hidden" name="test_type" value="General">
                        <input type="hidden" name="is_enabled" value="1">
                        <h2>New Quiz</h2>
                        <input name="title" value="{{ old('title') }}" required maxlength="160" placeholder="Quiz title">
                        <textarea name="description" rows="3" maxlength="1000" placeholder="Description">{{ old('description') }}</textarea>
                        <button class="builder-primary-button" type="submit"><span>+</span>Create</button>
                    </form>

                    <div class="builder-quiz-list">
                        @foreach ($quizzes as $managedQuiz)
                            <article class="builder-quiz-item @if ($quiz->id === $managedQuiz->id) is-selected @endif">
                                <a href="{{ route('admin.quiz', ['quiz' => $managedQuiz->id]) }}">
                                    <strong>{{ $managedQuiz->title }}</strong>
                                    <span>{{ $managedQuiz->is_enabled ? 'Active' : 'Inactive' }}</span>
                                </a>

                                <div class="builder-quiz-actions">
                                    <form method="POST" action="{{ route('admin.tests.toggle', ['quiz' => $managedQuiz->id]) }}">
                                        @csrf
                                        <button class="mini-action-button" type="submit">{{ $managedQuiz->is_enabled ? 'Disable' : 'Enable' }}</button>
                                    </form>
                                    <form method="POST" action="{{ route('admin.tests.destroy', ['quiz' => $managedQuiz->id]) }}" onsubmit="return confirm('Delete this quiz and all of its questions?')">
                                        @csrf
                                        @method('DELETE')
                                        <button class="delete-icon-button" type="submit" aria-label="Delete {{ $managedQuiz->title }}">x</button>
                                    </form>
                                </div>
                            </article>
                        @endforeach
                    </div>
                </aside>

                <main class="quiz-builder-main">
                    <section class="builder-card add-question-card">
                        <div class="builder-section-title">
                            <div>
                                <h1>Add Question</h1>
                                <p>{{ $quiz->title }} &middot; {{ $quiz->questions->count() }} questions</p>
                            </div>
                            <a class="builder-link-pill" href="{{ route('quiz.join', ['quizSlug' => $quiz->slug]) }}">Join Link</a>
                        </div>

                        @if ($errors->has('question_text') || $errors->has('option_a') || $errors->has('correct_option'))
                            <div class="alert error">
                                {{ $errors->first() }}
                            </div>
                        @endif

                        <form method="POST" action="{{ route('admin.questions.store') }}" class="question-builder-form">
                            @csrf
                            <input type="hidden" name="quiz_id" value="{{ $quiz->id }}">
                            <textarea id="import_question_text" name="question_text" rows="3" required placeholder="Question text">{{ old('question_text') }}</textarea>

                            <div class="answer-option-grid">
                                @foreach (['A', 'B', 'C', 'D'] as $letter)
                                    @php $field = 'option_'.strtolower($letter); @endphp
                                    <label class="answer-option-row">
                                        <input type="radio" name="correct_option" value="{{ $letter }}" @checked(old('correct_option', 'A') === $letter)>
                                        <span>{{ $letter }}</span>
                                        <input name="{{ $field }}" value="{{ old($field) }}" required maxlength="255" placeholder="Option {{ $loop->iteration }}">
                                    </label>
                                @endforeach
                            </div>

                            <div class="question-form-footer">
                                <div>
                                    <label for="duration_seconds">Time limit (seconds)</label>
                                    <input id="duration_seconds" name="duration_seconds" type="number" value="{{ old('duration_seconds', 15) }}" min="5" max="300" required>
                                </div>
                                <p>Correct: <strong id="correctChoiceLabel">{{ old('correct_option', 'A') }}</strong></p>
                            </div>

                            <button class="builder-primary-button add-question-button" type="submit"><span>+</span>Add Question</button>
                        </form>
                    </section>

                    <section class="bulk-import-panel">
                        <div class="bulk-import-icon">#</div>
                        <div>
                            <h2>Bulk Import from Excel</h2>
                            <p>Download the template, review the rows, then import only if the file is clean.</p>
                        </div>

                        @if ($errors->has('questions_import') || $errors->has('questions_file'))
                            <div class="alert error bulk-alert">
                                {{ $errors->first() }}
                            </div>
                        @endif

                        <form method="POST" action="{{ route('admin.quiz.import', ['quiz' => $quiz->id]) }}" enctype="multipart/form-data" class="bulk-import-actions">
                            @csrf
                            <input type="hidden" name="quiz_id" value="{{ $quiz->id }}">
                            <input type="hidden" name="replace_existing" value="1">
                            <a class="template-download-button" href="{{ route('admin.templates.questions') }}" download>Download Template</a>
                            <label class="builder-primary-button upload-button">
                                Upload CSV
                                <input name="questions_file" type="file" accept=".csv,.txt,text/csv,text/plain" onchange="this.form.submit()">
                            </label>
                        </form>

                        <p class="bulk-columns">Columns: <code>question_text</code>, <code>option_a</code>, <code>option_b</code>, <code>option_c</code>, <code>option_d</code>, <code>correct_option</code> (A/B/C/D), <code>time_limit</code></p>
                    </section>

                    <section class="questions-table-section">
                        <h2>Questions ({{ count($questionList) }})</h2>
                        <div class="questions-table">
                            @forelse ($questionList as $item)
                                <article class="question-row-card">
                                    <span>{{ $item['sort_order'] }}</span>
                                    <div>
                                        <strong>{{ $item['text'] }}</strong>
                                        <small>Correct: {{ ['', 'A', 'B', 'C', 'D'][$item['correct_option'] ?? 0] ?? '-' }} &middot; {{ $item['duration_seconds'] }}s</small>
                                    </div>
                                </article>
                            @empty
                                <p class="empty-state">No questions yet. Add one manually or import a template.</p>
                            @endforelse
                        </div>
                    </section>
                </main>
            </section>
        </section>
    </div>

    <script>
        window.quizApp = {!! \Illuminate\Support\Js::from([
            'quizUuid' => $quiz->uuid,
            'csrf' => csrf_token(),
            'csrfUrl' => route('csrf.token'),
            'routes' => [
                'start' => route('admin.quiz.start', ['quiz' => $quiz->id]),
                'next' => route('admin.quiz.next', ['quiz' => $quiz->id]),
                'reset' => route('admin.quiz.reset', ['quiz' => $quiz->id]),
            ],
            'canControl' => $quiz->is_enabled && $quiz->questions->isNotEmpty() && ! $shouldShowFinalResult,
            'shouldShowFinalResult' => $shouldShowFinalResult,
            'participants' => $participants,
            'state' => $state,
            'topThree' => $topThree,
            'overall' => $overall,
        ]) !!};
    </script>
@endsection

@push('vite')
    @vite(['resources/css/app.css', 'resources/js/admin.js'])
@endpush
