<x-app-layout>

<x-module-hero
    title="Create New Thread"
    description="Start a discussion with partners and mentors"
    icon="fa-plus-circle">

    <x-slot name="backButton">
        <a href="{{ route('partners.forum.index') }}"
           class="inline-flex items-center gap-1 text-sm text-[#475569] hover:text-[#1e293b] transition-colors">
            <i class="fas fa-arrow-left text-xs"></i> Back to Forum
        </a>
    </x-slot>

    <x-slot name="tabs">
        @can('view partners')
        <a href="{{ route('partners.index') }}"
           class="module-hero-tab {{ request()->routeIs('partners.index') && !request()->routeIs('partners.forum.*') ? 'border-b-2 border-[#1e293b]' : 'opacity-70 hover:opacity-100 transition-opacity' }}
                  inline-flex items-center gap-2 px-4 py-3 text-[#1e293b] text-sm font-medium
                  md:w-auto w-full border-b border-[#cbd5e1] md:border-b-0">
            <i class="fas fa-handshake text-sm"></i> Partners
        </a>
        @endcan
        @can('view forum')
        <a href="{{ route('partners.forum.index') }}"
           class="module-hero-tab {{ request()->routeIs('partners.forum.index') ? 'border-b-2 border-[#1e293b]' : 'opacity-70 hover:opacity-100 transition-opacity' }}
                  inline-flex items-center gap-2 px-4 py-3 text-[#1e293b] text-sm font-medium
                  md:w-auto w-full border-b border-[#cbd5e1] md:border-b-0">
            <i class="fas fa-comments text-sm"></i> Forum
        </a>
        @endcan
        @can('create forum threads')
        <a href="{{ route('partners.forum.create') }}"
           class="module-hero-tab {{ request()->routeIs('partners.forum.create') ? 'border-b-2 border-[#1e293b]' : 'opacity-70 hover:opacity-100 transition-opacity' }}
                  inline-flex items-center gap-2 px-4 py-3 text-[#1e293b] text-sm font-medium
                  md:w-auto w-full border-b border-[#cbd5e1] md:border-b-0">
            <i class="fas fa-plus text-sm"></i> New Thread
        </a>
        @endcan
    </x-slot>

</x-module-hero>

<div class="p-6">
    @if(session('error'))
        <div class="mb-4 p-4 bg-red-100 border border-red-400 text-red-700 rounded-lg flex items-center gap-2">
            <i class="fas fa-exclamation-circle"></i> {{ session('error') }}
        </div>
    @endif

    <div class="grid grid-cols-1 lg:grid-cols-3 gap-6">

        {{-- Main Form --}}
        <div class="lg:col-span-2">
            <form action="{{ route('partners.forum.store') }}" method="POST" enctype="multipart/form-data" id="create-thread-form">
                @csrf

                {{-- Title --}}
                <div class="bg-white rounded-xl shadow-sm border border-gray-200 p-6 mb-5">
                    <h3 class="text-sm font-semibold text-gray-800 mb-4 flex items-center gap-2">
                        <i class="fas fa-heading text-indigo-600"></i> Thread Title
                    </h3>
                    <input type="text"
                           name="title"
                           id="title"
                           value="{{ old('title') }}"
                           required
                           minlength="5"
                           maxlength="191"
                           placeholder="Enter a clear and descriptive title..."
                           class="w-full px-4 py-3 border border-gray-300 rounded-lg focus:ring-2 focus:ring-indigo-500 focus:border-transparent text-sm @error('title') border-red-500 @enderror">
                    @error('title')
                        <p class="mt-1 text-xs text-red-600">{{ $message }}</p>
                    @enderror
                    <p class="mt-1.5 text-xs text-gray-400">Minimum 5 characters, maximum 191 characters.</p>
                </div>

                {{-- Category & Visibility --}}
                <div class="bg-white rounded-xl shadow-sm border border-gray-200 p-6 mb-5">
                    <h3 class="text-sm font-semibold text-gray-800 mb-4 flex items-center gap-2">
                        <i class="fas fa-tag text-indigo-600"></i> Category & Visibility
                    </h3>
                    <div class="grid grid-cols-1 md:grid-cols-2 gap-5">
                        <div>
                            <label for="category" class="block text-xs font-medium text-gray-700 mb-1.5">
                                Category <span class="text-red-500">*</span>
                            </label>
                            <select name="category" id="category" required
                                    class="w-full px-4 py-2.5 border border-gray-300 rounded-lg focus:ring-2 focus:ring-indigo-500 focus:border-transparent text-sm @error('category') border-red-500 @enderror">
                                <option value="">Select a category...</option>
                                <option value="general"        {{ old('category') == 'general'        ? 'selected' : '' }}>General Discussion</option>
                                <option value="collaboration"  {{ old('category') == 'collaboration'  ? 'selected' : '' }}>Collaboration</option>
                                <option value="resources"      {{ old('category') == 'resources'      ? 'selected' : '' }}>Resources</option>
                                <option value="events"         {{ old('category') == 'events'         ? 'selected' : '' }}>Events</option>
                                <option value="announcements"  {{ old('category') == 'announcements'  ? 'selected' : '' }}>Announcements</option>
                                <option value="questions"      {{ old('category') == 'questions'      ? 'selected' : '' }}>Questions & Answers</option>
                                <option value="best_practices" {{ old('category') == 'best_practices' ? 'selected' : '' }}>Best Practices</option>
                                <option value="opportunities"  {{ old('category') == 'opportunities'  ? 'selected' : '' }}>Opportunities</option>
                            </select>
                            @error('category')
                                <p class="mt-1 text-xs text-red-600">{{ $message }}</p>
                            @enderror
                        </div>
                        <div>
                            <label for="visibility" class="block text-xs font-medium text-gray-700 mb-1.5">
                                Visibility
                            </label>
                            <select name="visibility" id="visibility"
                                    class="w-full px-4 py-2.5 border border-gray-300 rounded-lg focus:ring-2 focus:ring-indigo-500 focus:border-transparent text-sm">
                                <option value="public" {{ old('visibility') == 'public' ? 'selected' : '' }}>
                                    🌐 Public — All forum members
                                </option>
                                @if(auth()->user()->hasRole('Partners'))
                                    <option value="partners_only" {{ old('visibility') == 'partners_only' ? 'selected' : '' }}>
                                        🤝 Partners Only
                                    </option>
                                @endif
                                @if(auth()->user()->hasRole('Mentor'))
                                    <option value="mentors_only" {{ old('visibility') == 'mentors_only' ? 'selected' : '' }}>
                                        🎓 Mentors Only
                                    </option>
                                @endif
                            </select>
                            <p class="mt-1.5 text-xs text-gray-400">Control who can view this thread.</p>
                        </div>
                    </div>
                </div>

                {{-- Content (Rich Text Editor) --}}
                <div class="bg-white rounded-xl shadow-sm border border-gray-200 p-6 mb-5">
                    <h3 class="text-sm font-semibold text-gray-800 mb-4 flex items-center gap-2">
                        <i class="fas fa-align-left text-indigo-600"></i> Content <span class="text-red-500">*</span>
                    </h3>
                    {{-- Quill toolbar --}}
                    <div id="quill-toolbar" class="border border-gray-300 rounded-t-lg bg-gray-50">
                        <span class="ql-formats">
                            <select class="ql-header">
                                <option selected></option>
                                <option value="1">Heading 1</option>
                                <option value="2">Heading 2</option>
                                <option value="3">Heading 3</option>
                            </select>
                        </span>
                        <span class="ql-formats">
                            <button class="ql-bold"></button>
                            <button class="ql-italic"></button>
                            <button class="ql-underline"></button>
                            <button class="ql-strike"></button>
                        </span>
                        <span class="ql-formats">
                            <button class="ql-blockquote"></button>
                            <button class="ql-code-block"></button>
                        </span>
                        <span class="ql-formats">
                            <button class="ql-list" value="ordered"></button>
                            <button class="ql-list" value="bullet"></button>
                            <button class="ql-indent" value="-1"></button>
                            <button class="ql-indent" value="+1"></button>
                        </span>
                        <span class="ql-formats">
                            <button class="ql-link"></button>
                            <button class="ql-image"></button>
                        </span>
                        <span class="ql-formats">
                            <button class="ql-clean"></button>
                        </span>
                    </div>
                    <div id="quill-editor"
                         class="border border-t-0 border-gray-300 rounded-b-lg bg-white"
                         style="min-height: 280px; font-size: 0.9rem;">
                        {!! old('content') ? old('content') : '' !!}
                    </div>
                    <input type="hidden" name="content" id="content-input">
                    @error('content')
                        <p class="mt-1 text-xs text-red-600">{{ $message }}</p>
                    @enderror
                    <p class="mt-1.5 text-xs text-gray-400">Minimum 10 characters. Use the toolbar to format your content.</p>
                </div>

                {{-- Tags --}}
                <div class="bg-white rounded-xl shadow-sm border border-gray-200 p-6 mb-5">
                    <h3 class="text-sm font-semibold text-gray-800 mb-4 flex items-center gap-2">
                        <i class="fas fa-tags text-indigo-600"></i> Tags <span class="text-gray-400 font-normal text-xs">(optional)</span>
                    </h3>
                    <input type="text"
                           name="tags_input"
                           id="tags_input"
                           value="{{ old('tags_input') }}"
                           placeholder="collaboration, research, health-advocacy (comma-separated)"
                           class="w-full px-4 py-2.5 border border-gray-300 rounded-lg focus:ring-2 focus:ring-indigo-500 focus:border-transparent text-sm">
                    <p class="mt-1.5 text-xs text-gray-400">Add up to 5 tags to help others find your thread.</p>
                    <div id="tag-preview" class="mt-2 flex flex-wrap gap-1.5"></div>
                </div>

                {{-- File Attachments --}}
                <div class="bg-white rounded-xl shadow-sm border border-gray-200 p-6 mb-5">
                    <h3 class="text-sm font-semibold text-gray-800 mb-4 flex items-center gap-2">
                        <i class="fas fa-paperclip text-indigo-600"></i> Attachments <span class="text-gray-400 font-normal text-xs">(optional, max 5 files)</span>
                    </h3>

                    <div id="drop-zone"
                         class="border-2 border-dashed border-gray-300 rounded-xl p-8 text-center cursor-pointer hover:border-indigo-400 hover:bg-indigo-50/30 transition-all"
                         onclick="document.getElementById('file-input').click()">
                        <i class="fas fa-cloud-upload-alt text-3xl text-gray-400 mb-3 block"></i>
                        <p class="text-sm font-medium text-gray-700">Drop files here or click to browse</p>
                        <p class="text-xs text-gray-400 mt-1">Images (JPG, PNG, GIF, WebP), PDF, Word (DOC, DOCX), Excel (XLS, XLSX)</p>
                        <p class="text-xs text-gray-400">Max 10 MB per file · Up to 5 files</p>
                    </div>

                    <input type="file"
                           id="file-input"
                           name="attachments[]"
                           multiple
                           accept=".jpg,.jpeg,.png,.gif,.webp,.pdf,.doc,.docx,.xls,.xlsx"
                           class="hidden">

                    <div id="file-preview" class="mt-4 space-y-2"></div>
                </div>

                {{-- Submit --}}
                <div class="flex items-center justify-between">
                    <a href="{{ route('partners.forum.index') }}"
                       class="inline-flex items-center gap-2 px-5 py-2.5 bg-gray-100 text-gray-700 rounded-lg hover:bg-gray-200 transition text-sm font-medium">
                        <i class="fas fa-arrow-left"></i> Back
                    </a>
                    <button type="submit" id="submit-btn"
                            class="inline-flex items-center gap-2 px-6 py-2.5 bg-indigo-600 text-white rounded-lg hover:bg-indigo-700 transition text-sm font-semibold shadow-sm">
                        <i class="fas fa-paper-plane"></i> Create Thread
                    </button>
                </div>
            </form>
        </div>

        {{-- Sidebar --}}
        <div class="space-y-5">
            {{-- Guidelines --}}
            <div class="bg-indigo-50 rounded-xl border border-indigo-200 p-5">
                <h4 class="font-semibold text-indigo-900 mb-3 flex items-center gap-2 text-sm">
                    <i class="fas fa-info-circle text-indigo-600"></i> Posting Guidelines
                </h4>
                <ul class="text-xs text-indigo-800 space-y-2">
                    <li class="flex items-start gap-2">
                        <i class="fas fa-check text-indigo-500 mt-0.5 flex-shrink-0"></i>
                        Be respectful and professional in your communication.
                    </li>
                    <li class="flex items-start gap-2">
                        <i class="fas fa-check text-indigo-500 mt-0.5 flex-shrink-0"></i>
                        Stay on topic and provide clear, relevant information.
                    </li>
                    <li class="flex items-start gap-2">
                        <i class="fas fa-check text-indigo-500 mt-0.5 flex-shrink-0"></i>
                        Avoid sharing confidential or sensitive information.
                    </li>
                    <li class="flex items-start gap-2">
                        <i class="fas fa-check text-indigo-500 mt-0.5 flex-shrink-0"></i>
                        Use appropriate categories and tags for better organisation.
                    </li>
                    <li class="flex items-start gap-2">
                        <i class="fas fa-check text-indigo-500 mt-0.5 flex-shrink-0"></i>
                        Search existing threads before posting to avoid duplicates.
                    </li>
                </ul>
            </div>

            {{-- Category Guide --}}
            <div class="bg-white rounded-xl shadow-sm border border-gray-200 p-5">
                <h4 class="font-semibold text-gray-900 mb-3 text-sm">Category Guide</h4>
                <div class="space-y-2 text-xs text-gray-600">
                    <div class="flex items-start gap-2">
                        <span class="px-1.5 py-0.5 bg-blue-100 text-blue-700 rounded text-xs font-medium flex-shrink-0">General</span>
                        <span>Open discussions on any topic</span>
                    </div>
                    <div class="flex items-start gap-2">
                        <span class="px-1.5 py-0.5 bg-green-100 text-green-700 rounded text-xs font-medium flex-shrink-0">Collab</span>
                        <span>Joint projects and partnerships</span>
                    </div>
                    <div class="flex items-start gap-2">
                        <span class="px-1.5 py-0.5 bg-purple-100 text-purple-700 rounded text-xs font-medium flex-shrink-0">Q&A</span>
                        <span>Questions seeking answers</span>
                    </div>
                    <div class="flex items-start gap-2">
                        <span class="px-1.5 py-0.5 bg-yellow-100 text-yellow-700 rounded text-xs font-medium flex-shrink-0">Events</span>
                        <span>Upcoming events and activities</span>
                    </div>
                </div>
            </div>

            {{-- Attachment Guide --}}
            <div class="bg-white rounded-xl shadow-sm border border-gray-200 p-5">
                <h4 class="font-semibold text-gray-900 mb-3 text-sm flex items-center gap-2">
                    <i class="fas fa-paperclip text-gray-500"></i> Supported Files
                </h4>
                <div class="space-y-1.5 text-xs text-gray-600">
                    <div class="flex items-center gap-2">
                        <i class="fas fa-image text-blue-500 w-4"></i>
                        <span>Images: JPG, PNG, GIF, WebP</span>
                    </div>
                    <div class="flex items-center gap-2">
                        <i class="fas fa-file-pdf text-red-500 w-4"></i>
                        <span>Documents: PDF</span>
                    </div>
                    <div class="flex items-center gap-2">
                        <i class="fas fa-file-word text-blue-700 w-4"></i>
                        <span>Word: DOC, DOCX</span>
                    </div>
                    <div class="flex items-center gap-2">
                        <i class="fas fa-file-excel text-green-600 w-4"></i>
                        <span>Excel: XLS, XLSX</span>
                    </div>
                    <p class="text-gray-400 mt-2">Max 10 MB per file · Up to 5 files</p>
                </div>
            </div>
        </div>
    </div>
</div>

{{-- Quill CSS --}}
<link href="https://cdn.jsdelivr.net/npm/quill@2.0.2/dist/quill.snow.css" rel="stylesheet">

@push('scripts')
<script src="https://cdn.jsdelivr.net/npm/quill@2.0.2/dist/quill.js"></script>
<script>
// ── Quill Rich Text Editor ────────────────────────────────────────────────────
const quill = new Quill('#quill-editor', {
    theme: 'snow',
    modules: {
        toolbar: '#quill-toolbar',
        clipboard: { matchVisual: false },
    },
    placeholder: 'Describe your discussion topic in detail. Include any relevant background information, questions, or context...',
});

// Restore old content if validation failed
@if(old('content'))
    quill.root.innerHTML = {!! json_encode(old('content')) !!};
@endif

// Sync Quill content to hidden input before submit
document.getElementById('create-thread-form').addEventListener('submit', function (e) {
    const content = quill.root.innerHTML.trim();
    const text    = quill.getText().trim();

    if (text.length < 10) {
        e.preventDefault();
        quill.root.style.borderColor = '#ef4444';
        quill.root.focus();
        if (window.showToast) window.showToast('Content must be at least 10 characters.', 'error');
        return;
    }

    document.getElementById('content-input').value = content;
});

// ── Tag Preview ───────────────────────────────────────────────────────────────
const tagsInput   = document.getElementById('tags_input');
const tagPreview  = document.getElementById('tag-preview');

tagsInput.addEventListener('input', function () {
    const tags = this.value.split(',').map(t => t.trim()).filter(Boolean).slice(0, 5);
    tagPreview.innerHTML = tags.map(t =>
        `<span class="px-2 py-0.5 bg-indigo-100 text-indigo-700 text-xs rounded-full">#${t}</span>`
    ).join('');
});

// ── File Attachment Preview ───────────────────────────────────────────────────
const fileInput   = document.getElementById('file-input');
const filePreview = document.getElementById('file-preview');
const dropZone    = document.getElementById('drop-zone');
let selectedFiles = [];

const iconMap = {
    'image':       '<i class="fas fa-image text-blue-500"></i>',
    'pdf':         '<i class="fas fa-file-pdf text-red-500"></i>',
    'word':        '<i class="fas fa-file-word text-blue-700"></i>',
    'excel':       '<i class="fas fa-file-excel text-green-600"></i>',
    'default':     '<i class="fas fa-file text-gray-500"></i>',
};

function getFileIcon(name) {
    const ext = name.split('.').pop().toLowerCase();
    if (['jpg','jpeg','png','gif','webp'].includes(ext)) return iconMap.image;
    if (ext === 'pdf') return iconMap.pdf;
    if (['doc','docx'].includes(ext)) return iconMap.word;
    if (['xls','xlsx'].includes(ext)) return iconMap.excel;
    return iconMap.default;
}

function formatBytes(bytes) {
    if (bytes < 1024) return bytes + ' B';
    if (bytes < 1048576) return (bytes / 1024).toFixed(1) + ' KB';
    return (bytes / 1048576).toFixed(1) + ' MB';
}

function renderFilePreviews() {
    filePreview.innerHTML = '';
    selectedFiles.forEach((file, idx) => {
        const div = document.createElement('div');
        div.className = 'flex items-center gap-3 p-3 bg-gray-50 rounded-lg border border-gray-200';
        div.innerHTML = `
            <div class="text-xl flex-shrink-0">${getFileIcon(file.name)}</div>
            ${file.type.startsWith('image/') ? `<img src="${URL.createObjectURL(file)}" class="w-10 h-10 rounded object-cover flex-shrink-0">` : ''}
            <div class="flex-1 min-w-0">
                <p class="text-sm font-medium text-gray-800 truncate">${file.name}</p>
                <p class="text-xs text-gray-500">${formatBytes(file.size)}</p>
            </div>
            <button type="button" onclick="removeFile(${idx})"
                    class="text-gray-400 hover:text-red-500 transition p-1">
                <i class="fas fa-times"></i>
            </button>`;
        filePreview.appendChild(div);
    });
    syncFileInput();
}

function removeFile(idx) {
    selectedFiles.splice(idx, 1);
    renderFilePreviews();
}

function syncFileInput() {
    const dt = new DataTransfer();
    selectedFiles.forEach(f => dt.items.add(f));
    fileInput.files = dt.files;
}

fileInput.addEventListener('change', function () {
    const newFiles = Array.from(this.files);
    const combined = [...selectedFiles, ...newFiles].slice(0, 5);
    selectedFiles = combined;
    renderFilePreviews();
});

// Drag & drop
dropZone.addEventListener('dragover', e => { e.preventDefault(); dropZone.classList.add('border-indigo-500','bg-indigo-50'); });
dropZone.addEventListener('dragleave', () => dropZone.classList.remove('border-indigo-500','bg-indigo-50'));
dropZone.addEventListener('drop', e => {
    e.preventDefault();
    dropZone.classList.remove('border-indigo-500','bg-indigo-50');
    const dropped = Array.from(e.dataTransfer.files);
    const combined = [...selectedFiles, ...dropped].slice(0, 5);
    selectedFiles = combined;
    renderFilePreviews();
});
</script>
@endpush

</x-app-layout>
