@extends('website.layouts.app')

@section('content')
@php
    $partners = [
        ['id' => 1, 'name' => 'Odel Store', 'category' => 'Shopping', 'address' => 'No. 5, Alexandra Place, Colombo 07', 'discount' => '25% OFF', 'lat' => 6.9147, 'lng' => 79.8637, 'description' => 'Premier fashion and lifestyle department store.'],
        ['id' => 2, 'name' => 'Ministry of Crab', 'category' => 'Dining', 'address' => 'Old Dutch Hospital, Colombo 01', 'discount' => '20% OFF', 'lat' => 6.9344, 'lng' => 79.8528, 'description' => 'World-renowned seafood restaurant in a historic setting.'],
        ['id' => 3, 'name' => 'Spa Ceylon', 'category' => 'Health & Wellness', 'address' => 'Galle Face Hotel, Colombo 03', 'discount' => '30% OFF', 'lat' => 6.9246, 'lng' => 79.8540, 'description' => 'Luxury Ayurveda spa and wellness products.'],
        ['id' => 4, 'name' => 'Hilton Colombo', 'category' => 'Travel', 'address' => '2 Sir Chittampalam A Gardiner Mawatha, Colombo 01', 'discount' => '35% OFF', 'lat' => 6.9319, 'lng' => 79.8578, 'description' => 'Five-star hotel with premium dining and accommodation.'],
        ['id' => 5, 'name' => 'Keells Super', 'category' => 'Shopping', 'address' => 'Union Place, Colombo 02', 'discount' => '15% OFF', 'lat' => 6.9167, 'lng' => 79.8580, 'description' => 'Fresh produce and daily essentials supermarket.'],
        ['id' => 6, 'name' => 'Cargills Food City', 'category' => 'Shopping', 'address' => 'Staple Street, Colombo 02', 'discount' => '10% OFF', 'lat' => 6.9350, 'lng' => 79.8500, 'description' => 'Trusted supermarket chain for all your grocery needs.'],
        ['id' => 8, 'name' => 'Fashion Bug', 'category' => 'Shopping', 'address' => 'Bambalapitiya, Colombo 04', 'discount' => '20% OFF', 'lat' => 6.8920, 'lng' => 79.8570, 'description' => 'Trendy clothing for men, women, and kids.'],
        ['id' => 9, 'name' => 'Barista Coffee', 'category' => 'Dining', 'address' => 'Park Street, Colombo 02', 'discount' => '15% OFF', 'lat' => 6.9140, 'lng' => 79.8560, 'description' => 'Authentic Italian coffee and cafe snacks.'],
        ['id' => 10, 'name' => 'Scope Cinemas', 'category' => 'Entertainment', 'address' => 'Colombo City Centre', 'discount' => '25% OFF', 'lat' => 6.9175, 'lng' => 79.8560, 'description' => 'State-of-the-art movie theater experience.'],
        ['id' => 11, 'name' => 'British Council', 'category' => 'Education', 'address' => 'Alfred House Gardens, Colombo 03', 'discount' => '20% OFF', 'lat' => 6.9050, 'lng' => 79.8550, 'description' => 'English courses and library membership discounts.'],
        ['id' => 12, 'name' => 'Aura Fitness', 'category' => 'Health & Wellness', 'address' => 'Havelock Road, Colombo 05', 'discount' => '30% OFF', 'lat' => 6.8850, 'lng' => 79.8620, 'description' => 'Modern gym and fitness center with expert trainers.'],
    ];

    $categories = [
        ['name' => 'All', 'icon' => null, 'color' => 'text-gray-600 bg-gray-100'],
        ['name' => 'Dining', 'icon' => 'utensils-crossed', 'color' => 'text-orange-600 bg-orange-100'],
        ['name' => 'Travel', 'icon' => 'plane', 'color' => 'text-blue-600 bg-blue-100'],
        ['name' => 'Health & Wellness', 'icon' => 'heart', 'color' => 'text-red-600 bg-red-100'],
        ['name' => 'Shopping', 'icon' => 'shopping-bag', 'color' => 'text-purple-600 bg-purple-100'],
        ['name' => 'Entertainment', 'icon' => 'music', 'color' => 'text-pink-600 bg-pink-100'],
        ['name' => 'Education', 'icon' => 'graduation-cap', 'color' => 'text-green-600 bg-green-100'],
    ];

    $categoryMeta = collect($categories)->keyBy('name');
