<x-app-layout>

<x-module-hero
    title="Networking Forum"
    description="Connect and collaborate with partners and mentors"
    icon="fa-comments">

    <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>

    @can('create forum threads')
    <x-slot name="actions">
        <a href="{{ route('partners.forum.create') }}"
           class="inline-flex items-center gap-2 px-4 py-2 bg-[#1e293b] hover:bg-[#334155] text-white text-sm font-medium rounded-lg transition-colors">
            <i class="fas fa-plus"></i> New Thread
        </a>
    </x-slot>
    @endcan

</x-module-hero>

{{-- Category Filter Bar --}}
<div class="bg-white border-b border-gray-200 px-6 py-3">
    <div class="flex flex-wrap gap-2">
        <a href="{{ route('partners.forum.index') }}"
           class="px-3 py-1.5 rounded-full text-xs font-medium transition
               {{ !request('category') ? 'bg-indigo-600 text-white shadow-sm' : 'bg-gray-100 text-gray-600 hover:bg-gray-200' }}">
            All Topics
        </a>
        @foreach($categories as $value => $label)
            <a href="{{ route('partners.forum.index', ['category' => $value, 'q' => request('q')]) }}"
               class="px-3 py-1.5 rounded-full text-xs font-medium transition
                   {{ request('category') == $value ? 'bg-indigo-600 text-white shadow-sm' : 'bg-gray-100 text-gray-600 hover:bg-gray-200' }}">
                {{ $label }}
            </a>
        @endforeach
    </div>
</div>

{{-- Flash Messages --}}
<div class="px-6 pt-4">
    @if(session('success'))
        <div class="mb-4 p-4 bg-green-100 border border-green-400 text-green-700 rounded-lg flex items-center gap-2">
            <i class="fas fa-check-circle"></i> {{ session('success') }}
        </div>
    @endif
    @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>

{{-- Search Bar --}}
<div class="px-6 pb-4">
    <div class="bg-white rounded-xl shadow-sm border border-gray-200 p-4">
        <div class="flex flex-col sm:flex-row gap-3">
            <div class="flex-1 relative">
                <input type="text"
                       id="forum-search"
                       value="{{ $filters['q'] ?? '' }}"
                       placeholder="Search discussions... (results appear as you type)"
                       autocomplete="off"
                       class="w-full pl-10 pr-4 py-2.5 border border-gray-300 rounded-lg text-sm focus:ring-2 focus:ring-indigo-500 focus:border-transparent transition">
                <i class="fas fa-search absolute left-3 top-1/2 -translate-y-1/2 text-gray-400 text-sm"></i>
                <div id="search-spinner" class="hidden absolute right-3 top-1/2 -translate-y-1/2">
                    <i class="fas fa-circle-notch fa-spin text-indigo-400 text-sm"></i>
                </div>
            </div>
            @if(request('category'))
                <input type="hidden" id="category-filter" value="{{ request('category') }}">
            @endif
            @if(request('q') || request('category'))
                <a href="{{ route('partners.forum.index') }}"
                   class="px-4 py-2.5 bg-gray-100 text-gray-700 rounded-lg hover:bg-gray-200 transition text-sm flex items-center gap-1.5">
                    <i class="fas fa-times"></i> Clear
                </a>
            @endif
        </div>
    </div>
</div>

{{-- Threads Table --}}
<div class="px-6 pb-6" id="threads-container">
    @include('forum._threads_table', ['threads' => $threads])
</div>

