<!DOCTYPE html>
<html>
<head>
    <link rel="manifest" href="/manifest.json">
    <link rel='stylesheet' href='/stylesheets/homepage/index.css'/>
    <%- include('./partials/base'); %>
    <script src="/javascripts/local-storage.js"></script>
    <script>
        getUserId();
    </script>
</head>
<body>
<%- include('./partials/header', { title: 'Homepage',visibility:'visible' }); %>

<!-- Plant Carousel -->
<div id="plantCarousel" class="carousel slide p-3 p-md-5 m-md-3 bg-light rounded" data-ride="carousel">
    <div class="carousel-indicators">
        <button type="button" data-bs-target="#plantCarousel" data-bs-slide-to="0" class="active" aria-current="true"
                aria-label="Slide 1"></button>
        <button type="button" data-bs-target="#plantCarousel" data-bs-slide-to="1" aria-label="Slide 2"></button>
        <button type="button" data-bs-target="#plantCarousel" data-bs-slide-to="2" aria-label="Slide 3"></button>
    </div>

    <div class="carousel-inner">

    </div>

</div>
<button class="carousel-control-prev" type="button" data-bs-target="#plantCarousel" data-bs-slide="prev"
        style="margin-right: 2%">
    <span class="carousel-control-prev-icon" aria-hidden="true"></span>
    <span class="visually-hidden">Previous</span>
</button>
<button class="carousel-control-next" type="button" data-bs-target="#plantCarousel" data-bs-slide="next">
    <span class="carousel-control-next-icon" aria-hidden="true"></span>
    <span class="visually-hidden">Next</span>
</button>

