@include('base.header')

<style>
    /* ------------------- LOADER ------------------- */
    #loaderBox {
        position: fixed;
        inset: 0;
        background: #ffffff;
        display: flex;
        align-items: center;
        justify-content: center;
        z-index: 9999;
        flex-direction: column;
        gap: 1rem;
        transition: opacity .45s ease;
    }

    #loaderBox.hidden {
        opacity: 0;
        pointer-events: none;
    }

    .loader-spinner {
        width: 64px;
        height: 64px;
        border: 6px solid rgba(0, 0, 0, 0.1);
        border-top-color: #ef4444;
        border-radius: 50%;
        animation: spin 1s linear infinite;
    }

    @keyframes spin {
        to {
            transform: rotate(360deg);
        }
    }

    #pageContent {
        opacity: 0;
        transition: opacity .45s ease;
    }

    #pageContent.visible {
        opacity: 1;
    }

    /* ------------------- MAIN CARD GRID ------------------- */
    #vendorCards {
        display: grid;
        grid-template-columns: 1fr;
        gap: 25px;
    }

    /* Medium 2 columns */
    @media (min-width: 576px) {
        #vendorCards {
            grid-template-columns: repeat(2, 1fr);
        }
    }

    /* Large 3 columns */
    @media (min-width: 992px) {
        #vendorCards {
            grid-template-columns: repeat(3, 1fr);
        }
    }

    /* ------------------- CARD STYLE ------------------- */
    .vendor-card {
        background: #fff;
        border-radius: 1rem;
        overflow: hidden;
        display: flex;
        flex-direction: column;
        box-shadow: 0px 8px 20px rgba(0, 0, 0, 0.08);
        transition: 0.25s ease;
        position: relative;
    }

    .vendor-card:hover {
        transform: translateY(-4px);
        box-shadow: 0px 12px 28px rgba(0, 0, 0, 0.12);
    }

    /* Purple circle badge */
    /* Purple circle badge */
    .card-badge {
        height: 75px;
        left: 10px;
        position: absolute;
        top: 10px;
        width: 75px;
    }

    .card-badge .badge-img {
        width: 100%;
        height: 100%;
        object-fit: contain;
        /* keeps aspect ratio */
    }


    /* Online badge */
    .card-status1 {
        position: absolute;
        top: 10px;
        right: 10px;
        background: #0a9163;
        color: #f6faf9;
        padding: 4px 15px;
        border-radius: 50px;
        font-size: 12px;
        font-weight: 500;
    }

    .card-status1 {
        position: absolute;
        top: 7px;
        right: 4px;
        background: #48ab78;
        color: #4aff05;
        padding: 4px 15px;
        border-radius: 50px;
        font-size: 7px;
        font-weight: 500;
        display: flex;
        align-items: center;
        gap: 6px;
        /* space between dot and text */
    }

    .card-status {
        align-items: center;
        background-color: #0a9163;
        border-radius: 24px;
        color: #fff;
        display: flex;
        font-family: PlusJakartaSans-Medium;
        font-size: 12px;
        gap: 4px;
        padding: 4px 8px;
        position: absolute;
        right: 10px;
        top: 10px;
    }

    /* BIGGER DOT */
    .card-status::before {
        content: "";
        width: 10px;
        /* increase size here */
        height: 10px;
        /* increase size here */
        background: #2cf8b4;
        border-radius: 50%;
        display: inline-block;
    }

    /* ✓ Icon */
    .card-icon {
        width: 50px;
        height: 50px;
        background: #dc2626;
        color: #fff;
        border-radius: 50%;
        display: flex;
        align-items: center;
        justify-content: center;
        margin: 0 auto;
        font-weight: bold;
        font-size: 20px;
    }

    /* Card body & footer */
    .vendor-card .card-body {
        padding: 1rem;
        padding-top: 60px;
        /* to avoid overlapping badge */
        text-align: center;
    }

    .vendor-card .card-footer {
        padding: 1rem;
        border-top: 1px solid #eee;
    }

    /* Back button inside first card */
    .card-back-btn {
        position: absolute;
        top: 10px;
        left: 10px;
        background: #f3f4f6;
        color: #111827;
        padding: 6px 12px;
        border-radius: 6px;
        font-weight: 500;
        text-decoration: none;
        font-size: 14px;
        display: flex;
        align-items: center;
        gap: 5px;
        z-index: 10;
        box-shadow: 0 2px 5px rgba(0, 0, 0, 0.1);
    }

    .card-back-btn:hover {
        background: #e5e7eb;
    }


    button.no-hover-change:hover {
        background: #ef4444 !important;
        /* keep original color */
        color: white !important;
        /* keep original text color */
    }

    .loader-small {
        width: 16px;
        height: 16px;
        border: 2px solid rgba(255, 255, 255, 0.3);
        border-top-color: #fff;
        border-radius: 50%;
        animation: spin 0.8s linear infinite;
    }

    @keyframes spin {
        to {
            transform: rotate(360deg);
        }
    }

    .service-filter-bar {
        width: 100%;
        background: #ffffff;
        border: 2px solid #ef4444;
        padding: 10px 12px;
        display: flex;
        align-items: flex-end;
        gap: 10px;
        position: fixed;
        top: 70px;
        left: 0;
        z-index: 1200;
       flex-wrap: wrap;
    overflow-x: hidden;
        box-shadow: 0 6px 18px rgba(0, 0, 0, 0.08);
    }

    /* hide scrollbar (optional) */
    .service-filter-bar::-webkit-scrollbar {
        height: 4px;
    }

    .service-filter-bar::-webkit-scrollbar-thumb {
        background: #ef4444;
        border-radius: 10px;
    }

    /* filter box */
    .service-filter-bar .filter-item {
        display: flex;
        flex-direction: column;
        min-width: 100px;
        flex-shrink: 0;
    }

    /* labels */
    .service-filter-bar .filter-item label {
        font-size: 11px;
        font-weight: 600;
        color: #ef4444;
        margin-bottom: 4px;
        text-align: left;
    }

    /* inputs & selects */
    .service-filter-bar .filter-item input,
    .service-filter-bar .filter-item select {
        height: 34px;
        padding: 4px 8px;
        font-size: 13px;
        border-radius: 8px;
        border: 1px solid #d1d5db;
        background: #f9fafb;
        color: #111827;
        outline: none;
    }

    /* focus */
    .service-filter-bar .filter-item input:focus,
    .service-filter-bar .filter-item select:focus {
        border-color: #ef4444;
        background: #ffffff;
    }

    /* remove number arrows */
    .no-spinner::-webkit-inner-spin-button,
    .no-spinner::-webkit-outer-spin-button {
        -webkit-appearance: none;
    }

    .no-spinner {
        -moz-appearance: textfield;
    }

    /* mobile */
    @media (max-width: 768px) {
        .service-filter-bar {
            top: 70px;
            padding: 8px;
            gap: 8px;
        }

        .service-filter-bar .filter-item {
            min-width: 100px;
        }

        .service-filter-bar .filter-item label {
            font-size: 10px;
        }

        .service-filter-bar .filter-item input,
        .service-filter-bar .filter-item select {
            height: 32px;
            font-size: 12px;
        }
    }

    .select2-container--default .select2-selection--multiple {
        min-height: 34px;
        border-radius: 8px;
        font-size: 12px;
    }

    .select2-selection__choice {
        font-size: 11px;
    }

     .rate-group {
        max-width: 30px !important;
    }
    .service-filter-bar .search-group {
    min-width: 90px;
}

