@extends('front_end.pages.settings.layout')

@section('title', 'Blocking Settings - Socialink')

@section('settings_content')
<div class="card mb-4">
    <div class="card-header with-icon p-4">
        <div class="main-icon">
            <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><circle cx="12" cy="12" r="10"></circle><line x1="4.93" y1="4.93" x2="19.07" y2="19.07"></line></svg>
        </div>
        <h5 class="mb-0 ms-2">Blocked Users</h5>
    </div>
    <div class="card-body p-4">
        @if(session('success'))
        <div class="alert alert-success mb-4">
            {{ session('success') }}
        </div>
        @endif

        @if(session('error'))
        <div class="alert alert-danger mb-4">
            {{ session('error') }}
        </div>
        @endif
        <p class="text-muted mb-4">
            Manage who can interact with you across Socialink. Blocked accounts lose access to your profile, posts, and messaging.
        </p>

        <div class="mb-5">
            <h6 class="heading-small mb-3">Block Someone New</h6>
            <p class="small text-muted mb-3">
                Search for the person you want to block. We will show matching accounts as you type.
            </p>

            <div class="mb-3">
                <label class="form-label" for="block-user-search">Search by name or username</label>
                <div class="input-group">
                    <span class="input-group-text">
                        <i class="fas fa-search"></i>
                    </span>
                    <input type="text" id="block-user-search" class="form-control" placeholder="Start typing to find someone…" autocomplete="off">
                </div>
                <div class="form-text" id="block-user-feedback"></div>
            </div>

            <div class="list-group" id="block-user-results"></div>

            <form id="block-user-form" action="{{ route('settings.blocking.block') }}" method="POST" class="d-none">
                @csrf
                <input type="hidden" name="user_id" id="block-user-id">
            </form>
        </div>

        <h6 class="heading-small mb-3">Currently Blocked Users</h6>

        <div class="table-responsive">
            <table class="table">
                <thead>
                    <tr>
                        <th>User</th>
                        <th>Blocked Since</th>
                        <th>Actions</th>
                    </tr>
                </thead>
                <tbody>
                    @if(isset($blockedUsers) && count($blockedUsers) > 0)
                        @foreach($blockedUsers as $blockedUser)
                        @php
                            $avatar = getMedia($blockedUser->avatar, 'avatar') ?? asset('assets/images/default-avatar.jpg');
                            $displayName = $blockedUser->name ?? ($blockedUser->username ? '@' . $blockedUser->username : 'Unknown User');
                            $handle = $blockedUser->username ? '@' . $blockedUser->username : null;
                        @endphp
                        <tr>
                            <td>
                                <div class="d-flex align-items-center">
                                    <img src="{{ $avatar }}" alt="{{ $displayName }}" class="rounded-circle me-2" style="width: 40px; height: 40px; object-fit: cover;">
                                    <div>
                                        <div class="fw-bold">{{ $displayName }}</div>
                                        @if($handle)
                                        <small class="text-muted">{{ $handle }}</small>
                                        @endif
                                    </div>
                                </div>
                            </td>
                            <td>{{ \Carbon\Carbon::parse($blockedUser->created_at)->diffForHumans() }}</td>
                            <td>
                                <form action="{{ route('settings.blocking.unblock', $blockedUser->blocked_user_id) }}" method="POST" style="display: inline;">
                                    @csrf
                                    <button type="submit" class="btn btn-sm btn-outline-primary">Unblock</button>
                                </form>
                            </td>
                        </tr>
                        @endforeach
                    @else
                        <tr>
                            <td colspan="3" class="text-center">You haven't blocked any users yet.</td>
                        </tr>
                    @endif
                </tbody>
            </table>
        </div>
        
        <div class="mt-4">
            <div class="card bg-light">
                <div class="card-body">
                    <h6 class="card-title">About Blocking</h6>
                    <p class="mb-3 text-muted small">
                        Blocking is a discreet way to protect your space. The person you block will not be notified, but they will immediately lose access to you across Socialink.
                    </p>
                    <ul class="ps-3 mb-3">
                        <li>They can&rsquo;t view your profile, posts, or stories.</li>
                        <li>Messages, friend requests, and mentions from them are blocked.</li>
                        <li>Blocking also removes any existing follow or friend connections.</li>
                    </ul>
                    <p class="mb-0 text-muted small">
                        Need to change your mind later? Unblock them from the list above&mdash;your settings update right away.
                    </p>
                </div>
            </div>
        </div>
    </div>