@endphp

<link
    rel="stylesheet"
    href="https://unpkg.com/leaflet@1.9.4/dist/leaflet.css"
    integrity="sha256-p4NxAoJBhIIN+hmNHrzRCf9tD/miZyoHS5obTRR9BMY="
    crossorigin=""
/>
<link
    rel="stylesheet"
    href="https://unpkg.com/leaflet-routing-machine@3.2.12/dist/leaflet-routing-machine.css"
/>

<style>
    #partnerMap {
        width: 100%;
        height: 100%;
    }

    .line-clamp-2 {
        display: -webkit-box;
        -webkit-line-clamp: 2;
        -webkit-box-orient: vertical;
        overflow: hidden;
    }
</style>

<div class="h-screen flex flex-col bg-cream overflow-hidden">
    <header class="bg-white border-b border-gray-200 px-4 py-3 flex items-center justify-between shadow-sm z-20">
        <div class="flex items-center gap-2">
            <div class="bg-teal-deep text-white p-1.5 rounded-lg">
                <i data-lucide="credit-card" class="h-5 w-5"></i>
            </div>
            <span class="text-xl font-bold font-heading text-teal-deep">
                SaveSmart<span class="text-amber-gold">.lk</span>
            </span>
        </div>
        <a href="{{ route('website.home') }}" class="flex items-center gap-2 text-sm font-medium text-gray-600 hover:text-teal-deep transition-colors">
            <i data-lucide="arrow-left" class="w-4 h-4"></i>
            Back to Home
        </a>
    </header>

    <div class="flex-1 flex overflow-hidden">
        <div class="w-full md:w-[400px] bg-cream flex flex-col border-r border-gray-200 shadow-xl z-10 relative">
            <div class="p-4 bg-white border-b border-gray-100">
                <div class="relative">
                    <i data-lucide="search" class="absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-400 w-5 h-5"></i>
                    <input
                        id="partnerSearch"
                        type="text"
                        placeholder="Search Colombo partners or locations..."
                        class="w-full pl-10 pr-10 py-3 bg-gray-50 border border-gray-200 rounded-xl focus:outline-none focus:ring-2 focus:ring-teal-deep/20 focus:border-teal-deep transition-all"
                    >
                    <button id="clearSearch" type="button" class="hidden absolute right-3 top-1/2 transform -translate-y-1/2 text-gray-400 hover:text-gray-600">
                        <i data-lucide="x" class="w-4 h-4"></i>
                    </button>
                </div>
            </div>

            <div class="p-4 bg-white border-b border-gray-100 space-y-3">
                <p class="text-xs font-semibold text-gray-500 uppercase tracking-wider">Directions</p>
                <div class="grid grid-cols-1 gap-2">
                    <input
                        id="directionFrom"
                        type="text"
                        placeholder="From (e.g., Malabe)"
                        class="w-full px-3 py-2.5 bg-gray-50 border border-gray-200 rounded-xl focus:outline-none focus:ring-2 focus:ring-teal-deep/20 focus:border-teal-deep transition-all text-sm"
                    >
                    <input
                        id="directionTo"
                        type="text"
                        placeholder="To (e.g., Kotuwa/Fort)"
                        class="w-full px-3 py-2.5 bg-gray-50 border border-gray-200 rounded-xl focus:outline-none focus:ring-2 focus:ring-teal-deep/20 focus:border-teal-deep transition-all text-sm"
                    >
                </div>
                <div class="flex gap-2">
                    <button id="directionSearchBtn" type="button" class="flex-1 bg-teal-deep text-white text-sm font-semibold rounded-xl py-2.5 hover:bg-teal-dark transition-colors">Find Route</button>
                    <button id="directionClearBtn" type="button" class="px-3 rounded-xl border border-gray-200 text-gray-600 text-sm font-semibold hover:bg-gray-50">Clear</button>
                </div>
                <p id="directionStatus" class="text-xs text-gray-500"></p>
            </div>

            <div class="px-4 py-3 bg-white border-b border-gray-100">
                <div class="relative">
                    <button id="categoryScrollLeft" type="button" class="hidden md:flex absolute left-0 top-1/2 -translate-y-1/2 z-10 w-8 h-8 items-center justify-center rounded-full border border-gray-200 bg-white text-gray-600 shadow-sm hover:text-teal-deep">
                        <i data-lucide="chevron-left" class="w-4 h-4"></i>
                    </button>

                    <div id="categoryScrollArea" class="overflow-x-auto no-scrollbar md:px-10">
                        <div id="categoryFilters" class="flex gap-2 min-w-max">
                            @foreach ($categories as $category)
                                <button
                                    type="button"
                                    data-category="{{ $category['name'] }}"
                                    class="category-filter flex items-center gap-2 px-4 py-2 rounded-full text-sm font-medium transition-all {{ $loop->first ? 'bg-teal-deep text-white shadow-md' : 'bg-white text-gray-600 border border-gray-200 hover:bg-gray-50' }}"
                                >
                                    @if ($category['icon'])
                                        <i data-lucide="{{ $category['icon'] }}" class="w-4 h-4"></i>
                                    @endif
                                    {{ $category['name'] }}
                                </button>
                            @endforeach
                        </div>
                    </div>

                    <button id="categoryScrollRight" type="button" class="hidden md:flex absolute right-0 top-1/2 -translate-y-1/2 z-10 w-8 h-8 items-center justify-center rounded-full border border-gray-200 bg-white text-gray-600 shadow-sm hover:text-teal-deep">
                        <i data-lucide="chevron-right" class="w-4 h-4"></i>
                    </button>
                </div>
            </div>

            <div id="resultsCount" class="px-4 py-2 bg-gray-50 text-xs font-semibold text-gray-500 uppercase tracking-wider border-b border-gray-200">
                Showing {{ count($partners) }} partners
            </div>

            <div id="partnersList" class="flex-1 overflow-y-auto p-4 space-y-4">
                @foreach ($partners as $partner)
                    @php
                        $meta = $categoryMeta[$partner['category']] ?? ['icon' => 'map-pin', 'color' => 'text-gray-600 bg-gray-100'];
                    @endphp
                    <div
                        data-partner-id="{{ $partner['id'] }}"
                        data-name="{{ strtolower($partner['name']) }}"
                        data-address="{{ strtolower($partner['address']) }}"
                        data-category="{{ $partner['category'] }}"
                        class="partner-card bg-white rounded-xl p-4 border border-gray-100 transition-all cursor-pointer hover:shadow-md hover:border-gray-300"
                    >
                        <div class="flex justify-between items-start mb-2">
                            <div class="flex items-center gap-3">
                                <div class="w-10 h-10 rounded-full flex items-center justify-center {{ $meta['color'] }}">
                                    <i data-lucide="{{ $meta['icon'] ?? 'map-pin' }}" class="w-5 h-5"></i>
                                </div>
                                <div>
                                    <h3 class="font-bold text-gray-900 leading-tight">{{ $partner['name'] }}</h3>
                                    <p class="text-xs text-gray-500 font-medium">{{ $partner['category'] }}</p>
                                </div>
                            </div>
                            <span class="bg-amber-gold text-white text-xs font-bold px-2 py-1 rounded">{{ $partner['discount'] }}</span>
                        </div>
                        <p class="text-sm text-gray-600 mb-2 line-clamp-2">{{ $partner['description'] }}</p>
                        <div class="flex items-center gap-1 text-xs text-gray-400">
                            <i data-lucide="map-pin" class="w-3 h-3"></i>{{ $partner['address'] }}
                        </div>
                    </div>
                @endforeach

                <div id="noResults" class="hidden text-center py-12 text-gray-500">
                    <p>No partners found matching your search.</p>
                </div>
            </div>
        </div>

        <div class="flex-1 bg-gray-100 relative z-0">
            <div id="partnerMap"></div>
        </div>
    </div>
