(function () {
    'use strict';

    var state = { range: null, data: null, loading: false, mutating: false };

    function $(id) {
        return document.getElementById(id);
    }
    function t(key, fallback) {
        return window.HyAppI18n && window.HyAppI18n.t
            ? window.HyAppI18n.t(key, fallback)
            : fallback || key;
    }
    function toast(message) {
        if (window.HyAppToast) window.HyAppToast.show(message);
    }
    function count(value) {
        return Number.isFinite(value)
            ? Number(value).toLocaleString(undefined, {
                  maximumFractionDigits: 0,
              })
            : '—';
    }
    function dateTime(value) {
        return Number(value)
            ? new Date(Number(value)).toLocaleString(undefined, {
                  year: 'numeric',
                  month: '2-digit',
                  day: '2-digit',
                  hour: '2-digit',
                  minute: '2-digit',
              })
            : '—';
    }

    function renderProfile() {
        if (!state.data) return;
        var profile = state.data.profile || {};
        $('profileName').textContent = profile.name || '—';
        $('profileUID').textContent =
            t('fami_common.uid_prefix', 'UID:') +
            ' ' +
            (profile.displayUserId || profile.userId || '—');
        $('profileInitial').textContent = String(profile.name || 'B')
            .trim()
            .charAt(0)
            .toUpperCase();
        $('profileAvatar').hidden = !profile.avatar;
        $('profileInitial').hidden = !!profile.avatar;
        if (profile.avatar) $('profileAvatar').src = profile.avatar;
        $('contactValue').textContent = profile.contact || '—';
    }

    function agencyAvatar(item) {
        var shell = document.createElement('span');
        shell.className = 'agency-avatar';
        if (item.avatar) {
            var image = document.createElement('img');
            image.src = item.avatar;
            image.alt = '';
            shell.appendChild(image);
        } else {
            shell.textContent = String(item.name || 'A')
                .charAt(0)
                .toUpperCase();
        }
        return shell;
    }

    function textCell(row, value) {
        var cell = document.createElement('td');
        cell.textContent = value;
        row.appendChild(cell);
    }

    function renderAgencies() {
        var agencies =
            state.data && state.data.stats
                ? state.data.stats.agencies || []
                : [];
        var body = $('agencyTableBody');
        body.textContent = '';
        agencies.forEach(function (item) {
            var row = document.createElement('tr');
            var identityCell = document.createElement('td');
            var identity = document.createElement('div');
            identity.className = 'agency-identity';
            identity.appendChild(agencyAvatar(item));
            var copy = document.createElement('span');
            copy.className = 'agency-copy';
            var name = document.createElement('strong');
            name.textContent = item.name || '—';
            var id = document.createElement('span');
            id.textContent =
                t('fami_agency.id_prefix', 'Agency ID:') +
                ' ' +
                (item.shortId || item.id || '—');
            copy.appendChild(name);
            copy.appendChild(id);
            identity.appendChild(copy);
            identityCell.appendChild(identity);
            row.appendChild(identityCell);
            textCell(row, item.ownerId || '—');
            textCell(row, item.country || '—');
            textCell(row, count(item.totalHosts));
            textCell(row, count(item.giftedHostCount));
            textCell(row, count(item.diamondEarnings));
            textCell(row, dateTime(item.joinedAtMS));
            body.appendChild(row);
        });
        $('agencyEmpty').hidden = agencies.length > 0;
    }

    function renderRange() {
        document.querySelectorAll('[data-range]').forEach(function (button) {
            button.setAttribute(
                'aria-pressed',
                button.getAttribute('data-range') === state.range.preset
                    ? 'true'
                    : 'false'
            );
            button.disabled = state.loading;
        });
        $('rangeCaption').textContent =
            state.range.startDate === state.range.endDate
                ? state.range.startDate
                : state.range.startDate + ' – ' + state.range.endDate;
    }

    function renderAll() {
        renderProfile();
        renderAgencies();
        renderRange();
    }
    function setLoading(value) {
        state.loading = value;
        document.body.classList.toggle('is-loading', value);
        renderRange();
    }
    function setMutating(value) {
        state.mutating = value;
        document.body.classList.toggle('is-mutating', value);
    }

    function load() {
        setLoading(true);
        return window.HyGuild.bdCenter
            .load(state.range)
            .then(function (data) {
                state.data = data;
                $('statsStatus').hidden = true;
                renderAll();
            })
            .catch(function () {
                $('statsStatus').hidden = false;
                $('statsStatus').textContent = t(
                    'fami_bd.load_failed',
                    'Unable to load BD Center.'
                );
                toast($('statsStatus').textContent);
            })
            .finally(function () {
                setLoading(false);
            });
    }

    function selectRange(preset) {
        if (preset === 'custom') {
            $('rangeStart').value = state.range.startDate;
            $('rangeEnd').value = state.range.endDate;
            $('rangeDialog').showModal();
            return;
        }
        state.range = window.HyGuild.dateRange.create(preset);
        load();
    }

    function applyCustomRange(event) {
        event.preventDefault();
        try {
            state.range = window.HyGuild.dateRange.create('custom', {
                start: $('rangeStart').value,
                end: $('rangeEnd').value,
            });
        } catch (_) {
            toast(t('fami_range.invalid', 'Choose a valid date range.'));
            return;
        }
        $('rangeDialog').close();
        load();
    }

    function saveContact(event) {
        event.preventDefault();
        if (state.mutating) return;
        var value = String($('contactInput').value || '').trim();
        if (!value) {
            toast(t('fami_agency.contact_required', 'Enter a contact number.'));
            return;
        }
        setMutating(true);
        window.HyGuild.bdCenter
            .saveContact(value)
            .then(function () {
                state.data.profile.contact = value;
                $('contactDialog').close();
                renderProfile();
                toast(t('fami_agency.contact_saved', 'Contact saved.'));
            })
            .catch(function () {
                toast(
                    t(
                        'fami_agency.contact_save_failed',
                        'Unable to save contact.'
                    )
                );
            })
            .finally(function () {
                setMutating(false);
            });
    }

    function inviteAgency(event) {
        event.preventDefault();
        if (state.mutating) return;
        var ownerID = String($('ownerDisplayID').value || '').trim();
        if (!ownerID) return;
        setMutating(true);
        window.HyGuild.bdCenter
            .inviteAgency(ownerID, $('agencyNameInput').value)
            .then(function () {
                $('inviteDialog').close();
                toast(
                    t(
                        'fami_bd.invite_sent',
                        'Invitation sent. The agency is created after acceptance.'
                    )
                );
            })
            .catch(function () {
                toast(t('fami_bd.invite_failed', 'Unable to invite agency.'));
            })
            .finally(function () {
                setMutating(false);
            });
    }

    function bind() {
        $('backButton').addEventListener('click', function () {
            if (window.history.length > 1) window.history.back();
            else if (window.HyAppBridge) window.HyAppBridge.back();
        });
        $('editContactButton').addEventListener('click', function () {
            $('contactInput').value =
                (state.data && state.data.profile.contact) || '';
            $('contactDialog').showModal();
        });
        $('cancelContactButton').addEventListener('click', function () {
            $('contactDialog').close();
        });
        $('contactForm').addEventListener('submit', saveContact);
        $('addAgencyButton').addEventListener('click', function () {
            $('ownerDisplayID').value = '';
            $('agencyNameInput').value = '';
            $('inviteDialog').showModal();
        });
        $('cancelInviteButton').addEventListener('click', function () {
            $('inviteDialog').close();
        });
        $('inviteForm').addEventListener('submit', inviteAgency);
        $('rangeFilters').addEventListener('click', function (event) {
            var button = event.target.closest('[data-range]');
            if (button && !state.loading)
                selectRange(button.getAttribute('data-range'));
        });
        $('cancelRangeButton').addEventListener('click', function () {
            $('rangeDialog').close();
        });
        $('rangeForm').addEventListener('submit', applyCustomRange);
        window.addEventListener('hyapp:i18n-ready', renderAll);
    }

    function init() {
        state.range = window.HyGuild.dateRange.create('today');
        bind();
        renderRange();
        load();
    }
    if (document.readyState === 'loading')
        document.addEventListener('DOMContentLoaded', init);
    else init();
})();
