{{-- Shared Self Exam / Self Homework create: subject → chapter → topic → marks --}}
@php
    $formAction = $formAction ?? '#';
    $countsUrl = $countsUrl ?? '#';
    $cancelUrl = $cancelUrl ?? url('/student');
    $generateLabel = $generateLabel ?? 'Generate';
    $markOptions = $markOptions ?? [20, 30, 50, 70, 100];
@endphp

<div class="admin-page max-w-3xl"
     x-data="selfPaperBuilder({
        subjects: @js($subjects->map(fn ($s) => [
            'id' => $s->id,
            'name' => $s->name,
            'chapters' => $s->chapters->map(fn ($c) => [
                'id' => $c->id,
                'name' => $c->name,
                'topics' => $c->topics->map(fn ($t) => ['id' => $t->id, 'name' => $t->name])->values(),
            ])->values(),
        ])->values()),
        markOptions: @js($markOptions),
        countsUrl: @js($countsUrl),
        oldSubject: @js(old('subject_id')),
        oldChapter: @js(old('chapter_id')),
        oldTopic: @js(old('topic_id', '')),
        oldMarks: @js((int) old('target_marks', 20)),
     })">
    @if ($errors->any())
        <div class="mb-4 rounded-xl border border-rose-200 bg-rose-50 px-4 py-3 text-sm text-rose-800">
            <ul class="list-disc pl-4 space-y-1">
                @foreach ($errors->all() as $error)
                    <li>{{ $error }}</li>
                @endforeach
            </ul>
        </div>
    @endif
    @if (session('error'))
        <div class="mb-4 rounded-xl border border-rose-200 bg-rose-50 px-4 py-3 text-sm text-rose-800">{{ session('error') }}</div>
    @endif

    @if (! $standard || $subjects->isEmpty())
        <div class="admin-card p-8 text-center text-slate-600">
            No subjects found for {{ $standardName }}. Ask admin to assign subjects first.
        </div>
    @else
        <form method="POST" action="{{ $formAction }}" class="space-y-6"
              @submit="if (!canGenerate) { $event.preventDefault(); alert(planError || 'Please complete chapter, topic and marks.'); }">
            @csrf

            <div class="admin-card p-6 space-y-5">
                <div>
                    <label class="block text-sm font-medium text-slate-700 mb-1">Subject *</label>
                    <select name="subject_id" x-model="subjectId" @change="onSubjectChange()" required class="w-full rounded-xl border-slate-200 h-11">
                        <option value="">Select subject</option>
                        @foreach ($subjects as $subject)
                            <option value="{{ $subject->id }}" @selected((string) old('subject_id') === (string) $subject->id)>{{ $subject->name }}</option>
                        @endforeach
                    </select>
                </div>

                <div>
                    <label class="block text-sm font-medium text-slate-700 mb-1">Chapter *</label>
                    <select name="chapter_id" x-model="chapterId" @change="onChapterChange()" required class="w-full rounded-xl border-slate-200 h-11" :disabled="!chapters.length">
                        <option value="">Select chapter</option>
                        <template x-for="ch in chapters" :key="ch.id">
                            <option :value="ch.id" x-text="ch.name"></option>
                        </template>
                    </select>
                </div>

                <div>
                    <label class="block text-sm font-medium text-slate-700 mb-1">Topic *</label>
                    <select name="topic_id" x-model="topicId" @change="refreshCounts()" class="w-full rounded-xl border-slate-200 h-11" :disabled="!chapterId">
                        <option value="">All topics in chapter</option>
                        <template x-for="tp in topics" :key="tp.id">
                            <option :value="tp.id" x-text="tp.name"></option>
                        </template>
                    </select>
                    <p class="text-xs text-slate-500 mt-1">Choose one topic, or keep “All topics in chapter”.</p>
                </div>

                <div>
                    <p class="block text-sm font-medium text-slate-700 mb-2">Total marks *</p>
                    <div class="flex flex-wrap gap-2">
                        <template x-for="marks in markOptions" :key="marks">
                            <label class="cursor-pointer">
                                <input type="radio" name="target_marks" :value="marks" x-model.number="targetMarks" @change="refreshCounts()" class="peer sr-only">
                                <span class="inline-flex h-10 min-w-[3.25rem] items-center justify-center rounded-lg border px-3 text-sm font-semibold leading-none border-slate-200 bg-white text-slate-700 peer-checked:border-brand-green peer-checked:bg-emerald-50 peer-checked:text-brand-green peer-checked:ring-1 peer-checked:ring-brand-green"
                                      x-text="marks"></span>
                            </label>
                        </template>
                    </div>
                </div>
            </div>

            <div class="admin-card p-6 space-y-4">
                <div class="flex items-center justify-between gap-3">
                    <div>
                        <h3 class="font-bold text-slate-900">Questions available (by type)</h3>
                        <p class="text-xs text-slate-500">Chapter / topic bank. Paper auto-builds for selected marks.</p>
                    </div>
                    <button type="button" @click="refreshCounts()" class="text-xs font-semibold text-brand-green hover:underline" :disabled="loading">
                        <span x-show="!loading">Refresh</span>
                        <span x-show="loading">Loading…</span>
                    </button>
                </div>

                <div x-show="planError" class="rounded-xl border border-amber-200 bg-amber-50 px-3 py-2 text-xs text-amber-800" x-text="planError"></div>

                <div class="overflow-x-auto">
                    <table class="admin-table w-full text-sm">
                        <thead>
                            <tr>
                                <th>Type</th>
                                <th>Available</th>
                                <th>In this paper</th>
                            </tr>
                        </thead>
                        <tbody>
                            <template x-for="row in typeRows" :key="row.type">
                                <tr>
                                    <td x-text="row.label"></td>
                                    <td x-text="row.available"></td>
                                    <td class="font-semibold">
                                        <input type="number"
                                               min="0"
                                               :max="row.available"
                                               x-model.number="row.planned"
                                               @input="onPlannedInput(row)"
                                               class="w-20 rounded-lg border-slate-200 text-sm">
                                        <input type="hidden" :name="`type_counts[${row.type}]`" :value="row.planned ?? 0">
                                    </td>
                                </tr>
                            </template>
                            <tr x-show="typeRows.length === 0">
                                <td colspan="3" class="text-center text-slate-500 py-6">Select chapter and marks to see availability.</td>
                            </tr>
                        </tbody>
                    </table>
                </div>

                <div class="rounded-xl bg-slate-50 border border-slate-100 px-4 py-3 text-sm text-slate-700" x-show="typeRows.length">
                    <span class="font-semibold">Paper plan:</span>
                    <span x-text="plannedQuestions"></span> questions ·
                    <span x-text="plannedMarks"></span> marks
                </div>
            </div>

            <div class="flex flex-wrap gap-3">
                <button type="submit"
                        class="inline-flex h-10 items-center justify-center rounded-lg bg-brand-green px-5 text-sm font-semibold leading-none text-white hover:bg-brand-green-dark transition disabled:opacity-50"
                        :disabled="!canGenerate || loading">
                    {{ $generateLabel }}
                </button>
                <a href="{{ $cancelUrl }}" class="inline-flex h-10 items-center justify-center rounded-lg border border-slate-200 px-5 text-sm font-semibold leading-none text-slate-600 hover:bg-slate-50 transition">Cancel</a>
            </div>
        </form>
    @endif
