@extends('layouts.self-paced-dashboard')

@section('title', 'Edit Sub-Topic — ' . $subtopic->title)
@section('page-title', 'Edit Sub-Topic')
@section('page-subtitle', $course->title . ' › ' . $topic->title)

@section('hero-actions')
    <a href="{{ route('self-paced.dashboard.courses.topics.subtopics.show', [$course, $topic, $subtopic]) }}"
       class="inline-flex items-center gap-2 px-4 py-2 bg-white/10 hover:bg-white/20 text-white text-sm font-medium rounded-lg transition border border-white/30">
        <i class="fas fa-eye"></i> View
    </a>
    <a href="{{ route('self-paced.dashboard.courses.topics.show', [$course, $topic]) }}"
       class="inline-flex items-center gap-2 px-4 py-2 bg-white/10 hover:bg-white/20 text-white text-sm font-medium rounded-lg transition border border-white/30">
        <i class="fas fa-arrow-left"></i> Back
    </a>
@endsection

@push('styles')
<link href="https://cdn.jsdelivr.net/npm/quill@2.0.3/dist/quill.snow.css" rel="stylesheet">
<style>
    #quill-editor {
        min-height: 420px;
        font-size: 14px;
        font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif;
        border-bottom-left-radius: 0.5rem;
        border-bottom-right-radius: 0.5rem;
    }
    .ql-toolbar.ql-snow {
        border-top-left-radius: 0.5rem;
        border-top-right-radius: 0.5rem;
        background: #f9fafb;
        border-color: #e5e7eb;
    }
    .ql-container.ql-snow {
        border-color: #e5e7eb;
        border-bottom-left-radius: 0.5rem;
        border-bottom-right-radius: 0.5rem;
    }
    .ql-editor { min-height: 400px; line-height: 1.7; color: #374151; }
    .ql-editor img { max-width: 100%; border-radius: 8px; }
    .ql-editor iframe { max-width: 100%; border-radius: 8px; }
    .ql-editor blockquote {
        border-left: 4px solid #6366f1;
        background: #eef2ff;
        padding: 8px 16px;
        margin: 0;
        border-radius: 0 8px 8px 0;
    }
    .ql-editor pre.ql-syntax {
        background: #1f2937;
        color: #f9fafb;
        border-radius: 8px;
        padding: 16px;
    }
    #video-dialog-overlay {
        display: none;
        position: fixed; inset: 0; background: rgba(0,0,0,0.5);
        z-index: 9999; align-items: center; justify-content: center;
    }
    #video-dialog-overlay.active { display: flex; }
    #video-dialog {
        background: white; border-radius: 12px; padding: 24px;
        width: 100%; max-width: 480px; box-shadow: 0 20px 60px rgba(0,0,0,0.3);
    }
</style>
@endpush