.service-filter-bar .search-group button {
    height: 34px;
    border-radius: 8px;
    border: none;
    background: #ef4444;
    color: #ffffff;
    font-size: 13px;
    font-weight: 600;
    cursor: pointer;
    transition: background .2s ease;
}

.service-filter-bar .search-group button:hover {
    background: #dc2626;
}
/* ================= MOBILE FIX ================= */
@media (max-width: 768px) {

    /* Filter bar wraps to next line */
    .service-filter-bar {
        position: relative;
        top: 70px!important;
        flex-wrap: wrap;
        overflow-x: hidden;
    }

    /* Each filter takes full row or half */
    .service-filter-bar .filter-item {
        min-width: 48%;
        flex: 1 1 48%;
    }

    /* Search button full width */
    .service-filter-bar .search-group {
        flex: 1 1 100%;
    }

    /* Vendor cards responsive */
    #vendorCards {
        grid-template-columns: 1fr !important;
    }

    .vendor-card {
        width: 100% !important;
    }
}

</style>

@php
    $START_SECONDS = $web_time;
@endphp

<input type="hidden" id="distance" value="5">

<!-- LOADER -->
<div id="loaderBox">
    <div class="loader-spinner"></div>
    <div class="text-center">
        <div class="text-success fw-semibold">Kindly hold on for a minute while we search online for the relevant
            services.</div>
        <div id="loaderTimer" class="fs-2 fw-bold text-danger">{{ $START_SECONDS }}</div>
        <div class="text-secondary">
            Please wait <span id="loaderUnits">seconds</span>
        </div>
        <div style="text-align:center; margin-top:20px;">
            <button onclick="goHome()"
                style="
            padding: 12px 30px;
            background: #ffffff;
            border: 1px solid #d1d5db;
            border-radius: 8px;
            font-size: 18px;
            font-weight: 500;
            color: #111827;
            cursor: pointer;
            transition: 0.25s ease;
        ">
                Back to Home
            </button>
        </div>


    </div>
