const Territory_History = {
    list: [],

    async init() {
        let html = await fetch('/lib/pages/territory/history/index.html').then((response) => response.text());
        app.innerHTML = html;

        this.setHTML()
    },

    async loadAPI(url) {
        const uuid = localStorage.getItem("uuid");

        const response = await fetch(url, {
            method: 'GET',
            headers: {
                "Content-Type": "application/json",
                "Authorization": uuid
            }
        });
        return await response.json();
    },

    async setHTML() {
        const block_list = document.getElementById('list');
        const url = `${CONFIG.api}history/apartments/list?limit=300`;
        let list = this.list.length > 0 ? this.list : await this.loadAPI(url);

        list.sort((a, b) => b.id - a.id);

        let html = "";
        for (const element of list) {
            html += this.renderCard({ element });
        }

        block_list.innerHTML = html;
    },

    renderCard: ({ element }) => {
        const labels = ["", "Відмова (Не цікавить)", "Не заходити (Груба відмова)", "Нема домофона", "Повторна відвідина", "Немає вдома", "Свідки Єгови"];
        const color_status = [
            ["var(--ColorThemes2)", "var(--ColorThemes3)"],
            ["#fbf1e0", "#ff8300"],
            ["#fce3e2", "#ff0000"],
            ["#d7ddec", "#2919bd"],
            ["#d5e9dd", "#11a568"],
            ["#d7ebfa", "#3fb4fc"],
            ["#e8dbf5", "#b381eb"]
        ];

        const [bg, color] = color_status[element.status];
                
        let description = element.description 
            ? `<div class="description"><p>${element.description}</p></div>`
            : ``;

        return `
            <div class="card" style="background:${bg};color:${color};border:1px solid ${color}">
                <div class="info" title="${element.id}">
                    <a href="/territory/card/house/${element.house_id}" class="address">
                        <p title="${element.address.entrance}">${element.address.house.title} ${element.address.house.number}</p>
                    </a>
                    <div class="apartment">
                        <p>кв. ${element.address.apartment}</p>
                    </div>
                    <div class="status">
                        <p>${labels[element.status]}</p>
                    </div>
                    <a href="/sheeps/${element.sheep.id}" class="name">
                        <p>${element.sheep.name ?? "--"}</p>
                    </a>
                    <div class="date">
                        <p>${formattedDateTime(element.created_at)}</p>
                    </div>
                </div>
                ${description}
            </div>
        `;
    },
}