@section('content')
<div class="max-w-4xl mx-auto">

    <nav class="flex items-center gap-2 text-xs text-gray-400 mb-4 flex-wrap">
        <a href="{{ route('self-paced.dashboard.index') }}" class="hover:text-indigo-600 transition">Dashboard</a>
        <i class="fas fa-chevron-right text-[10px]"></i>
        <a href="{{ route('self-paced.dashboard.courses.show', $course) }}" class="hover:text-indigo-600 transition">{{ Str::limit($course->title, 30) }}</a>
        <i class="fas fa-chevron-right text-[10px]"></i>
        <a href="{{ route('self-paced.dashboard.courses.topics.show', [$course, $topic]) }}" class="hover:text-indigo-600 transition">{{ Str::limit($topic->title, 30) }}</a>
        <i class="fas fa-chevron-right text-[10px]"></i>
        <a href="{{ route('self-paced.dashboard.courses.topics.subtopics.show', [$course, $topic, $subtopic]) }}" class="hover:text-indigo-600 transition">{{ Str::limit($subtopic->title, 25) }}</a>
        <i class="fas fa-chevron-right text-[10px]"></i>
        <span class="text-gray-600 font-medium">Edit</span>
    </nav>

    @if($errors->any())
    <div class="bg-red-50 border border-red-200 rounded-xl p-4 mb-5">
        <div class="flex items-start gap-3">
            <i class="fas fa-exclamation-circle text-red-500 mt-0.5"></i>
            <div>
                <p class="text-sm font-semibold text-red-700 mb-1">Please fix the following errors:</p>
                <ul class="text-sm text-red-600 space-y-0.5 list-disc list-inside">
                    @foreach($errors->all() as $error)<li>{{ $error }}</li>@endforeach
                </ul>
            </div>
        </div>
    </div>
    @endif

    <form action="{{ route('self-paced.dashboard.courses.topics.subtopics.update', [$course, $topic, $subtopic]) }}"
          method="POST" enctype="multipart/form-data" id="subtopic-form">
        @csrf
        @method('PUT')

        <div class="bg-white rounded-xl shadow-sm border border-gray-100 p-6">
            <h2 class="text-base font-semibold text-gray-800 mb-5 flex items-center gap-2">
                <i class="fas fa-layer-group text-blue-500"></i> Sub-Topic Details
            </h2>

            <div class="space-y-5">

                {{-- Title --}}
                <div>
                    <label class="block text-xs font-semibold text-gray-600 mb-1.5">
                        <i class="fas fa-heading text-gray-400 mr-1"></i> Sub-Topic Title <span class="text-red-500">*</span>
                    </label>
                    <input type="text" name="title" value="{{ old('title', $subtopic->title) }}"
                           class="w-full px-3 py-2 text-sm border @error('title') border-red-400 bg-red-50 @else border-gray-200 @enderror rounded-lg focus:outline-none focus:ring-2 focus:ring-indigo-300 focus:border-indigo-400 transition">
                    @error('title')<p class="text-red-500 text-xs mt-1">{{ $message }}</p>@enderror
                </div>

                {{-- Rich Content Editor --}}
                <div>
                    <label class="block text-xs font-semibold text-gray-600 mb-1.5">
                        <i class="fas fa-file-alt text-gray-400 mr-1"></i> Content
                        <span class="text-gray-400 font-normal">(rich text — paragraphs, headings, images, videos, tables, code, links)</span>
                    </label>

                    {{-- Hidden textarea — receives Quill HTML on submit --}}
                    <textarea name="content" id="content-input" class="hidden">{{ old('content', $subtopic->content) }}</textarea>

                    {{-- Quill editor container --}}
                    <div id="quill-editor"></div>

                    @error('content')<p class="text-red-500 text-xs mt-1">{{ $message }}</p>@enderror
                </div>

                <div class="grid grid-cols-1 md:grid-cols-2 gap-5">
                    <div>
                        <label class="block text-xs font-semibold text-gray-600 mb-1.5">
                            <i class="fas fa-sort-numeric-up text-gray-400 mr-1"></i> Sort Order
                        </label>
                        <input type="number" name="sort_order" value="{{ old('sort_order', $subtopic->sort_order) }}" min="0"
                               class="w-full px-3 py-2 text-sm border border-gray-200 rounded-lg focus:outline-none focus:ring-2 focus:ring-indigo-300 focus:border-indigo-400 transition">
                    </div>
                    <div class="flex items-center">
                        <label class="flex items-center gap-3 cursor-pointer">
                            <div class="relative">
                                <input type="hidden" name="is_published" value="0">
                                <input type="checkbox" name="is_published" value="1"
                                       {{ old('is_published', $subtopic->is_published ? '1' : '0') == '1' ? 'checked' : '' }}
                                       class="sr-only peer">
                                <div class="w-10 h-5 bg-gray-200 peer-checked:bg-indigo-600 rounded-full transition peer-focus:ring-2 peer-focus:ring-indigo-300"></div>
                                <div class="absolute top-0.5 left-0.5 w-4 h-4 bg-white rounded-full shadow transition peer-checked:translate-x-5"></div>
                            </div>
                            <div>
                                <p class="text-xs font-semibold text-gray-600"><i class="fas fa-toggle-on text-gray-400 mr-1"></i> Published</p>
                                <p class="text-xs text-gray-400">Visible to enrolled learners</p>
                            </div>
                        </label>
                    </div>
                </div>
            </div>
        </div>

        <div class="flex justify-between mt-4">
            <a href="{{ route('self-paced.dashboard.courses.topics.subtopics.show', [$course, $topic, $subtopic]) }}"
               class="inline-flex items-center gap-2 px-5 py-2.5 bg-gray-100 hover:bg-gray-200 text-gray-700 text-sm font-semibold rounded-lg transition">
                <i class="fas fa-times"></i> Cancel
            </a>
            <button type="submit"
                    class="inline-flex items-center gap-2 px-6 py-2.5 bg-green-600 hover:bg-green-700 text-white text-sm font-semibold rounded-lg transition shadow">
                <i class="fas fa-save"></i> Save Changes
            </button>
        </div>

    </form>
</div>