</div>
<input type="hidden" id="request_id" value="{{ $request_id }}">

<!-- PAGE CONTENT -->
<div id="pageContent">
    <!-- Toggle Button -->
    <!-- History toggle button -->
    <!-- FULL WIDTH FILTER BAR WITH SMALL INPUTS -->
    <!-- FULL WIDTH FILTER BAR WITH LABELS -->

   <div class="service-filter-bar">

            <!-- Service -->
            <div class="filter-item">
                <label>Service</label>
                <select id="serviceType">
                    <option value="" disabled>Select Service</option>
                    @foreach ($serviceTypeModels as $services)
                        <option value="{{ $services->id }}"
                            {{ ($requestData->service_type_id ?? '') == $services->id ? 'selected' : '' }}>
                            {{ $services->service_type }}
                        </option>
                    @endforeach
                </select>
            </div>

            <!-- Country -->
            <div class="filter-item country-group">
                <label>Country</label>
                <select>
                    @foreach ($countryModels as $c)
                        <option value="{{ $c->id }}"   {{ ($requestData->countryId ?? '') == $c->id ? 'selected' : '' }}>{{ $c->name }}</option>
                    @endforeach
                </select>
            </div>
 <!-- RATE GROUP -->
            <div class="filter-item rate-group">
                <label>Hr Min</label>
                <input type="test" class="no-spinner" value="{{ $requestData->hour_min }}">
            </div>
            <!-- RATE GROUP -->
            <div class="filter-item rate-group">
                <label>Hr Min</label>
                <input type="number" class="no-spinner" value="{{ $requestData->hour_min }}">
            </div>

            <div class="filter-item rate-group">
                <label>Hr Max</label>
                <input type="number" class="no-spinner" value="{{ $requestData->hour_max }}">
            </div>

            <div class="filter-item rate-group">
                <label>Night Min</label>
                <input type="number" class="no-spinner" value="{{ $requestData->night_min }}">
            </div>

            <div class="filter-item rate-group">
                <label>Night Max</label>
                <input type="number" class="no-spinner" value="{{ $requestData->night_max }}">
            </div>

            <!-- Availability -->
            <div class="filter-item availability-group">
                <label>Availability</label>
                <select>
                    <option value="1" {{ ($requestData->availability ?? '') == 1 ? 'selected' : '' }}>In Call</option>
                    <option value="2"{{ ($requestData->availability ?? '') == 2 ? 'selected' : '' }}>Out Call</option>
                    <option value="3" {{ ($requestData->availability ?? '') == 3 ? 'selected' : '' }}>Both</option>
                </select>
            </div>

            <!-- Language (MULTI) -->
            <div class="filter-item language-group">
                <label>Lang</label>
                <select id="languageSelect" multiple>
                    @foreach ($languageModels as $lang)
                        <option value="{{ $lang->id }}"
                            {{ in_array($lang->name, explode(', ', $requestData->languages ?? '')) ? 'selected' : '' }}>
                            {{ $lang->name }}
                        </option>
                    @endforeach
                </select>
            </div>
            <!-- Search Button -->
            <div class="filter-item search-group">
                <label>&nbsp;</label>
                <button type="button" id="filterSearchBtn">
                    Search
                </button>
            </div>

        </div>
    <main class="container py-5" style="padding-top:9rem!important;">
     


        <!-- CARD AREA -->
        {{-- <div id="vendorCards" style="width: 1500px"></div> --}}
        <div id="vendorCards"></div>

    </main>
    @if ($service != 4)
        <div style="text-align:center; margin:20px;    margin-top: 150px;align-items: center!important;">
            <button id="increaseDistanceBtn" class="no-hover-change" onclick="increaseDistance()"
                style="
        padding: 12px 25px;
        background: #ef4444;
        color: white;
        border: none;
        border-radius: 8px;
        font-size: 18px;
        cursor: pointer;
        display: flex;
        align-items: center;
        justify-content: center;
        gap: 8px;
    ">
                <span class="btn-text">Increase Distance +5 km</span>
                <span class="btn-loader" style="display:none;">
                    <div class="loader-small"></div>
                </span>
            </button>

        </div>
    @endif