<!-- Marketing Banner -->
<div class="card" style="width: 100%;">
    <div class="card-body" style="background-color: #eaf3d8;color: #575757">
        <div class="row text-center">
            <div class="col-12">
                <h3>Discover, Learn, Connect</h3>
            </div>
        </div>
        <div class="row">
            <div class="col-6 d-flex align-items-center ">
                <div class="text-center">
                    <i class="fa-sharp fa-solid fa-plus"></i>

                    <h2>Add Plants</h2>
                </div>
            </div>
            <div class="col-6 d-flex align-items-center">
                <div class="text-center">
                    <i class="fa-solid fa-comment"></i>
                    <h2>Real-time chat</h2>
                </div>
            </div>
        </div>
        <div class="row">
            <div class="col-6">

                <p>Add new plants to your collection with ease</p>
            </div>
            <div class="col-6">
                <p>Engage in real-time chat about specific plants</p>
            </div>
        </div>
        <div class="row">
            <div class="col-6 d-flex align-items-center">
                <div class="text-center">
                    <i class="fa-solid fa-circle-info"></i>
                    <h2>Interactive Plant Catalog</h2>
                </div>
            </div>
            <div class="col-6 d-flex align-items-center">
                <div class="text-center">
                    <i class="fa-solid fa-circle-info"></i>
                    <h2>Filter Plants</h2>
                </div>
            </div>
        </div>
        <div class="row">
            <div class="col-6">
                <p>Interactive catalog of plants with detailed information, images, and categorization to engage users
                    and help them explore different plant options easily.</p>
            </div>

            <div class="col-6">
                <p>Filter plants according to specific criteria</p>
            </div>
        </div>

    </div>

    <!-- Filter and Plants Listing -->
    <div class="row">
        <div class="col-4 d-flex ">
            <div class="min-vh-50 mt-4 w-50 m-auto">
                <div class="input-group">
                    <label class="input-group-text" for="filterSelect"><i class="fa-solid fa-filter"></i></label>
                    <select class="form-select" aria-label="Filter select" id="filterSelect">
                        <option disabled hidden selected><i class="bi bi-funnel"></i> Filter Plants By..</option>
                        <option value="all" selected>Show All</option>
                        <option value="withFlowers">Flowers</option>
                        <option value="withoutFlowers">Without Flowers</option>
                        <option value="withFruits">Fruits</option>
                        <option value="withoutFruits">Without Fruits</option>
                        <option value="withLeaves">Leaves</option>
                        <option value="withoutLeaves">Without Leaves</option>
                    </select>
                </div>
            </div>
        </div>
        <div class="col-4 d-flex">
            <div class="input-group ms-1 border rounded-2 w-20" style="margin-top: 5%; width: 100%; height: 60%;">
        <span class="input-group-text" id="search-icon">
            <i class="fa fa-search"></i>
        </span>
                <input class="form-control" id="searchbox" type="search" placeholder="Search for a Plant"
                       aria-label="Search" style="border-color: #3C1414;">
            </div>
        </div>
        <div class="col-4 d-flex ">
            <div class="min-vh-50 mt-4 w-50 m-auto">
                <div class="input-group mt-2">
                    <label class="input-group-text" for="sortBy"><i class="fa-solid fa-sort"></i></label>
                    <select class="form-select" aria-label="Sort select" id="sortBy">
                        <option disabled hidden selected>Sort by Date & Time...</option>
                        <option value="dateAsc">Date & Time (Ascending)</option>
                        <option value="dateDesc">Date & Time (Descending)</option>
                        <option value="distanceAsc">Distance (Ascending)</option>
                        <option value="distanceDesc">Distance (Descending)</option>
                    </select>
                </div>
            </div>
        </div>
    </div>
    <div class="row " style="margin-top: 1%;margin-left: 1%;margin-right: 1%" id="plant_list">

    </div>


    <!--    Pagination Logic-->
    <nav aria-label="Page navigation">
        <ul class="pagination justify-content-center">
            <% if (currentPage > 1) { %>
                <li class="page-item">
                    <a class="page-link" href="/?page=<%= currentPage - 1 %>" aria-label="Previous">
                        <span aria-hidden="true">&laquo;</span>
                        <span class="visually-hidden">Previous</span>
                    </a>
                </li>
            <% } %>
            <% for (let i = 1; i <= totalPages; i++) { %>
                <li class="page-item <%= i === currentPage ? 'active' : '' %>">
                    <a class="page-link" href="/?page=<%= i %>"><%= i %></a>
                </li>
            <% } %>
            <% if (currentPage < totalPages) { %>
                <li class="page-item">
                    <a class="page-link" href="/?page=<%= currentPage + 1 %>" aria-label="Next">
                        <span aria-hidden="true">&raquo;</span>
                        <span class="visually-hidden">Next</span>
                    </a>
                </li>
            <% } %>
        </ul>
    </nav>

    <%- include('./partials/footer'); %>

    <script src="/javascripts/sightings.js"></script>
    <script src="/javascripts/index.js"></script>
    <script src="/javascripts/idb-utility.js"></script>

    <script>

        // Helper Function for Sort By Distance Filter
        function calculateDistance(lat1, lon1, lat2, lon2) {
            const R = 6371; // Radius of the earth in km
            const dLat = deg2rad(lat2 - lat1);
            const dLon = deg2rad(lon2 - lon1);
            const a =
                Math.sin(dLat / 2) * Math.sin(dLat / 2) +
                Math.cos(deg2rad(lat1)) * Math.cos(deg2rad(lat2)) *
                Math.sin(dLon / 2) * Math.sin(dLon / 2);
            const c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
            const distance = R * c;
            return distance;
        }

        //Degree To Radians Conversion
        function deg2rad(deg) {
            return deg * (Math.PI / 180);
        }


        //Sorting Logic
        document.getElementById('sortBy').addEventListener('change', function () {
            const sortBy = this.value;
            let plantCards = Array.from(document.querySelectorAll('.plant_list'));

            function parseDateString(dateString) {
                const [datePart, timePart] = dateString.split(', ');
                const [day, month, year] = datePart.split('/');
                const [hours, minutes, seconds] = timePart.split(':');
                return new Date(year, month - 1, day, hours, minutes, seconds);
            }

            //By Date Ascending
            if (sortBy === 'dateAsc') {
                plantCards.sort(function (a, b) {
                    const dateA = parseDateString(a.getAttribute('data-date-time'));
                    const dateB = parseDateString(b.getAttribute('data-date-time'));
                    return dateA - dateB;
                });
            }
            //By Date Descending
            else if (sortBy === 'dateDesc') {
                plantCards.sort(function (a, b) {
                    const dateA = parseDateString(a.getAttribute('data-date-time'));
                    const dateB = parseDateString(b.getAttribute('data-date-time'));
                    return dateB - dateA;
                });
            }
            //By Distance Ascending
            else if (sortBy === 'distanceAsc') {
                // Get user's current location
                navigator.geolocation.getCurrentPosition(function (position) {
                    const userLatitude = position.coords.latitude;
                    const userLongitude = position.coords.longitude;

                    plantCards.sort(function (a, b) {
                        const plantALocation = a.getAttribute('data-location').split(',');
                        const plantBLocation = b.getAttribute('data-location').split(',');
                        const plantALatitude = parseFloat(plantALocation[0]);
                        const plantALongitude = parseFloat(plantALocation[1]);
                        const plantBLatitude = parseFloat(plantBLocation[0]);
                        const plantBLongitude = parseFloat(plantBLocation[1]);

                        const distanceA = calculateDistance(userLatitude, userLongitude, plantALatitude, plantALongitude);
                        const distanceB = calculateDistance(userLatitude, userLongitude, plantBLatitude, plantBLongitude);

                        return distanceA - distanceB;
                    });

                    const plantList = document.getElementById('plant_list');
                    plantList.innerHTML = '';
                    plantCards.forEach(function (card) {
                        plantList.appendChild(card);
                    });
                });
                return;
            }
            //By Distance Descending
            else if (sortBy === 'distanceDesc') {
                // Get user's current location
                navigator.geolocation.getCurrentPosition(function (position) {
                    const userLat = position.coords.latitude;
                    const userLon = position.coords.longitude;

                    plantCards.sort(function (a, b) {
                        const plantALocation = a.getAttribute('data-location').split(',');
                        const plantBLocation = b.getAttribute('data-location').split(',');
                        const plantALat = parseFloat(plantALocation[0]);
                        const plantALon = parseFloat(plantALocation[1]);
                        const plantBLat = parseFloat(plantBLocation[0]);
                        const plantBLon = parseFloat(plantBLocation[1]);

                        const distanceA = calculateDistance(userLat, userLon, plantALat, plantALon);
                        const distanceB = calculateDistance(userLat, userLon, plantBLat, plantBLon);

                        return distanceB - distanceA;
                    });

                    const plantList = document.getElementById('plant_list');
                    plantList.innerHTML = '';
                    plantCards.forEach(function (card) {
                        plantList.appendChild(card);
                    });
                });
                return;
            }

            // Update the display with the sorted list
            const plantList = document.getElementById('plant_list');
            plantList.innerHTML = '';
            plantCards.forEach(function (card) {
                plantList.appendChild(card);
            });
        });

        //Search Functionality
        document.getElementById('searchbox').addEventListener('input', function () {
            const query = this.value.toLowerCase();
            const plantCards = document.querySelectorAll('.plant_list');

            plantCards.forEach(function (card) {
                const plantName = card.getAttribute("plant-name").toLowerCase();
                // Check if the plant name contains the search query
                if (plantName.includes(query.toLowerCase())) {
                    card.style.display = 'block';
                } else {
                    card.style.display = 'none';
                }
            });
        });


        //Filter Logic
        document.getElementById('filterSelect').addEventListener('change', function () {
            let filterValue = this.value;
            sessionStorage.setItem('plantFilter', filterValue);
            let plantCards = document.querySelectorAll('.plant_list');
            plantCards.forEach(function (card) {
                if (filterValue === 'all') {
                    card.style.display = 'block';
                } else if (filterValue === 'withFlowers' && card.getAttribute("data-has-flowers") === 'true') {
                    card.style.display = 'block';
                } else if (filterValue === 'withoutFlowers' && card.getAttribute("data-has-flowers") === 'false') {
                    card.style.display = 'block';
                } else if (filterValue === 'withFruits' && card.getAttribute("data-has-fruits") === 'true') {
                    card.style.display = 'block';
                } else if (filterValue === 'withoutFruits' && card.getAttribute("data-has-fruits") === 'false') {
                    card.style.display = 'block';
                } else if (filterValue === 'withLeaves' && card.getAttribute("data-has-leaves") === 'true') {
                    card.style.display = 'block';
                } else if (filterValue === 'withoutLeaves' && card.getAttribute("data-has-leaves") === 'false') {
                    card.style.display = 'block';
                } else {
                    card.style.display = 'none';
                }
            });
        });


        window.addEventListener('load', function () {
            let filterValue = sessionStorage.getItem('plantFilter');
            if (filterValue) {
                document.getElementById('filterSelect').value = filterValue;
                document.getElementById('filterSelect').dispatchEvent(new Event('change'));
            }
        });


    </script>

</div>
</body>
</html>