{{-- Video embed dialog --}}
<div id="video-dialog-overlay">
    <div id="video-dialog">
        <h3 class="text-sm font-semibold text-gray-800 mb-1 flex items-center gap-2">
            <i class="fas fa-video text-indigo-500"></i> Embed Video
        </h3>
        <p class="text-xs text-gray-500 mb-3">Paste a YouTube, Vimeo, or direct video URL.</p>
        <input type="text" id="video-url-input" placeholder="https://www.youtube.com/watch?v=..."
               class="w-full px-3 py-2 text-sm border border-gray-200 rounded-lg focus:outline-none focus:ring-2 focus:ring-indigo-300 mb-3">
        <div class="flex gap-2 justify-end">
            <button type="button" id="video-cancel"
                    class="px-4 py-2 text-sm bg-gray-100 hover:bg-gray-200 text-gray-700 rounded-lg transition">Cancel</button>
            <button type="button" id="video-insert"
                    class="px-4 py-2 text-sm bg-indigo-600 hover:bg-indigo-700 text-white font-semibold rounded-lg transition">Insert</button>
        </div>
    </div>
</div>
@endsection

@push('scripts')
<script src="https://cdn.jsdelivr.net/npm/quill@2.0.3/dist/quill.js"></script>
<script>
(function () {
    const overlay  = document.getElementById('video-dialog-overlay');
    const urlInput = document.getElementById('video-url-input');
    let quillRange = null;

    function openVideoDialog(range) {
        quillRange = range;
        urlInput.value = '';
        overlay.classList.add('active');
        setTimeout(() => urlInput.focus(), 50);
    }

    document.getElementById('video-cancel').addEventListener('click', () => {
        overlay.classList.remove('active');
    });

    overlay.addEventListener('click', (e) => {
        if (e.target === overlay) overlay.classList.remove('active');
    });

    document.getElementById('video-insert').addEventListener('click', () => {
        const url = urlInput.value.trim();
        if (!url) return;
        overlay.classList.remove('active');

        let embedUrl = url;
        const ytMatch = url.match(/(?:youtube\.com\/watch\?v=|youtu\.be\/)([A-Za-z0-9_-]{11})/);
        if (ytMatch) embedUrl = 'https://www.youtube.com/embed/' + ytMatch[1];
        const vimeoMatch = url.match(/vimeo\.com\/(\d+)/);
        if (vimeoMatch) embedUrl = 'https://player.vimeo.com/video/' + vimeoMatch[1];

        const index = quillRange ? quillRange.index : quill.getLength();
        quill.insertEmbed(index, 'video', embedUrl, 'user');
        quill.setSelection(index + 1, 0);
    });

    function imageUploadHandler() {
        const input = document.createElement('input');
        input.setAttribute('type', 'file');
        input.setAttribute('accept', 'image/*');
        input.click();

        input.onchange = async () => {
            const file = input.files[0];
            if (!file) return;

            const formData = new FormData();
            formData.append('file', file);
            formData.append('_token', document.querySelector('meta[name="csrf-token"]').content);

            try {
                const res = await fetch('{{ route("api.self-paced.media.upload") }}', {
                    method: 'POST',
                    body: formData,
                });
                const data = await res.json();
                if (res.ok && data.location) {
                    const range = quill.getSelection(true);
                    quill.insertEmbed(range.index, 'image', data.location, 'user');
                    quill.setSelection(range.index + 1, 0);
                } else {
                    alert(data.error || 'Image upload failed. Please try again.');
                }
            } catch (e) {
                alert('Image upload failed. Please try again.');
            }
        };
    }

    const toolbarOptions = [
        [{ 'header': [1, 2, 3, 4, false] }],
        [{ 'font': [] }],
        [{ 'size': ['small', false, 'large', 'huge'] }],
        ['bold', 'italic', 'underline', 'strike'],
        [{ 'color': [] }, { 'background': [] }],
        [{ 'align': [] }],
        [{ 'list': 'ordered' }, { 'list': 'bullet' }, { 'list': 'check' }],
        [{ 'indent': '-1' }, { 'indent': '+1' }],
        ['blockquote', 'code-block'],
        ['link', 'image', 'video'],
        [{ 'script': 'sub' }, { 'script': 'super' }],
        ['clean'],
    ];

    const quill = new Quill('#quill-editor', {
        theme: 'snow',
        placeholder: 'Write the sub-topic content here…',
        modules: {
            toolbar: {
                container: toolbarOptions,
                handlers: {
                    image: imageUploadHandler,
                    video: function () {
                        openVideoDialog(this.quill.getSelection());
                    },
                },
            },
            history: { delay: 1000, maxStack: 200, userOnly: true },
        },
    });

    // Load existing content
    const existing = document.getElementById('content-input').value.trim();
    if (existing) {
        quill.clipboard.dangerouslyPasteHTML(existing);
    }

    // Sync to hidden textarea on submit
    document.getElementById('subtopic-form').addEventListener('submit', function () {
        document.getElementById('content-input').value = quill.getSemanticHTML();
    });
})();
</script>
@endpush