</div>
<!-- jQuery -->
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script>
    function toggleFilters(serviceId) {
        console.log("serviceId");
        console.log(serviceId);
        // show all by default
        $('.rate-group, .availability-group, .language-group,.country-group').hide();

        if (serviceId == 4) {
            // ONLY language
            $('.rate-group, .availability-group').hide();
            $('.language-group').show();
        }

        if (serviceId == 3 || serviceId == 1 || serviceId == 2) {
            // hide rate + language + availability
            $('.rate-group, .availability-group,.country-group').show();
        }
    }

    // on change
    $('#serviceType').on('change', function() {
        toggleFilters($(this).val());
    });

    // on page load (important)


    $(document).ready(function() {
        toggleFilters($('#serviceType').val());
        $('#languageSelect').select2({
            placeholder: "Select Lang",
            width: '100%',
            closeOnSelect: false
        });


        const infoBox = $('.service-info-box');
        const toggleBtn = $('#serviceToggleBtn');

        // Toggle info box on icon click
        toggleBtn.on('click', function(e) {
            e.stopPropagation(); // prevent click from bubbling
            infoBox.toggle();
        });

        // Hide info box when clicking outside
        $(document).on('click', function(e) {
            if (!infoBox.is(e.target) && infoBox.has(e.target).length === 0 && !toggleBtn.is(e
                    .target)) {
                infoBox.hide();
            }
        });

        // Prevent clicks inside the info box from closing it
        infoBox.on('click', function(e) {
            e.stopPropagation();
        });
    });
</script>