</div>
@endsection

@push('scripts')
<script src="https://unpkg.com/leaflet@1.9.4/dist/leaflet.js" integrity="sha256-20nQCchB9co0qIjJZRGuk2/Z9VM+kNiyxNV1lvTlZBo=" crossorigin=""></script>
<script src="https://unpkg.com/leaflet-routing-machine@3.2.12/dist/leaflet-routing-machine.min.js"></script>
<script>
    (function () {
        const PARTNERS = @json($partners);

        const categoryFiltersEl = document.getElementById('categoryFilters');
        const partnersListEl = document.getElementById('partnersList');
        const resultsCountEl = document.getElementById('resultsCount');
        const searchEl = document.getElementById('partnerSearch');
        const clearSearchEl = document.getElementById('clearSearch');
        const categoryScrollArea = document.getElementById('categoryScrollArea');
        const categoryScrollLeft = document.getElementById('categoryScrollLeft');
        const categoryScrollRight = document.getElementById('categoryScrollRight');
        const directionFromEl = document.getElementById('directionFrom');
        const directionToEl = document.getElementById('directionTo');
        const directionSearchBtn = document.getElementById('directionSearchBtn');
        const directionClearBtn = document.getElementById('directionClearBtn');
        const directionStatusEl = document.getElementById('directionStatus');
        const noResultsEl = document.getElementById('noResults');
        const allCards = Array.from(document.querySelectorAll('.partner-card'));
        const filterButtons = Array.from(document.querySelectorAll('.category-filter'));

        let searchQuery = '';
        let activeCategory = 'All';
        let selectedPartnerId = null;
        let routePartnerIds = null;
        let routingControl = null;

        // Wider Colombo city area bounds (for free navigation inside Colombo)
        const colomboBounds = [[6.78, 79.82], [6.99, 79.97]];

        const map = L.map('partnerMap', {
            zoomControl: true,
            minZoom: 11,
            maxZoom: 18,
            maxBounds: colomboBounds,
            maxBoundsViscosity: 0.9,
        }).fitBounds(colomboBounds);

        L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
            attribution: '&copy; OpenStreetMap contributors',
            noWrap: true,
        }).addTo(map);

        const markerLayer = L.layerGroup().addTo(map);

        const redIcon = L.icon({
            iconUrl: 'https://raw.githubusercontent.com/pointhi/leaflet-color-markers/master/img/marker-icon-red.png',
            shadowUrl: 'https://cdnjs.cloudflare.com/ajax/libs/leaflet/1.9.4/images/marker-shadow.png',
            iconSize: [25, 41],
            iconAnchor: [12, 41],
            popupAnchor: [1, -34],
        });

        function getFilteredPartners() {
            return PARTNERS.filter(function (partner) {
                const matchesSearch = partner.name.toLowerCase().includes(searchQuery.toLowerCase()) || partner.address.toLowerCase().includes(searchQuery.toLowerCase());
                const matchesCategory = activeCategory === 'All' || partner.category === activeCategory;
                const matchesRoute = !routePartnerIds || routePartnerIds.has(partner.id);
                return matchesSearch && matchesCategory && matchesRoute;
            });
        }

        function distancePointToSegment(point, segmentStart, segmentEnd) {
            const toRad = Math.PI / 180;
            const latToKm = 111;
            const lngToKm = 111 * Math.cos(point.lat * toRad);

            const px = point.lng * lngToKm;
            const py = point.lat * latToKm;
            const x1 = segmentStart.lng * lngToKm;
            const y1 = segmentStart.lat * latToKm;
            const x2 = segmentEnd.lng * lngToKm;
            const y2 = segmentEnd.lat * latToKm;

            const dx = x2 - x1;
            const dy = y2 - y1;
            const lengthSquared = dx * dx + dy * dy;

            if (lengthSquared === 0) {
                return Math.hypot(px - x1, py - y1);
            }

            let t = ((px - x1) * dx + (py - y1) * dy) / lengthSquared;
            t = Math.max(0, Math.min(1, t));

            const nearestX = x1 + t * dx;
            const nearestY = y1 + t * dy;

            return Math.hypot(px - nearestX, py - nearestY);
        }

        function getPartnersNearRoute(routeCoords, thresholdKm) {
            const partnerIds = new Set();

            PARTNERS.forEach(function (partner) {
                const point = { lat: partner.lat, lng: partner.lng };
                let minDistance = Infinity;

                for (let i = 0; i < routeCoords.length - 1; i += 1) {
                    const distance = distancePointToSegment(point, routeCoords[i], routeCoords[i + 1]);
                    if (distance < minDistance) {
                        minDistance = distance;
                    }
                }

                if (minDistance <= thresholdKm) {
                    partnerIds.add(partner.id);
                }
            });

            return partnerIds;
        }

        function clearDirectionRoute() {
            if (routingControl) {
                map.removeControl(routingControl);
                routingControl = null;
            }

            routePartnerIds = null;

            if (directionStatusEl) {
                directionStatusEl.textContent = '';
            }

            renderAll();
        }

        async function geocodePlace(query) {
            const endpoint = 'https://nominatim.openstreetmap.org/search?format=jsonv2&limit=1&countrycodes=lk&q=' + encodeURIComponent(query + ', Colombo');
            const response = await fetch(endpoint, {
                headers: {
                    'Accept': 'application/json',
                },
            });

            if (!response.ok) {
                throw new Error('Unable to fetch location.');
            }

            const data = await response.json();

            if (!data.length) {
                throw new Error('Location not found inside Colombo.');
            }

            return L.latLng(Number(data[0].lat), Number(data[0].lon));
        }

        async function findDirectionRoute() {
            const from = directionFromEl ? directionFromEl.value.trim() : '';
            const to = directionToEl ? directionToEl.value.trim() : '';

            if (!from || !to) {
                if (directionStatusEl) {
                    directionStatusEl.textContent = 'Please enter both start and destination locations.';
                }
                return;
            }

            if (directionStatusEl) {
                directionStatusEl.textContent = 'Finding route...';
            }

            try {
                const fromPoint = await geocodePlace(from);
                const toPoint = await geocodePlace(to);

                if (routingControl) {
                    map.removeControl(routingControl);
                }

                routingControl = L.Routing.control({
                    waypoints: [fromPoint, toPoint],
                    routeWhileDragging: false,
                    addWaypoints: false,
                    draggableWaypoints: false,
                    show: false,
                    fitSelectedRoutes: true,
                    lineOptions: {
                        styles: [{ color: '#0D4F4F', weight: 5, opacity: 0.9 }],
                    },
                    createMarker: function () {
                        return null;
                    },
                }).addTo(map);

                routingControl.on('routesfound', function (event) {
                    const route = event.routes[0];
                    const coords = route.coordinates.map(function (point) {
                        return { lat: point.lat, lng: point.lng };
                    });

                    routePartnerIds = getPartnersNearRoute(coords, 1.2);
                    renderAll();

                    if (directionStatusEl) {
                        directionStatusEl.textContent = 'Route found. Showing partner markers along this route.';
                    }
                });

                routingControl.on('routingerror', function () {
                    routePartnerIds = null;
                    renderAll();
                    if (directionStatusEl) {
                        directionStatusEl.textContent = 'Route not found. Try different Colombo locations.';
                    }
                });
            } catch (error) {
                routePartnerIds = null;
                renderAll();

                if (directionStatusEl) {
                    directionStatusEl.textContent = error && error.message ? error.message : 'Unable to find direction route.';
                }
            }
        }

        function updateCategoryState() {
            filterButtons.forEach(function (button) {
                const isActive = button.getAttribute('data-category') === activeCategory;
                button.classList.toggle('bg-teal-deep', isActive);
                button.classList.toggle('text-white', isActive);
                button.classList.toggle('shadow-md', isActive);
                button.classList.toggle('bg-white', !isActive);
                button.classList.toggle('text-gray-600', !isActive);
                button.classList.toggle('border', !isActive);
                button.classList.toggle('border-gray-200', !isActive);
                button.classList.toggle('hover:bg-gray-50', !isActive);
            });
        }

        function renderPartners(partners) {
            const partnerIds = new Set(partners.map(function (partner) {
                return partner.id;
            }));

            allCards.forEach(function (card) {
                const cardId = Number(card.getAttribute('data-partner-id'));
                const visible = partnerIds.has(cardId);
                card.classList.toggle('hidden', !visible);

                const isSelected = selectedPartnerId === cardId;
                card.classList.toggle('border-amber-gold', isSelected);
                card.classList.toggle('ring-1', isSelected);
                card.classList.toggle('ring-amber-gold', isSelected);
                card.classList.toggle('shadow-md', isSelected);
                card.classList.toggle('border-gray-100', !isSelected);
                card.classList.toggle('hover:border-gray-300', !isSelected);
            });

            if (noResultsEl) {
                noResultsEl.classList.toggle('hidden', partners.length !== 0);
            }
        }

        function renderMarkers(partners) {
            markerLayer.clearLayers();

            partners.forEach(function (partner) {
                const marker = L.marker([partner.lat, partner.lng], { icon: redIcon });
                marker.bindPopup(
                    '<div class="p-1 min-w-[200px]">' +
                        '<h3 class="font-bold text-teal-deep text-lg mb-1">' + partner.name + '</h3>' +
                        '<p class="text-sm text-gray-600 mb-2">' + partner.category + '</p>' +
                        '<div class="inline-block bg-amber-gold text-white text-xs font-bold px-2 py-1 rounded mb-2">' + partner.discount + '</div>' +
                        '<p class="text-xs text-gray-500">' + partner.address + '</p>' +
                    '</div>'
                );

                marker.on('click', function () {
                    selectedPartnerId = partner.id;
                    renderAll();
                });

                marker.addTo(markerLayer);
            });
        }

        function renderAll() {
            const filteredPartners = getFilteredPartners();
            resultsCountEl.textContent = 'Showing ' + filteredPartners.length + ' partners';
            updateCategoryState();
            renderPartners(filteredPartners);
            renderMarkers(filteredPartners);

            if (clearSearchEl) {
                clearSearchEl.classList.toggle('hidden', !searchQuery);
            }

            if (window.lucide) {
                window.lucide.createIcons();
            }
        }

        filterButtons.forEach(function (button) {
            button.addEventListener('click', function () {
                activeCategory = button.getAttribute('data-category') || 'All';
                renderAll();
            });
        });

        allCards.forEach(function (card) {
            card.addEventListener('click', function () {
                selectedPartnerId = Number(card.getAttribute('data-partner-id'));
                const selectedPartner = PARTNERS.find(function (partner) {
                    return partner.id === selectedPartnerId;
                });

                if (selectedPartner) {
                    map.flyTo([selectedPartner.lat, selectedPartner.lng], 15, { duration: 1.5 });
                }

                renderAll();
            });
        });

        if (searchEl) {
            searchEl.addEventListener('input', function (event) {
                searchQuery = event.target.value || '';
                renderAll();
            });
        }

        if (clearSearchEl) {
            clearSearchEl.addEventListener('click', function () {
                searchQuery = '';
                if (searchEl) {
                    searchEl.value = '';
                    searchEl.focus();
                }
                renderAll();
            });
        }

        if (categoryScrollArea && categoryScrollLeft && categoryScrollRight) {
            categoryScrollLeft.addEventListener('click', function () {
                categoryScrollArea.scrollBy({ left: -180, behavior: 'smooth' });
            });

            categoryScrollRight.addEventListener('click', function () {
                categoryScrollArea.scrollBy({ left: 180, behavior: 'smooth' });
            });
        }

        if (directionSearchBtn) {
            directionSearchBtn.addEventListener('click', findDirectionRoute);
        }

        if (directionClearBtn) {
            directionClearBtn.addEventListener('click', function () {
                if (directionFromEl) {
                    directionFromEl.value = '';
                }

                if (directionToEl) {
                    directionToEl.value = '';
                }

                clearDirectionRoute();
                map.fitBounds(colomboBounds);
            });
        }

        renderAll();
    })();
</script>
@endpush
