{% extends "base.html" %}
{% block title %}{{_("Weather")}}{% endblock %}

{% block content %}
<h1>{{_("Weather")}}</h1>
<form action=""
      method="get"
      class="mb-4">
  <div class="input-group mb-3">
    <input type="text"
           class="form-control"
           id="query"
           name="query"
           placeholder="{{_('Enter the city name')}}">
    <button class="btn btn-primary"
            type="submit">{{_("Search")}}</button>
  </div>
</form>
<ul id="locations"
    class="list-group mb-5">
  {% for location in locations %}
  <a href="weather/{{location.id}}"
     class="list-group-item list-group-item-action px-4"
     onclick="saveLocation({id:'{{location.id}}', name:'{{location.name}}'});">
    <span class="fi fi-{{location.country_code}} me-1"></span>
    <span class="text-primary">{{location.name}}</span>
    <span class="small ms-1 text-secondary">
      {{location.country}}, {{location.district}}, {{location.subdistrict}}
    </span>
    <span></span>
  </a>
  {% endfor %}
</ul>
<script>
  (function () {
    document.loadLocations = () => {
      const locations = JSON.parse(window.localStorage.getItem('locations') || '{}');
      const container = document.querySelector('#locations');
      container.innerHTML = '';
      for (const [id, name] of Object.entries(locations)) {
        const element = document.createElement('a');
        element.href = `weather/${id}`;
        element.className = 'list-group-item list-group-item-action px-4 d-flex justify-content-between align-items-start';
        element.innerHTML = `
        <span class="text-primary me-auto">${name}</span>
        <span class="text-danger" onclick="removeLocation('${id}'); event.preventDefault();">&#x2715;</span>
        `;
        container.appendChild(element);
      }
    }

    document.saveLocation = (location) => {
      const locations = JSON.parse(window.localStorage.getItem('locations') || '{}');
      locations[location.id] = location.name;
      window.localStorage.setItem('locations', JSON.stringify(locations));
    }

    document.removeLocation = (id) => {
      const locations = JSON.parse(window.localStorage.getItem('locations') || '{}');
      delete locations[id];
      window.localStorage.setItem('locations', JSON.stringify(locations));
      document.loadLocations();
    }

    const params = new URLSearchParams(window.location.search);
    const searchQuery = params.get('query');
    if (searchQuery) {
      document.querySelector('#query').value = searchQuery;
    } else {
      document.loadLocations();
    }
  })();
</script>
{% endblock %}