<script>
    let firstLoad = true; // FIRST VISIT FLAG
    let loaderInterval = null;
    let service = {{ $service }};

    function increaseDistance() {
        let btn = $("#increaseDistanceBtn");
        let btnText = btn.find(".btn-text");
        let btnLoader = btn.find(".btn-loader");
        let dist = parseInt($("#distance").val());
        let newDist = dist + 5;


        let maxLimit = 25;

        // 🚫 Limit check
        if (newDist > maxLimit) {
            showToast('error', 'Distance limit exceeded. Maximum allowed is 25 km.');
            return;
        }

        $("#distance").val(newDist);

        // Show loader again
        // Disable button and show loader
        btn.prop("disabled", true);
        btn.css("opacity", 0.8);
        btnText.hide();
        btnLoader.show();
        searchDistanceIncreaseRequest(newDist);
    }

    function searchDistanceIncreaseRequest(newDist) {
        // STOP if service = 4
        if (service == 4) {
            return; // do nothing
        }
        let btn = $("#increaseDistanceBtn");
        let btnText = btn.find(".btn-text");
        let btnLoader = btn.find(".btn-loader");
        $.ajax({
            url: "/searchDistanceIncreaseRequest",
            method: "POST",
            data: {
                _token: "{{ csrf_token() }}",
                distance: newDist,
                requestId: $('#request_id').val()
            },
            success: function(response) {

                console.log("First request completed");
                startLoader(5);
                btn.prop("disabled", false);
                btn.css("opacity", 1);
                btnText.show();
                btnLoader.hide();

            }
        });

    }
    $(document).ready(function() {

        // CASE 1: Back/Forward cached page → NO LOADER
        window.addEventListener("pageshow", function(event) {
            if (event.persisted) {
                skipLoaderAndLoad();
                return;
            }
        });

        // CASE 2: Direct normal first visit → RUN LOADER
        startLoader(5);
    });

    function goHome() {
        // Stop loader timer if running
        if (window.loaderInterval) {
            clearInterval(window.loaderInterval);
        }

        // Redirect to home page
        window.location.href = "/";
    }

    function loadVendorData() {
        let btn = $("#increaseDistanceBtn");
        let btnText = btn.find(".btn-text");
        let btnLoader = btn.find(".btn-loader");
        // $("#vendorCards").html(`<p class="text-center text-secondary">Loading data...</p>`);
        var requestId = $('#request_id').val();
        $.ajax({
            url: "{{ route('getAcceptedrequests') }}",
            method: "GET",
            data: {
                id: requestId
            },
            dataType: "json",
            success: function(res) {


                // if (!res.data || res.data.length === 0) {
                //     window.location.href = "{{ url('/') }}?no_data=1";
                //     return;
                // }

                btn.prop("disabled", false);
                btn.css("opacity", 1);
                btnText.show();
                btnLoader.hide();

                let html = "";
//  <div class="vendor-card" style="width:250px!important; cursor:pointer;"onclick="openVendor('${item.id}', '${item.request_id}')">
                res.data.forEach((item, index) => {
                    html += `
               <div class="vendor-card" style="cursor:pointer;"
         onclick="openVendor('${item.id}', '${item.request_id}')">

                    <div class="card-body position-relative" style="background-image: url(${item.serviceImage}); background-size: cover; background-repeat: no-repeat; height: 300px;">




                        <div class='card-badge'>${item.service_type}</div>
                        <span class='card-status'>Online</span>

                        <div class="pt-3 pb-4 mt-5">

            <!-- VENDOR IMAGE -->


                  </div>

                    </div>

                    <div class="card-footer">
                        <h5 class="fw-bold">${item.title}</h5>
                        <p class="text-muted small">${item.language}</p>
                    </div>

                </div>
                `;
                });

                $("#vendorCards").html(html);
                var currentDistance = $("#distance").val();
                $('.currentDistance').text(currentDistance)
            }
        });
    }

    function skipLoaderAndLoad() {
        $("#loaderBox").hide();
        $("#pageContent").addClass("visible");
        document.body.style.overflow = "";
        loadVendorData();
    }

    function startLoader(distanceValue) {

        $("#pageContent").removeClass("visible");
        $("#loaderBox").show().removeClass("hidden");
        document.body.style.overflow = "hidden";

        let timeLeft = {{ $START_SECONDS }};
        const timerEl = document.getElementById("loaderTimer");
        const unitsEl = document.getElementById("loaderUnits");

        function updateUnits(n) {
            unitsEl.textContent = n === 1 ? "second" : "seconds";
        }

        updateUnits(timeLeft);
        timerEl.textContent = timeLeft;

        if (loaderInterval) clearInterval(loaderInterval);

        loaderInterval = setInterval(function() {
            timeLeft--;

            if (timeLeft <= 0) {
                clearInterval(loaderInterval);

                $("#loaderBox").addClass("hidden");
                setTimeout(() => $("#loaderBox").hide(), 450);
                $("#pageContent").addClass("visible");
                document.body.style.overflow = "";

                // Load vendor data after the timer ends
                loadVendorData();
            }

            updateUnits(timeLeft);
            timerEl.textContent = timeLeft;

        }, 1000);
    }

    window.addEventListener("pageshow", function(event) {

        const navType = performance.getEntriesByType("navigation")[0]?.type;

        // CASE 1: Back button (bfcache)
        if (event.persisted || navType === "back_forward") {
            console.log("Back navigation detected");
            skipLoaderAndLoad();
            return;
        }

        // CASE 2: Page refresh (reload)
        if (navType === "reload") {
            console.log("Page refresh detected");
            skipLoaderAndLoad();
            return;
        }

        // CASE 3: First-time visit → Do nothing (loader will run)
    });


    function openVendor(vendorId, requestId) {

        $.ajax({
            url: "{{ route('store-user-vendor-view') }}",
            method: "POST",
            data: {
                _token: "{{ csrf_token() }}",
                service_id: vendorId,
                request_id: requestId
            },
            success: function() {
                console.log("User view saved.");
            }
        });
        // Redirect with parameters in query string
        window.location.href = `/vendor/${vendorId}?request_id=${requestId}`;
    }



    (function() {

        // // Detect Back/Forward cached page
        // const navIsBack = performance.getEntriesByType("navigation")[0]?.type === "back_forward";

        // // If page restored from BACK → skip loader
        // if (navIsBack) {
        //     document.getElementById("loaderBox").style.display = "none";
        //     document.getElementById("pageContent").classList.add("visible");
        //     document.body.style.overflow = "";
        //     return;
        // }

        // --- normal loader works ONLY on first load ---
        // const START = {{ $START_SECONDS }};
        // let timeLeft = START;

        // const timerEl = document.getElementById("loaderTimer");
        // const loaderBox = document.getElementById("loaderBox");
        // const pageContent = document.getElementById("pageContent");
        // const unitsEl = document.getElementById("loaderUnits");

        // function updateUnits(n) {
        //     unitsEl.textContent = n === 1 ? "second" : "seconds";
        // }

        // updateUnits(timeLeft);
        // document.body.style.overflow = "hidden";

        // const interval = setInterval(() => {

        //     timeLeft--;
        //     if (timeLeft < 0) timeLeft = 0;

        //     timerEl.textContent = timeLeft;
        //     updateUnits(timeLeft);

        //     if (timeLeft <= 0) {
        //         clearInterval(interval);

        //         loaderBox.classList.add("hidden");
        //         setTimeout(() => loaderBox.style.display = "none", 450);

        //         pageContent.classList.add("visible");
        //         document.body.style.overflow = "";

        //         loadVendorData();
        //     }
        // }, 1000);

    })();
</script>

<script>
    // Detect back/forward navigation
    window.addEventListener("pageshow", function(event) {
        if (event.persisted) {
            // Page loaded from cache → NO LOADER
            document.getElementById("loaderBox").style.display = "none";
            document.getElementById("pageContent").classList.add("visible");
            document.body.style.overflow = "";
        }
    });
</script>

@include('base.footer')