</div>
@endsection 

@push('scripts')
<script>
document.addEventListener('DOMContentLoaded', () => {
    const searchInput = document.getElementById('block-user-search');
    const resultsContainer = document.getElementById('block-user-results');
    const feedback = document.getElementById('block-user-feedback');
    const blockForm = document.getElementById('block-user-form');
    const blockUserIdInput = document.getElementById('block-user-id');
    const defaultAvatar = @json(asset('assets/images/default-avatar.jpg'));
    const blockedUsersSet = new Set(@json(isset($blockedUsers) ? $blockedUsers->pluck('blocked_user_id')->all() : []));
    const messages = {
        initial: 'Type at least 2 characters to search.',
        searching: 'Searching…',
        none: 'No users matched your search.',
        error: 'Unable to search right now. Please try again.'
    };

    let debounceId = null;
    let abortController = null;

    if (!searchInput || !resultsContainer || !feedback) {
        return;
    }

    feedback.textContent = messages.initial;

    searchInput.addEventListener('input', () => {
        const query = searchInput.value.trim();

        if (debounceId) {
            clearTimeout(debounceId);
        }

        if (query.length < 2) {
            if (abortController) {
                abortController.abort();
            }
            feedback.textContent = messages.initial;
            resultsContainer.innerHTML = '';
            return;
        }

        feedback.textContent = messages.searching;

        debounceId = setTimeout(async () => {
            if (abortController) {
                abortController.abort();
            }
            abortController = new AbortController();

            try {
                const response = await fetch("{{ url('/web_api/messenger/users/search') }}?query=" + encodeURIComponent(query), {
                    headers: {
                        'Accept': 'application/json'
                    },
                    signal: abortController.signal
                });

                if (!response.ok) {
                    throw new Error('Request failed');
                }

                const payload = await response.json();
                const users = Array.isArray(payload.data) ? payload.data : [];

                if (users.length === 0) {
                    resultsContainer.innerHTML = '';
                    feedback.textContent = messages.none;
                    return;
                }

                feedback.textContent = '';
                resultsContainer.innerHTML = users.map(renderUserResult).join('');

                resultsContainer.querySelectorAll('[data-block-user]').forEach(button => {
                    button.addEventListener('click', () => {
                        const userId = Number(button.dataset.blockUser);

                        if (!userId || blockedUsersSet.has(userId)) {
                            return;
                        }

                        blockUserIdInput.value = userId;
                        blockForm.submit();
                    });
                });
            } catch (error) {
                if (error.name === 'AbortError') {
                    return;
                }

                console.error('User search failed', error);
                feedback.textContent = messages.error;
                resultsContainer.innerHTML = '';
            }
        }, 250);
    });

    function renderUserResult(user) {
        const isBlocked = blockedUsersSet.has(user.id);
        const name = (user.full_name && user.full_name.trim()) ? user.full_name : user.username;
        const username = user.username ? '@' + user.username : '';
        const avatar = user.avatar || defaultAvatar;

        return `
            <div class="list-group-item d-flex align-items-center justify-content-between">
                <div class="d-flex align-items-center">
                    <img src="${avatar}" alt="${name}" class="rounded-circle me-3" style="width: 40px; height: 40px; object-fit: cover;">
                    <div>
                        <div class="fw-semibold">${name}</div>
                        ${username ? `<div class="text-muted small">${username}</div>` : ''}
                    </div>
                </div>
                ${isBlocked
                    ? '<span class="badge bg-secondary">Blocked</span>'
                    : `<button type="button" class="btn btn-sm btn-outline-danger" data-block-user="${user.id}">Block</button>`
                }
            </div>
        `;
    }
});
</script>
@endpush
