// Location: /pwa/assets/pwa_filters.js
window.PWA_FILTERS = (function () {
    function sanitize(str) {
        return (str || '').toString().toLowerCase();
    }

    function initCustomersPage(data) {
        const container = document.getElementById('pwa-customers-filters');
        const listEl = document.getElementById('pwa-customers-list');
        if (!container || !listEl) return;

        container.innerHTML = `
            <div class="pwa-search-bar">
                <input type="search" id="pwa-customers-search" class="pwa-search-input"
                       placeholder="Search by name or city..." />
            </div>
            <div class="pwa-filter-chips" id="pwa-customers-type-chips"></div>
            <div class="pwa-sort-row">
                <select id="pwa-customers-sort" class="pwa-sort-select">
                    <option value="none">Sort: Default</option>
                    <option value="name_asc">Name A → Z</option>
                    <option value="kw_desc">kW High → Low</option>
                    <option value="kw_asc">kW Low → High</option>
                </select>
            </div>
        `;

        const typeChipsEl = document.getElementById('pwa-customers-type-chips');
        const searchInput = document.getElementById('pwa-customers-search');
        const sortSelect = document.getElementById('pwa-customers-sort');

        const types = ['All', 'Domestic', 'Commercial', 'Factory', 'School', 'Clinic', 'Office', 'Others'];
        types.forEach(t => {
            const btn = document.createElement('button');
            btn.type = 'button';
            btn.className = 'pwa-filter-chip' + (t === 'All' ? ' active' : '');
            btn.dataset.value = t;
            btn.textContent = t;
            typeChipsEl.appendChild(btn);
        });

        const state = {
            search: '',
            type: 'All',
            sort: 'none'
        };

        function applyFilters() {
            let items = (data.customers || []).slice();

            if (state.type !== 'All') {
                items = items.filter(c => c.customer_type === state.type || c.type === state.type);
            }

            if (state.search) {
                const term = sanitize(state.search);
                items = items.filter(c =>
                    sanitize(c.name).includes(term) ||
                    sanitize(c.city).includes(term)
                );
            }

            if (state.sort === 'name_asc') {
                items.sort((a, b) => sanitize(a.name).localeCompare(sanitize(b.name)));
            } else if (state.sort === 'kw_desc') {
                items.sort((a, b) => (b.kw || 0) - (a.kw || 0));
            } else if (state.sort === 'kw_asc') {
                items.sort((a, b) => (a.kw || 0) - (b.kw || 0));
            }

            listEl.innerHTML = items.map(c => {
                const type = c.customer_type || c.type;
                const isDomestic = (type === 'Domestic' || type === 'Home' || type === 'Clinic');
                const badgeClass = isDomestic ? 'pwa-badge-domestic' : 'pwa-badge-commercial';
                const role = document.body.getAttribute('data-role');
                const url = '/pwa/' + role + '/customer_view.php?id=' + encodeURIComponent(c.id);
                return `
                    <a href="${url}" style="text-decoration:none;color:inherit;">
                        <div class="pwa-card">
                            <div class="pwa-card-header">
                                <div>
                                    <strong>${c.name}</strong><br>
                                    <span class="pwa-card-meta">${c.city || ''}</span>
                                </div>
                                <div>
                                    <span class="pwa-badge ${badgeClass}">${type}</span>
                                </div>
                            </div>
                            <div class="pwa-card-meta">
                                Est. Capacity: ${c.kw} kW
                            </div>
                        </div>
                    </a>
                `;
            }).join('');
        }

        typeChipsEl.addEventListener('click', function (e) {
            const btn = e.target.closest('.pwa-filter-chip');
            if (!btn) return;
            typeChipsEl.querySelectorAll('.pwa-filter-chip').forEach(b => b.classList.remove('active'));
            btn.classList.add('active');
            state.type = btn.dataset.value || 'All';
            applyFilters();
        });

        searchInput.addEventListener('input', function () {
            state.search = this.value || '';
            applyFilters();
        });

        sortSelect.addEventListener('change', function () {
            state.sort = this.value || 'none';
            applyFilters();
        });

        applyFilters();
    }

    function initFollowupsPage(data) {
        const container = document.getElementById('pwa-followups-filters');
        const listEl = document.getElementById('pwa-followups-list');
        if (!container || !listEl) return;

        container.innerHTML = `
            <div class="pwa-search-bar">
                <input type="search" id="pwa-followups-search" class="pwa-search-input"
                       placeholder="Search by customer name..." />
            </div>
            <div class="pwa-filter-chips" id="pwa-followups-status-chips"></div>
        `;

        const statusChipsEl = document.getElementById('pwa-followups-status-chips');
        const searchInput = document.getElementById('pwa-followups-search');

        const statuses = ['All', 'Pending', 'Done', 'Overdue'];
        statuses.forEach(s => {
            const btn = document.createElement('button');
            btn.type = 'button';
            btn.className = 'pwa-filter-chip' + (s === 'All' ? ' active' : '');
            btn.dataset.value = s;
            btn.textContent = s;
            statusChipsEl.appendChild(btn);
        });

        const state = {
            search: '',
            status: 'All'
        };

        function applyFilters() {
            let items = (data.followups || []).slice();

            if (state.status !== 'All') {
                items = items.filter(f => (f.status || '') === state.status);
            }

            if (state.search) {
                const term = sanitize(state.search);
                items = items.filter(f =>
                    sanitize(f.customer).includes(term)
                );
            }

            items.sort((a, b) => {
                const order = { 'Overdue': 0, 'Pending': 1, 'Done': 2 };
                return (order[a.status] || 9) - (order[b.status] || 9);
            });

            listEl.innerHTML = items.map(f => {
                let statusClass = 'pwa-status-pending';
                if (f.status === 'Done') statusClass = 'pwa-status-done';
                if (f.status === 'Overdue') statusClass = 'pwa-status-overdue';
                return `
                    <div class="pwa-list-row">
                        <div>
                            <strong>${f.customer}</strong><br>
                            <span class="pwa-card-meta">Last: ${f.last}</span>
                        </div>
                        <div>
                            <span class="pwa-card-meta">Next:</span><br>
                            <strong>${f.next}</strong>
                        </div>
                        <div style="text-align:right;">
                            <span class="pwa-status-chip ${statusClass}">${f.status}</span>
                        </div>
                    </div>
                `;
            }).join('');
        }

        statusChipsEl.addEventListener('click', function (e) {
            const btn = e.target.closest('.pwa-filter-chip');
            if (!btn) return;
            statusChipsEl.querySelectorAll('.pwa-filter-chip').forEach(b => b.classList.remove('active'));
            btn.classList.add('active');
            state.status = btn.dataset.value || 'All';
            applyFilters();
        });

        searchInput.addEventListener('input', function () {
            state.search = this.value || '';
            applyFilters();
        });

        applyFilters();
    }

    function initTasksPage(data) {
        const container = document.getElementById('pwa-tasks-filters');
        const listEl = document.getElementById('pwa-tasks-list');
        if (!container || !listEl) return;

        container.innerHTML = `
            <div class="pwa-search-bar">
                <input type="search" id="pwa-tasks-search" class="pwa-search-input"
                       placeholder="Search tasks..." />
            </div>
            <div class="pwa-filter-chips" id="pwa-tasks-priority-chips"></div>
            <div class="pwa-filter-chips" id="pwa-tasks-status-chips"></div>
        `;

        const priorityChipsEl = document.getElementById('pwa-tasks-priority-chips');
        const statusChipsEl = document.getElementById('pwa-tasks-status-chips');
        const searchInput = document.getElementById('pwa-tasks-search');

        const priorities = ['All', 'Low', 'Medium', 'High', 'Critical'];
        const statuses = ['All', 'Open', 'Done'];

        priorities.forEach(p => {
            const btn = document.createElement('button');
            btn.type = 'button';
            btn.className = 'pwa-filter-chip' + (p === 'All' ? ' active' : '');
            btn.dataset.value = p;
            btn.textContent = p;
            priorityChipsEl.appendChild(btn);
        });

        statuses.forEach(s => {
            const btn = document.createElement('button');
            btn.type = 'button';
            btn.className = 'pwa-filter-chip' + (s === 'All' ? ' active' : '');
            btn.dataset.value = s;
            btn.textContent = s;
            statusChipsEl.appendChild(btn);
        });

        const state = {
            search: '',
            priority: 'All',
            status: 'All'
        };

        function applyFilters() {
            let items = (data.tasks || []).slice();

            if (state.priority !== 'All') {
                items = items.filter(t => (t.priority || '') === state.priority);
            }

            if (state.status !== 'All') {
                items = items.filter(t => (t.status || '') === state.status);
            }

            if (state.search) {
                const term = sanitize(state.search);
                items = items.filter(t =>
                    sanitize(t.title).includes(term)
                );
            }

            listEl.innerHTML = items.map(t => {
                return `
                    <div class="pwa-card">
                        <div class="pwa-card-header">
                            <span>${t.title}</span>
                            <span class="pwa-card-meta">${t.priority} • ${t.status}</span>
                        </div>
                        <div class="pwa-card-meta">
                            Due: ${t.due}
                        </div>
                    </div>
                `;
            }).join('');
        }

        priorityChipsEl.addEventListener('click', function (e) {
            const btn = e.target.closest('.pwa-filter-chip');
            if (!btn) return;
            priorityChipsEl.querySelectorAll('.pwa-filter-chip').forEach(b => b.classList.remove('active'));
            btn.classList.add('active');
            state.priority = btn.dataset.value || 'All';
            applyFilters();
        });

        statusChipsEl.addEventListener('click', function (e) {
            const btn = e.target.closest('.pwa-filter-chip');
            if (!btn) return;
            statusChipsEl.querySelectorAll('.pwa-filter-chip').forEach(b => b.classList.remove('active'));
            btn.classList.add('active');
            state.status = btn.dataset.value || 'All';
            applyFilters();
        });

        searchInput.addEventListener('input', function () {
            state.search = this.value || '';
            applyFilters();
        });

        applyFilters();
    }

    return {
        initCustomersPage,
        initFollowupsPage,
        initTasksPage
    };
})();
