/**
 * calendar.js — the Tables toolbar "Calendar & Events app" enabler.
 *
 * The Calendar is a standalone event-management app that provisions its own
 * tables; this wizard just enables + configures it at the project level (saved
 * to the `calendar` ModuleState). On Build the app is generated at
 * generated/calendar/ and linked in the menu. Self-contained (own listeners).
 */
(function () {
    'use strict';

    function ready(fn) { document.readyState !== 'loading' ? fn() : document.addEventListener('DOMContentLoaded', fn); }
    function $(id) { return document.getElementById(id); }
    function result(html, ok) { $('calAppResult').innerHTML = '<div class="alert alert-' + (ok ? 'success' : 'danger') + ' py-2 px-3 mb-0 small">' + html + '</div>'; }

    function loadConfig() {
        var base = (typeof baseUrl !== 'undefined' ? baseUrl : (window.baseUrl || '')), slug = (typeof projectSlug !== 'undefined' ? projectSlug : (window.projectSlug || ''));
        fetch(base + '/project/' + slug + '/tables/calendar-config', { credentials: 'same-origin' })
            .then(function (r) { return r.json(); })
            .then(function (d) {
                var c = (d && d.config) || {};
                if (typeof c.enabled === 'boolean') $('calAppEnabled').checked = c.enabled;
                if (c.defaultView) $('calAppView').value = c.defaultView;
                if (c.firstDay != null) $('calAppFirstDay').value = String(c.firstDay);
                if (c.menuLabel) $('calAppMenuLabel').value = c.menuLabel;
                if (typeof c.allowPersonal === 'boolean') $('calAppPersonal').checked = c.allowPersonal;
                if (typeof c.appReminders === 'boolean') $('calAppInApp').checked = c.appReminders;
                if (typeof c.emailReminders === 'boolean') $('calAppEmail').checked = c.emailReminders;
            }).catch(function () {});
    }

    function submit() {
        var payload = {
            enabled: $('calAppEnabled').checked,
            defaultView: $('calAppView').value,
            firstDay: parseInt($('calAppFirstDay').value, 10) || 0,
            menuLabel: $('calAppMenuLabel').value || 'Calendar',
            allowPersonal: $('calAppPersonal').checked,
            appReminders: $('calAppInApp').checked,
            emailReminders: $('calAppEmail').checked
        };
        var btn = $('btnCreateCalendarSubmit');
        btn.disabled = true;
        var base = (typeof baseUrl !== 'undefined' ? baseUrl : (window.baseUrl || '')), slug = (typeof projectSlug !== 'undefined' ? projectSlug : (window.projectSlug || ''));
        fetch(base + '/project/' + slug + '/tables/calendar', {
            method: 'POST', credentials: 'same-origin',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify(payload)
        }).then(function (r) { return r.json(); }).then(function (d) {
            btn.disabled = false;
            if (d && d.success) {
                if (window.Swal) {
                    window.Swal.fire({ icon: 'success', title: payload.enabled ? 'Calendar enabled' : 'Calendar disabled', text: d.message || '', confirmButtonColor: '#6366f1' }).then(closeModal);
                } else {
                    result('<i class="bi bi-check-circle me-1"></i>' + (d.message || 'Saved.'), true);
                    closeModal();
                }
            } else {
                result((d && d.message) || 'Could not save.', false);
            }
        }).catch(function () { btn.disabled = false; result('Network error.', false); });
    }

    // Close the Bootstrap modal (once the success alert is dismissed).
    function closeModal() {
        var m = $('createCalendarModal');
        if (m && window.bootstrap && window.bootstrap.Modal) {
            var inst = window.bootstrap.Modal.getInstance(m) || new window.bootstrap.Modal(m);
            inst.hide();
        }
    }

    ready(function () {
        var modalEl = $('createCalendarModal');
        if (!modalEl) return;
        var openBtn = $('btnCreateCalendar');
        if (openBtn && window.bootstrap) openBtn.addEventListener('click', function () { new window.bootstrap.Modal(modalEl).show(); });
        modalEl.addEventListener('show.bs.modal', loadConfig);
        $('btnCreateCalendarSubmit').addEventListener('click', submit);
    });
})();
