(function () {
    'use strict';

    const config = window.KARVI_DASHBOARD;
    if (!config || !config.apiMode) {
        return;
    }

    const labels = config.labels || {};

    const statsTotal = document.getElementById('dashboardStatTotal');
    const statsPending = document.getElementById('dashboardStatPending');
    const statsSigned = document.getElementById('dashboardStatSigned');
    const apiErrorBanner = document.getElementById('dashboardApiError');
    const apiErrorText = document.getElementById('dashboardApiErrorText');
    const loadingEl = document.getElementById('dashboardContractsLoading');
    const tableWrap = document.getElementById('dashboardContractsTableWrap');
    const tableBody = document.getElementById('dashboardContractsTableBody');
    const mobileWrap = document.getElementById('dashboardContractsMobile');
    const emptyState = document.getElementById('dashboardContractsEmpty');

    function escapeHtml(value) {
        return String(value ?? '')
            .replace(/&/g, '&amp;')
            .replace(/</g, '&lt;')
            .replace(/>/g, '&gt;')
            .replace(/"/g, '&quot;');
    }

    function contractRef(contract) {
        const id = Number(contract.id || 0);
        return 'KP-' + String(id).padStart(5, '0');
    }

    function contractAdminToken(contract) {
        return String((contract && (contract.token || contract.sign_token)) || '');
    }

    function adminDownloadUrl(base, contract) {
        const token = contractAdminToken(contract);
        const id = Number(contract && contract.id) || 0;
        let url = (base || '').replace(/\/$/, '') + '?token=' + encodeURIComponent(token);

        if (id > 0) {
            url += '&id=' + encodeURIComponent(String(id));
        }

        return url;
    }

    function contractUrl(contractOrToken) {
        const signUrlBase = (config.contractSignUrlBase || '').replace(/\/$/, '');
        const contractUrlBase = (config.contractUrlBase || '').replace(/\/$/, '');

        if (contractOrToken && typeof contractOrToken === 'object') {
            const signToken = contractOrToken.sign_token || contractOrToken.token || '';
            if (signToken && signUrlBase) {
                return signUrlBase + '/' + encodeURIComponent(signToken);
            }
            if (contractOrToken.customer_url) {
                const path = String(contractOrToken.customer_url);
                if (path.startsWith('http')) {
                    return path;
                }
                const origin = window.location.origin || '';
                return origin + (path.startsWith('/') ? path : '/' + path);
            }
            return '';
        }

        if (signUrlBase) {
            return signUrlBase + '/' + encodeURIComponent(contractOrToken || '');
        }

        return contractUrlBase + '/' + encodeURIComponent(contractOrToken || '');
    }

    function copyTextToClipboard(text, onSuccess) {
        if (navigator.clipboard && window.isSecureContext) {
            navigator.clipboard.writeText(text).then(onSuccess).catch(function () {
                fallbackCopyText(text, onSuccess);
            });
            return;
        }

        fallbackCopyText(text, onSuccess);
    }

    function fallbackCopyText(text, onSuccess) {
        const textarea = document.createElement('textarea');
        textarea.value = text;
        textarea.setAttribute('readonly', '');
        textarea.style.position = 'fixed';
        textarea.style.left = '-9999px';
        document.body.appendChild(textarea);
        textarea.select();

        try {
            if (document.execCommand('copy')) {
                onSuccess();
            }
        } catch (err) {
            // ignore
        }

        document.body.removeChild(textarea);
    }

    function statusLabel(status) {
        const key = 'status_' + String(status || 'pending').toLowerCase();
        return labels[key] || status || 'pending';
    }

    function formatDate(value) {
        if (!value) {
            return '';
        }

        const normalized = String(value).replace(' ', 'T');
        const date = new Date(normalized);

        if (Number.isNaN(date.getTime())) {
            return String(value);
        }

        return date.toLocaleDateString(undefined, {
            year: 'numeric',
            month: 'short',
            day: 'numeric',
        });
    }

    function setLoading(isLoading) {
        if (loadingEl) {
            loadingEl.classList.toggle('hidden', !isLoading);
        }
    }

    function showApiError(message) {
        if (!apiErrorBanner || !apiErrorText) {
            return;
        }

        if (!message) {
            apiErrorBanner.classList.add('hidden');
            apiErrorText.textContent = '';
            return;
        }

        apiErrorBanner.classList.remove('hidden');
        apiErrorText.textContent = message;
    }

    function updateStats(contracts) {
        const total = contracts.length;
        const signed = contracts.filter(function (contract) {
            return (contract.status || '') === 'signed';
        }).length;
        const pending = total - signed;

        if (statsTotal) {
            statsTotal.textContent = String(total);
        }
        if (statsPending) {
            statsPending.textContent = String(pending);
        }
        if (statsSigned) {
            statsSigned.textContent = String(signed);
        }
    }

    function contractDetailsUrl(contract) {
        const id = Number(contract && contract.id) || 0;
        if (id <= 0) {
            return '';
        }

        const base = (config.contractDetailsUrl || (window.karviPath ? window.karviPath('/admin/contracts') : '/admin/contracts')).replace(/\/$/, '');
        return base + '/' + encodeURIComponent(String(id));
    }

    function contractEditUrl(contract) {
        const id = Number(contract && contract.id) || 0;
        if (id <= 0) {
            return '';
        }

        const base = (config.contractDetailsUrl || (window.karviPath ? window.karviPath('/admin/contracts') : '/admin/contracts')).replace(/\/$/, '');
        return base + '/' + encodeURIComponent(String(id)) + '/edit';
    }

    function downloadButtonsHtml(contract) {
        const token = contractAdminToken(contract);
        if (token === '') {
            return '';
        }

        const status = String(contract.status || 'pending').toLowerCase();
        if (status !== 'signed') {
            return '';
        }

        const pdfUrl = escapeHtml(adminDownloadUrl(config.downloadPdfUrl || (window.karviPath ? window.karviPath('/admin/download') : '/admin/download'), contract));
        const signaturesUrl = escapeHtml(adminDownloadUrl(config.downloadSignaturesUrl || (window.karviPath ? window.karviPath('/admin/download-signatures') : '/admin/download-signatures'), contract));
        const contractLabel = escapeHtml(labels.download_contract || 'Contract');
        const signaturesLabel = escapeHtml(labels.download_signatures || 'Signature');

        return ''
            + '<a href="' + pdfUrl + '" class="btn-secondary !py-1.5 !px-2.5 !text-xs whitespace-nowrap" title="' + contractLabel + '">'
            + '<span class="material-symbols-rounded text-base">download</span>'
            + contractLabel
            + '</a>'
            + '<a href="' + signaturesUrl + '" class="btn-secondary !py-1.5 !px-2.5 !text-xs whitespace-nowrap" title="' + signaturesLabel + '">'
            + '<span class="material-symbols-rounded text-base">download</span>'
            + signaturesLabel
            + '</a>';
    }

    function actionButtonsHtml(contract) {
        const token = escapeHtml(contractAdminToken(contract));
        const ref = escapeHtml(contractRef(contract));
        const url = escapeHtml(contractUrl(contract));
        const detailsUrl = escapeHtml(contractDetailsUrl(contract));
        const editUrl = escapeHtml(contractEditUrl(contract));
        const duplicateUrl = escapeHtml(config.duplicateUrl || '');
        const duplicateConfirm = escapeHtml(labels.duplicate_contract_confirm || 'Create duplicate contract?');
        const detailsLabel = escapeHtml(labels.view_contract_details || 'Details');
        const editLabel = escapeHtml(labels.edit_contract || 'Edit');

        let html = '';
        if (detailsUrl) {
            html += '<a href="' + detailsUrl + '" class="btn-secondary !py-1.5 !px-2.5 !text-xs whitespace-nowrap" title="' + detailsLabel + '">'
                + '<span class="material-symbols-rounded text-base">visibility</span>'
                + detailsLabel
                + '</a>';
        }
        if (editUrl) {
            html += '<a href="' + editUrl + '" class="btn-secondary !py-1.5 !px-2.5 !text-xs whitespace-nowrap" title="' + editLabel + '">'
                + '<span class="material-symbols-rounded text-base">edit</span>'
                + editLabel
                + '</a>';
        }

        return html + downloadButtonsHtml(contract)
            + '<button type="button" class="btn-secondary !py-1.5 !px-2.5 !text-xs whitespace-nowrap copy-row-btn" data-url="' + url + '" title="' + escapeHtml(labels.copy_link || 'Copy link') + '">'
            + '<span class="material-symbols-rounded text-base">content_copy</span>'
            + escapeHtml(labels.copy_link || 'Copy link')
            + '</button>'
            + '<form method="POST" action="' + duplicateUrl + '" class="inline-flex">'
            + '<input type="hidden" name="token" value="' + token + '">'
            + '<input type="hidden" name="id" value="' + escapeHtml(String(contract.id || '')) + '">'
            + '<button type="button" class="btn-secondary !py-1.5 !px-2.5 !text-xs whitespace-nowrap" title="' + escapeHtml(labels.duplicate_contract || 'Duplicate') + '" data-duplicate-contract data-confirm="' + duplicateConfirm + '">'
            + '<span class="material-symbols-rounded text-base">library_add</span>'
            + escapeHtml(labels.duplicate_contract || 'Duplicate')
            + '</button>'
            + '</form>'
            + '<button type="button" class="btn-danger !py-1.5 !px-2.5 !text-xs whitespace-nowrap" title="' + escapeHtml(labels.delete_contract || 'Delete') + '" data-delete-contract data-token="' + token + '" data-id="' + escapeHtml(String(contract.id || '')) + '" data-ref="' + ref + '">'
            + '<span class="material-symbols-rounded text-base">delete</span>'
            + escapeHtml(labels.delete_contract || 'Delete')
            + '</button>';
    }

    function renderContracts(contracts) {
        updateStats(contracts);

        const hasContracts = contracts.length > 0;

        if (emptyState) {
            emptyState.classList.toggle('hidden', hasContracts);
        }
        if (tableWrap) {
            tableWrap.classList.toggle('hidden', !hasContracts);
        }
        if (mobileWrap) {
            mobileWrap.classList.toggle('hidden', !hasContracts);
        }

        if (!hasContracts) {
            if (tableBody) {
                tableBody.innerHTML = '';
            }
            if (mobileWrap) {
                mobileWrap.innerHTML = '';
            }
            return;
        }

        if (tableBody) {
            tableBody.innerHTML = contracts.map(function (contract) {
                const ref = escapeHtml(contractRef(contract));
                const name = escapeHtml(contract.restaurant_name || contract.partner_name || '');
                const email = escapeHtml(contract.partner_email || '');
                const type = escapeHtml(contract.partner_type || contract.partnership_type || '');
                const status = escapeHtml(contract.status || 'pending');
                const statusText = escapeHtml(statusLabel(contract.status || 'pending'));
                const date = escapeHtml(formatDate(contract.created_at));

                return ''
                    + '<tr>'
                    + '<td><a href="' + escapeHtml(contractDetailsUrl(contract)) + '" class="font-mono text-xs font-semibold bg-karvi-100 px-2 py-1 rounded-lg hover:bg-karvi-200">' + ref + '</a></td>'
                    + '<td><div class="font-semibold text-karvi-950">' + name + '</div><div class="text-xs text-karvi-500 mt-0.5">' + email + '</div></td>'
                    + '<td>' + type + '</td>'
                    + '<td><span class="status-badge status-' + status + '">' + statusText + '</span></td>'
                    + '<td class="text-karvi-500 text-sm">' + date + '</td>'
                    + '<td><div class="flex items-center gap-2 flex-wrap">' + actionButtonsHtml(contract) + '</div></td>'
                    + '</tr>';
            }).join('');
        }

        if (mobileWrap) {
            mobileWrap.innerHTML = contracts.map(function (contract) {
                const ref = escapeHtml(contractRef(contract));
                const name = escapeHtml(contract.restaurant_name || contract.partner_name || '');
                const email = escapeHtml(contract.partner_email || '');
                const type = escapeHtml(contract.partner_type || contract.partnership_type || '');
                const status = escapeHtml(contract.status || 'pending');
                const statusText = escapeHtml(statusLabel(contract.status || 'pending'));
                const date = escapeHtml(formatDate(contract.created_at));
                const url = escapeHtml(contractUrl(contract));

                return ''
                    + '<div class="contract-card-mobile">'
                    + '<div class="flex items-start justify-between gap-3 mb-3">'
                    + '<div><span class="font-mono text-xs font-semibold bg-karvi-100 px-2 py-1 rounded-lg">' + ref + '</span>'
                    + '<h3 class="font-semibold text-karvi-950 mt-2">' + name + '</h3>'
                    + '<p class="text-xs text-karvi-500">' + email + '</p></div>'
                    + '<span class="status-badge status-' + status + '">' + statusText + '</span>'
                    + '</div>'
                    + '<div class="flex items-center justify-between text-sm text-karvi-500 mb-4"><span>' + type + '</span><span>' + date + '</span></div>'
                    + '<div class="copy-link-box"><input type="text" readonly value="' + url + '" class="form-input !py-2 !text-xs">'
                    + '<button type="button" class="btn-secondary !py-2 copy-row-btn" data-url="' + url + '">'
                    + '<span class="material-symbols-rounded text-base">content_copy</span>'
                    + escapeHtml(labels.copy_link || 'Copy link')
                    + '</button></div>'
                    + '<div class="grid grid-cols-2 gap-2 mt-3">' + actionButtonsHtml(contract) + '</div>'
                    + '</div>';
            }).join('');
        }

        bindDynamicActions();
    }

    function bindDynamicActions() {
        document.querySelectorAll('.copy-row-btn').forEach(function (button) {
            if (button.dataset.boundCopy === '1') {
                return;
            }
            button.dataset.boundCopy = '1';
            button.addEventListener('click', function () {
                const url = button.getAttribute('data-url');
                if (!url) {
                    return;
                }
                const original = button.innerHTML;
                const i18n = window.KARVI_I18N || {};
                copyTextToClipboard(url, function () {
                    button.innerHTML = '<span class="material-symbols-rounded text-base">check</span> ' + escapeHtml(i18n.copied || 'Copied');
                    setTimeout(function () {
                        button.innerHTML = original;
                    }, 1500);
                });
            });
        });

        document.querySelectorAll('[data-duplicate-contract]').forEach(function (button) {
            if (button.dataset.boundDuplicate === '1') {
                return;
            }
            button.dataset.boundDuplicate = '1';
            button.addEventListener('click', function () {
                const message = button.getAttribute('data-confirm') || 'Create duplicate contract?';
                if (!window.confirm(message)) {
                    return;
                }
                const form = button.closest('form');
                if (form) {
                    form.submit();
                }
            });
        });

        document.querySelectorAll('[data-delete-contract]').forEach(function (button) {
            if (button.dataset.boundDelete === '1') {
                return;
            }
            button.dataset.boundDelete = '1';
            button.addEventListener('click', function () {
                const modal = document.getElementById('deleteContractModal');
                const tokenInput = document.getElementById('deleteContractToken');
                const contractIdInput = document.getElementById('deleteContractId');
                const refLabel = document.getElementById('deleteContractRef');
                const passwordInput = document.getElementById('deleteContractPassword');

                if (tokenInput) {
                    tokenInput.value = button.getAttribute('data-token') || '';
                }
                if (contractIdInput) {
                    contractIdInput.value = button.getAttribute('data-id') || '';
                }
                if (refLabel) {
                    refLabel.textContent = button.getAttribute('data-ref') || '';
                }
                if (passwordInput) {
                    passwordInput.value = '';
                }
                if (modal) {
                    modal.classList.remove('hidden');
                    document.body.classList.add('admin-modal-open');
                    if (passwordInput) {
                        passwordInput.focus();
                    }
                }
            });
        });
    }

    function fetchContractsFromApi() {
        return fetch(config.contractsApiUrl || (window.karviPath ? window.karviPath('/admin/api/contracts') : '/admin/api/contracts'), {
            method: 'GET',
            headers: {
                Accept: 'application/json',
            },
            credentials: 'same-origin',
        }).then(function (response) {
            return response.json().then(function (payload) {
                if (!response.ok || !payload.success) {
                    throw new Error(payload.message || labels.api_error_title || 'Could not load contracts.');
                }
                return payload.contracts || [];
            });
        });
    }

    function syncContracts() {
        setLoading(true);

        return fetchContractsFromApi()
            .then(function (contracts) {
                showApiError('');
                renderContracts(contracts);
            })
            .catch(function (error) {
                showApiError(error.message || labels.api_error_title || 'Could not load contracts.');
                renderContracts([]);
            })
            .finally(function () {
                setLoading(false);
            });
    }

    syncContracts();
})();
