{% extends "fellchensammlung/base_bulma.html" %}
{% load i18n %}

{% block title %}<title>{% translate "Suche" %}</title>{% endblock %}

{% block content %}
    {% get_current_language as LANGUAGE_CODE_CURRENT %}
    <div class="columns">
    <div class="column">
        {% include "fellchensammlung/partials/bulma-partial-map.html" %}
    </div>
    <div class="column">
        <form class="block" method="post">
            {% csrf_token %}
            <input type="hidden" name="longitude" maxlength="200" id="longitude">
            <input type="hidden" name="latitude" maxlength="200" id="latitude">
            <input type="hidden" id="place_id" name="place_id">
            <!--- https://docs.djangoproject.com/en/5.2/topics/forms/#reusable-form-templates -->
            {{ search_form }}
            <ul id="results"></ul>
            <button class="button is-primary" type="submit" value="search" name="search">
                <i class="fas fa-search"></i> {% trans 'Suchen' %}
            </button>
            {% if searched %}
                {% if subscribed_search %}
                    <button class="button" type="submit" value="{{ subscribed_search.pk }}"
                            name="unsubscribe_to_search">
                        <i class="fas fa-bell-slash"></i> {% trans 'Suche nicht mehr abonnieren' %}
                    </button>
                {% else %}
                    <button class="button" type="submit" name="subscribe_to_search">
                        <i class="fas fa-bell"></i> {% trans 'Suche abonnieren' %}
                    </button>
                {% endif %}
            {% endif %}
        </form>
        <div class="block">
            {% if place_not_found %}
                <div class="block notification is-warning">
                    <p>
                        {% trans 'Ort nicht gefunden' %}
                    </p>
                </div>
            {% endif %}
        </div>
    </div>
    {% include "fellchensammlung/lists/bulma-list-adoption-notices.html" %}

    <script>
        const locationInput = document.getElementById('id_location_string');
        const resultsList = document.getElementById('results');
        const placeIdInput = document.getElementById('place_id');

        locationInput.addEventListener('input', async function () {
            const query = locationInput.value.trim();

            if (query.length < 3) {
                resultsList.innerHTML = ''; // Don't search for or show results if input is less than 3 characters
                return;
            }

            try {
                const response = await fetch(`{{ geocoding_api_url }}/?q=${encodeURIComponent(query)}&limit=5&lang={{ LANGUAGE_CODE_CURRENT }}`);
                const data = await response.json();

                if (data && data.features) {
                    resultsList.innerHTML = ''; // Clear previous results

                    const locations = data.features.slice(0, 5); // Show only the first 5 results

                    locations.forEach(location => {
                        const listItem = document.createElement('li');
                        listItem.classList.add('result-item');
                        listItem.textContent = geojson_to_summary(location);

                        // Add event when user clicks on a result location
                        listItem.addEventListener('click', () => {

                            locationInput.value = geojson_to_searchable_string(location); // Set input field to selected location
                            resultsList.innerHTML = ''; // Clear the results after selecting a location
                        });

                        resultsList.appendChild(listItem);
                    });
                }
            } catch (error) {
                console.error('Error fetching location data:', error);
                resultsList.innerHTML = '<li class="result-item">Error fetching data. Please try again.</li>';
            }
        });
    </script>
{% endblock %}