{{-- Right-click Context Menu --}}
<div id="forum-context-menu"
     class="fixed z-50 bg-white rounded-xl shadow-2xl border border-gray-200 py-1.5 min-w-[200px]"
     style="display:none;">
    <div class="px-3 py-1.5 text-xs font-semibold text-gray-400 uppercase tracking-wider border-b border-gray-100 mb-1">
        Thread Actions
    </div>
    <button id="ctx-mark-read"
            class="w-full flex items-center gap-3 px-4 py-2.5 text-sm text-gray-700 hover:bg-indigo-50 hover:text-indigo-700 transition">
        <i class="fas fa-envelope-open w-4 text-center"></i> Mark as Read
    </button>
    <button id="ctx-mark-unread"
            class="w-full flex items-center gap-3 px-4 py-2.5 text-sm text-gray-700 hover:bg-indigo-50 hover:text-indigo-700 transition">
        <i class="fas fa-envelope w-4 text-center"></i> Mark as Unread
    </button>
    <div id="ctx-pin-divider" class="border-t border-gray-100 my-1" style="display:none;"></div>
    <button id="ctx-pin"
            class="w-full flex items-center gap-3 px-4 py-2.5 text-sm text-gray-700 hover:bg-yellow-50 hover:text-yellow-700 transition"
            style="display:none;">
        <i class="fas fa-thumbtack w-4 text-center"></i> <span id="ctx-pin-label">Pin to Top</span>
    </button>
    <div class="border-t border-gray-100 my-1"></div>
    <a id="ctx-open" href="#"
       class="flex items-center gap-3 px-4 py-2.5 text-sm text-gray-700 hover:bg-gray-50 transition">
        <i class="fas fa-external-link-alt w-4 text-center"></i> Open Thread
    </a>
</div>

@push('scripts')
<script>
const CSRF        = document.querySelector('meta[name="csrf-token"]').content;
const searchInput = document.getElementById('forum-search');
const spinner     = document.getElementById('search-spinner');
const container   = document.getElementById('threads-container');
const ctxMenu     = document.getElementById('forum-context-menu');
const categoryVal = document.getElementById('category-filter')?.value ?? '';

// Server-side flag: does the current user have 'moderate forum' permission?
const CAN_MODERATE = @json(auth()->check() && auth()->user()->can('moderate forum'));

let searchTimeout;
let currentThreadId  = null;
let currentThreadUrl = null;
let currentIsPinned  = false;
let currentRow       = null;

// Show/hide the pin button based on permission
const ctxPin        = document.getElementById('ctx-pin');
const ctxPinDivider = document.getElementById('ctx-pin-divider');
if (CAN_MODERATE) {
    ctxPin.style.display        = '';
    ctxPinDivider.style.display = '';
}

// ── Real-time search ──────────────────────────────────────────────────────────
searchInput.addEventListener('input', function () {
    clearTimeout(searchTimeout);
    const q = this.value.trim();

    if (q.length === 0 && !categoryVal) {
        location.href = '{{ route('partners.forum.index') }}' + (categoryVal ? '?category=' + categoryVal : '');
        return;
    }

    spinner.classList.remove('hidden');
    searchTimeout = setTimeout(() => performSearch(q), 280);
});

function performSearch(q) {
    const url = new URL('{{ route('partners.forum.search') }}', window.location.origin);
    url.searchParams.set('q', q);
    if (categoryVal) url.searchParams.set('category', categoryVal);

    fetch(url.toString(), {
        headers: { 'Accept': 'application/json', 'X-CSRF-TOKEN': CSRF }
    })
    .then(r => r.json())
    .then(data => {
        spinner.classList.add('hidden');
        if (data.success) renderSearchResults(data.threads);
    })
    .catch(() => spinner.classList.add('hidden'));
}

