<script lang="ts">
    function encodeRFC3986URIComponent(str) {
        return encodeURIComponent(str).replace(
            /[!'()*]/g,
            (c) => `%${c.charCodeAt(0).toString(16).toUpperCase()}`
        );
    }
    import { http } from "@tauri-apps/api";

    let place = "Unknown, Unknown";
    let temp_c = "";
    let temp_f = "";

    window.addEventListener("maccha-submit", async (event: CustomEventInit) => {
        const query = `https://wttr.in/${encodeRFC3986URIComponent(
            event.detail.substring(4).trim()
        )}?format=j1`;
        console.log(query);
        const res = await http.fetch(query);

        const data = res.data as { [k: string]: any };

        console.log(data);

        place = `${data.nearest_area[0].areaName[0].value}, ${data.nearest_area[0].country[0].value}`;
        temp_c = data.current_condition[0].temp_C;
        temp_f = data.current_condition[0].temp_F;
    });
</script>

<div class="maccha-weather">
    <h1 class="weather-header">{place}</h1>
    <h2 class="temperature-header">{temp_c}°C / {temp_f}°F</h2>
</div>