</div>

<script>
function selfPaperBuilder(cfg) {
    return {
        subjects: cfg.subjects || [],
        markOptions: cfg.markOptions || [20, 30, 50, 70, 100],
        countsUrl: cfg.countsUrl,
        subjectId: cfg.oldSubject ? String(cfg.oldSubject) : '',
        chapterId: cfg.oldChapter ? String(cfg.oldChapter) : '',
        topicId: cfg.oldTopic === null || cfg.oldTopic === undefined ? '' : String(cfg.oldTopic),
        targetMarks: cfg.oldMarks || 20,
        chapters: [],
        topics: [],
        typeRows: [],
        plan: null,
        planError: '',
        loading: false,

        get canGenerate() {
            return !!(this.subjectId && this.chapterId && this.targetMarks && this.plannedQuestions > 0 && !this.planError);
        },

        get plannedQuestions() {
            return this.typeRows.reduce((sum, row) => sum + Math.max(0, Number(row.planned || 0)), 0);
        },

        get plannedMarks() {
            return this.typeRows.reduce((sum, row) => (
                sum + (Math.max(0, Number(row.planned || 0)) * Math.max(1, Number(row.marks || 1)))
            ), 0);
        },

        init() {
            this.onSubjectChange(false);
            if (this.chapterId) this.onChapterChange(false);
            if (this.chapterId) this.refreshCounts();
        },

        onSubjectChange(reset = true) {
            const subject = this.subjects.find(s => String(s.id) === String(this.subjectId));
            this.chapters = subject ? subject.chapters : [];
            if (reset) {
                this.chapterId = '';
                this.topicId = '';
                this.topics = [];
                this.typeRows = [];
                this.plan = null;
                this.planError = '';
            } else if (this.chapterId) {
                const ch = this.chapters.find(c => String(c.id) === String(this.chapterId));
                this.topics = ch ? (ch.topics || []) : [];
            }
        },

        onChapterChange(resetTopic = true) {
            const ch = this.chapters.find(c => String(c.id) === String(this.chapterId));
            this.topics = ch ? (ch.topics || []) : [];
            if (resetTopic) this.topicId = '';
            this.refreshCounts();
        },

        onPlannedInput(row) {
            const available = Math.max(0, Number(row.available || 0));
            const value = Math.max(0, Number(row.planned || 0));
            row.planned = Math.min(value, available);
            this.planError = '';
        },

        async refreshCounts() {
            this.plan = null;
            this.planError = '';
            if (!this.subjectId || !this.chapterId || !this.targetMarks) {
                this.typeRows = [];
                return;
            }
            this.loading = true;
            try {
                const params = new URLSearchParams();
                params.set('subject_id', this.subjectId);
                params.set('chapter_id', this.chapterId);
                params.set('target_marks', this.targetMarks);
                if (this.topicId) params.set('topic_id', this.topicId);

                const res = await fetch(this.countsUrl + '?' + params.toString(), {
                    headers: { 'Accept': 'application/json', 'X-Requested-With': 'XMLHttpRequest' }
                });
                const data = await res.json();
                const planned = data.plan?.type_counts || {};
                this.typeRows = (data.types || []).map(t => ({
                    ...t,
                    planned: planned[t.type] ?? 0,
                }));
                this.plan = data.plan || null;
                this.planError = data.error || '';
                if (!this.plan && !this.planError && (data.total === 0)) {
                    this.planError = 'No questions available for this chapter/topic.';
                }
                if (!this.planError && this.plannedQuestions === 0 && data.total > 0) {
                    this.planError = 'Set at least one question in "In this paper".';
                }
            } catch (e) {
                this.planError = 'Could not load question counts.';
            } finally {
                this.loading = false;
            }
        },
    }
}
</script>