function renderSearchResults(threads) {
    if (threads.length === 0) {
        container.innerHTML = `
            <div class="bg-white rounded-xl shadow-sm border border-gray-200 p-12 text-center">
                <i class="fas fa-search text-5xl text-gray-300 mb-4 block"></i>
                <h3 class="text-lg font-semibold text-gray-700 mb-2">No Discussions Found</h3>
                <p class="text-gray-500 text-sm">Try different keywords or clear the search.</p>
            </div>`;
        return;
    }

    let rows = threads.map((t) => `
        <tr class="forum-row odd:bg-white even:bg-gray-50 hover:bg-indigo-50/60 transition cursor-pointer border-b border-gray-100 last:border-0"
            data-thread-id="${t.id}"
            data-thread-url="${t.url}"
            data-is-pinned="${t.is_pinned ? '1' : '0'}"
            data-is-read="0"
            onclick="window.location.href='${t.url}'">
            <td class="px-4 py-3">
                <div class="flex items-start gap-3">
                    <div class="flex-shrink-0 mt-0.5 thread-status-icon">
                        ${t.is_pinned
                            ? '<i class="fas fa-thumbtack text-indigo-500 text-sm" title="Pinned"></i>'
                            : t.is_locked
                                ? '<i class="fas fa-lock text-gray-400 text-sm" title="Locked"></i>'
                                : '<i class="fas fa-circle text-indigo-500 text-xs" title="Unread"></i>'}
                    </div>
                    <div class="min-w-0">
                        <a href="${t.url}" class="font-medium text-gray-900 hover:text-indigo-600 text-sm ${t.is_pinned ? 'font-semibold' : ''}" onclick="event.stopPropagation()">
                            ${t.title}
                        </a>
                        <div class="mt-0.5 flex items-center gap-2 text-xs text-gray-500">
                            <span>by ${t.author}</span>
                            <span>· ${t.last_activity}</span>
                        </div>
                    </div>
                </div>
            </td>
            <td class="px-4 py-3 whitespace-nowrap">
                <span class="px-2 py-0.5 text-xs rounded-full bg-indigo-100 text-indigo-700">${t.category}</span>
            </td>
            <td class="px-4 py-3 whitespace-nowrap text-center text-sm text-gray-700">${t.replies}</td>
            <td class="px-4 py-3 whitespace-nowrap text-center text-sm text-gray-700">${t.views}</td>
            <td class="px-4 py-3 whitespace-nowrap text-sm text-gray-500">${t.last_activity}</td>
        </tr>`).join('');

    container.innerHTML = `
        <div class="bg-white rounded-xl shadow-sm border border-gray-200 overflow-hidden">
            <div class="overflow-x-auto">
                <table class="w-full">
                    <thead>
                        <tr class="bg-gray-50 border-b border-gray-200">
                            <th class="px-4 py-3 text-left text-xs font-semibold text-gray-600 uppercase tracking-wider w-1/2">Topic</th>
                            <th class="px-4 py-3 text-left text-xs font-semibold text-gray-600 uppercase tracking-wider">Category</th>
                            <th class="px-4 py-3 text-center text-xs font-semibold text-gray-600 uppercase tracking-wider">Replies</th>
                            <th class="px-4 py-3 text-center text-xs font-semibold text-gray-600 uppercase tracking-wider">Views</th>
                            <th class="px-4 py-3 text-left text-xs font-semibold text-gray-600 uppercase tracking-wider">Last Activity</th>
                        </tr>
                    </thead>
                    <tbody>${rows}</tbody>
                </table>
            </div>
            <div class="px-4 py-2 border-t border-gray-100 bg-gray-50 text-xs text-gray-500">
                ${threads.length} result${threads.length !== 1 ? 's' : ''} found
            </div>
        </div>`;

    attachRowContextListeners();
}

// ── Right-click context menu ──────────────────────────────────────────────────
function attachRowContextListeners() {
    document.querySelectorAll('.forum-row').forEach(row => {
        // Remove any previously attached listener to avoid duplicates
        row.removeEventListener('contextmenu', handleContextMenu);
        row.addEventListener('contextmenu', handleContextMenu);
    });
}

function handleContextMenu(e) {
    e.preventDefault();
    e.stopPropagation();

    currentRow       = e.currentTarget;
    currentThreadId  = currentRow.dataset.threadId;
    currentThreadUrl = currentRow.dataset.threadUrl;
    currentIsPinned  = currentRow.dataset.isPinned === '1';

    // Update pin label
    const pinLabel = document.getElementById('ctx-pin-label');
    if (pinLabel) pinLabel.textContent = currentIsPinned ? 'Unpin from Top' : 'Pin to Top';

    document.getElementById('ctx-open').href = currentThreadUrl;

    // Position menu — keep within viewport
    const menuW = 220, menuH = ctxMenu.scrollHeight || 200;
    let x = e.clientX, y = e.clientY;
    if (x + menuW > window.innerWidth)  x = window.innerWidth  - menuW - 8;
    if (y + menuH > window.innerHeight) y = window.innerHeight - menuH - 8;

    ctxMenu.style.left    = x + 'px';
    ctxMenu.style.top     = y + 'px';
    ctxMenu.style.display = 'block';
}

// Close menu on any click or Escape
document.addEventListener('click', (e) => {
    if (!ctxMenu.contains(e.target)) {
        ctxMenu.style.display = 'none';
    }
});

document.addEventListener('contextmenu', (e) => {
    // If right-click is NOT on a forum row, close the menu
    if (!e.target.closest('.forum-row')) {
        ctxMenu.style.display = 'none';
    }
});

document.addEventListener('keydown', e => {
    if (e.key === 'Escape') ctxMenu.style.display = 'none';
});

// ── Context menu button handlers ──────────────────────────────────────────────
document.getElementById('ctx-mark-read').addEventListener('click', () => {
    if (!currentThreadId) return;
    ctxMenu.style.display = 'none';

    postAction(
        `/api/partners/forum/${currentThreadId}/mark-read`,
        'Marked as read.',
        false,
        () => updateRowReadState(currentRow, true)
    );
});

document.getElementById('ctx-mark-unread').addEventListener('click', () => {
    if (!currentThreadId) return;
    ctxMenu.style.display = 'none';

    postAction(
        `/api/partners/forum/${currentThreadId}/mark-unread`,
        'Marked as unread.',
        false,
        () => updateRowReadState(currentRow, false)
    );
});

document.getElementById('ctx-pin').addEventListener('click', () => {
    if (!currentThreadId) return;
    ctxMenu.style.display = 'none';

    postAction(
        `/api/partners/forum/${currentThreadId}/toggle-pin`,
        currentIsPinned ? 'Thread unpinned.' : 'Thread pinned.',
        true
    );
});

/**
 * Update the row's visual read/unread indicator without a page reload.
 */
function updateRowReadState(row, isRead) {
    if (!row) return;

    row.dataset.isRead = isRead ? '1' : '0';

    const iconContainer = row.querySelector('.thread-status-icon');
    if (!iconContainer) return;

    // Only update if the thread is not pinned or locked (those icons take priority)
    const isPinned = row.dataset.isPinned === '1';
    const isLocked = iconContainer.querySelector('.fa-lock') !== null;

    if (!isPinned && !isLocked) {
        if (isRead) {
            iconContainer.innerHTML = '<i class="fas fa-comment text-gray-300 text-sm" title="Read"></i>';
        } else {
            iconContainer.innerHTML = '<i class="fas fa-circle text-indigo-500 text-xs" title="Unread"></i>';
        }
    }
}

/**
 * POST an action to the server.
 * @param {string}   url        - Endpoint URL
 * @param {string}   successMsg - Toast message on success
 * @param {boolean}  reload     - Whether to reload the page after success
 * @param {Function} onSuccess  - Optional callback on success (before reload)
 */
function postAction(url, successMsg, reload = false, onSuccess = null) {
    fetch(url, {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
            'X-CSRF-TOKEN': CSRF,
            'Accept': 'application/json',
        }
    })
    .then(r => {
        if (r.status === 401) {
            window.location.href = '/login';
            return null;
        }
        if (r.status === 403) {
            showToast('You do not have permission to perform this action.', 'error');
            return null;
        }
        return r.json();
    })
    .then(d => {
        if (!d) return;
        if (d.success) {
            showToast(d.message || successMsg, 'success');
            if (onSuccess) onSuccess();
            if (reload) setTimeout(() => location.reload(), 700);
        } else {
            showToast(d.message || 'Action failed.', 'error');
        }
    })
    .catch(() => showToast('Network error. Please try again.', 'error'));
}

/**
 * Simple toast notification — uses window.showToast if available,
 * otherwise falls back to a minimal inline implementation.
 */
function showToast(message, type = 'success') {
    if (window.showToast && window.showToast !== showToast) {
        window.showToast(message, type);
        return;
    }

    // Minimal fallback toast
    const existing = document.getElementById('forum-toast');
    if (existing) existing.remove();

    const colors = type === 'success'
        ? 'bg-green-600 text-white'
        : 'bg-red-600 text-white';

    const toast = document.createElement('div');
    toast.id = 'forum-toast';
    toast.className = `fixed bottom-6 right-6 z-[9999] px-5 py-3 rounded-lg shadow-lg text-sm font-medium transition-opacity ${colors}`;
    toast.textContent = message;
    document.body.appendChild(toast);

    setTimeout(() => {
        toast.style.opacity = '0';
        setTimeout(() => toast.remove(), 400);
    }, 3000);
}

// Attach context listeners to server-rendered rows on page load
document.addEventListener('DOMContentLoaded', () => attachRowContextListeners());
</script>
@endpush

</x-app-layout>
