/* timeclock.js — main-app timeclock dashboard */
var Timeclock = (function () {
    var _cfg = {};

    function init(cfg) {
        _cfg = cfg;
        bindClockButtons();
        bindManagerEvents();
        scheduleWhosInRefresh();
    }

    /* ── Clock In / Out / Break / Lunch / Return ───────────────────────────── */
    function bindClockButtons() {
        var btnIn     = document.getElementById('btn-clock-in');
        var btnOut    = document.getElementById('btn-clock-out');
        var btnBreak  = document.getElementById('btn-break');
        var btnLunch  = document.getElementById('btn-lunch');
        var btnReturn = document.getElementById('btn-return-from-break');

        if (btnIn) {
            btnIn.addEventListener('click', function () {
                btnIn.disabled = true;
                postJson('/Timeclock/ClockIn', {})
                    .then(function () { location.reload(); })
                    .catch(function (err) {
                        showFeedback(err, 'danger');
                        btnIn.disabled = false;
                    });
            });
        }

        if (btnOut) {
            btnOut.addEventListener('click', function () {
                btnOut.disabled = true;
                var entryId = parseInt(btnOut.getAttribute('data-entry-id'));
                postJson('/Timeclock/ClockOut', { entryId: entryId })
                    .then(function () { location.reload(); })
                    .catch(function (err) {
                        showFeedback(err, 'danger');
                        btnOut.disabled = false;
                    });
            });
        }

        // Break button (type 1) and Lunch button (type 2) share the same handler
        [btnBreak, btnLunch].forEach(function (btn) {
            if (!btn) return;
            btn.addEventListener('click', function () {
                btn.disabled = true;
                var breakType = parseInt(btn.getAttribute('data-break-type'));
                postJson('/Timeclock/GoOnBreak', { breakType: breakType })
                    .then(function () { location.reload(); })
                    .catch(function (err) {
                        showFeedback(err, 'danger');
                        btn.disabled = false;
                    });
            });
        });

        if (btnReturn) {
            btnReturn.addEventListener('click', function () {
                btnReturn.disabled = true;
                postJson('/Timeclock/ReturnFromBreak', {})
                    .then(function () { location.reload(); })
                    .catch(function (err) {
                        showFeedback(err, 'danger');
                        btnReturn.disabled = false;
                    });
            });
        }
    }

    /* ── Who's In refresh every 60 s ──────────────────────────────────────── */
    function scheduleWhosInRefresh() {
        setInterval(refreshWhosIn, 60000);
    }

    function refreshWhosIn() {
        fetch('/Timeclock/ActiveNow')
            .then(function (r) { return r.json(); })
            .then(function (data) {
                var count = data.length;
                var badge = document.getElementById('whos-in-count');
                if (badge) badge.textContent = count;

                var ts = document.getElementById('whos-in-updated');
                if (ts) ts.textContent = 'Updated ' + new Date().toLocaleTimeString();
            });
    }

    /* ── Manager: edit / delete / manual entry ────────────────────────────── */
    function bindManagerEvents() {
        if (!_cfg.isManager) return;

        document.addEventListener('click', function (e) {
            if (e.target.closest('.btn-edit-entry')) openEditModal(e.target.closest('.btn-edit-entry'));
            if (e.target.closest('.btn-delete-entry')) confirmDelete(e.target.closest('.btn-delete-entry'));
        });

        var btnSaveEdit = document.getElementById('btn-save-edit');
        if (btnSaveEdit) btnSaveEdit.addEventListener('click', saveEdit);

        var btnLoad = document.getElementById('btn-manager-load');
        if (btnLoad) btnLoad.addEventListener('click', loadManagerHistory);

        var btnSaveManual = document.getElementById('btn-save-manual-entry');
        if (btnSaveManual) btnSaveManual.addEventListener('click', saveManualEntry);

        // Pre-fill clock-in to "now" each time the modal opens
        var manualModal = document.getElementById('manualEntryModal');
        if (manualModal) {
            manualModal.addEventListener('show.bs.modal', function () {
                document.getElementById('manual-clock-in').value = toDatetimeLocal(new Date().toISOString());
                document.getElementById('manual-clock-out').value = '';
                document.getElementById('manual-notes').value = '';
                document.getElementById('manual-employee').value = '';
                setManualFeedback('', '');
            });
        }
    }

    function openEditModal(btn) {
        document.getElementById('edit-entry-id').value   = btn.getAttribute('data-id');
        document.getElementById('edit-clock-in').value  = toDatetimeLocal(btn.getAttribute('data-clockin'));
        var out = btn.getAttribute('data-clockout');
        document.getElementById('edit-clock-out').value = out ? toDatetimeLocal(out) : '';
        document.getElementById('edit-notes').value     = btn.getAttribute('data-notes');
        new bootstrap.Modal(document.getElementById('editEntryModal')).show();
    }

    function saveEdit() {
        var id      = parseInt(document.getElementById('edit-entry-id').value);
        var inVal   = document.getElementById('edit-clock-in').value;
        var outVal  = document.getElementById('edit-clock-out').value;
        var notes   = document.getElementById('edit-notes').value;

        postJson('/Timeclock/Edit', {
            id:           id,
            clockInTime:  new Date(inVal).toISOString(),
            clockOutTime: outVal ? new Date(outVal).toISOString() : null,
            notes:        notes
        }).then(function () {
            location.reload();
        }).catch(function (err) {
            alert('Error saving: ' + err);
        });
    }

    function confirmDelete(btn) {
        if (!confirm('Delete this clock entry? This cannot be undone.')) return;
        var id = parseInt(btn.getAttribute('data-id'));
        postJson('/Timeclock/Delete', id)
            .then(function () { location.reload(); })
            .catch(function (err) { alert('Error: ' + err); });
    }

    function saveManualEntry() {
        var userId  = document.getElementById('manual-employee').value;
        var inVal   = document.getElementById('manual-clock-in').value;
        var outVal  = document.getElementById('manual-clock-out').value;
        var notes   = document.getElementById('manual-notes').value;

        if (!userId) { setManualFeedback('Please select an employee.', 'danger'); return; }
        if (!inVal)  { setManualFeedback('Clock-in time is required.', 'danger'); return; }
        if (outVal && new Date(outVal) <= new Date(inVal)) {
            setManualFeedback('Clock-out must be after clock-in.', 'danger');
            return;
        }

        var btn = document.getElementById('btn-save-manual-entry');
        btn.disabled = true;

        postJson('/Timeclock/ManualEntry', {
            userId:       userId,
            clockInTime:  new Date(inVal).toISOString(),
            clockOutTime: outVal ? new Date(outVal).toISOString() : null,
            notes:        notes || null
        }).then(function () {
            bootstrap.Modal.getInstance(document.getElementById('manualEntryModal')).hide();
            location.reload();
        }).catch(function (err) {
            setManualFeedback(err || 'Failed to save entry.', 'danger');
            btn.disabled = false;
        });
    }

    function setManualFeedback(msg, type) {
        var el = document.getElementById('manual-entry-feedback');
        if (!el) return;
        if (!msg) { el.className = 'd-none'; el.textContent = ''; return; }
        el.className = 'alert alert-' + type + ' alert-permanent py-2';
        el.textContent = msg;
    }

    function loadManagerHistory() {
        var from = document.getElementById('manager-from').value;
        var to   = document.getElementById('manager-to').value;
        var url  = '/Timeclock/History?from=' + from + '&to=' + to;

        fetch(url)
            .then(function (r) { return r.json(); })
            .then(function (data) {
                renderManagerHistory(data);
            });
    }

    function renderManagerHistory(entries) {
        var container = document.getElementById('manager-history-container');
        if (!entries.length) {
            container.innerHTML = '<div class="text-muted text-center py-4">No entries in this range.</div>';
            return;
        }

        var TYPE_LABELS = ['<span class="badge bg-success">Work</span>',
                           '<span class="badge bg-warning text-dark">Break</span>',
                           '<span class="badge bg-info text-dark">Lunch</span>'];

        var rows = entries.map(function (e) {
            var inTime   = new Date(e.clockInTime).toLocaleString();
            var outTime  = e.clockOutTime ? new Date(e.clockOutTime).toLocaleString() : '&mdash;';
            var hours    = e.hoursWorked != null ? e.hoursWorked.toFixed(2) : '&mdash;';
            var typeBadge = TYPE_LABELS[e.entryType] || TYPE_LABELS[0];
            return '<tr>' +
                '<td>' + escHtml(e.userDisplayName) + '</td>' +
                '<td>' + typeBadge + '</td>' +
                '<td>' + inTime + '</td>' +
                '<td>' + outTime + '</td>' +
                '<td>' + hours + '</td>' +
                '<td>' + escHtml(e.notes || '') + '</td>' +
                '</tr>';
        }).join('');

        container.innerHTML = '<table class="table table-hover table-sm mb-0">' +
            '<thead class="table-light"><tr>' +
            '<th>Employee</th><th>Type</th><th>Clock In</th><th>Clock Out</th><th>Hours</th><th>Notes</th>' +
            '</tr></thead><tbody>' + rows + '</tbody></table>';
    }

    /* ── Utilities ─────────────────────────────────────────────────────────── */
    function postJson(url, data) {
        return fetch(url, {
            method:  'POST',
            headers: { 'Content-Type': 'application/json', 'RequestVerificationToken': getAntiForgery() },
            body:    JSON.stringify(data)
        }).then(function (r) {
            if (!r.ok) return r.json().then(function (e) { throw e.message || 'Request failed'; });
            return r.json();
        });
    }

    function getAntiForgery() {
        var el = document.querySelector('input[name="__RequestVerificationToken"]');
        return el ? el.value : '';
    }

    function showFeedback(msg, type) {
        var el = document.getElementById('clock-feedback');
        if (!el) return;
        el.className = 'mt-3 alert alert-' + type + ' alert-permanent';
        el.textContent = msg;
        el.classList.remove('d-none');
    }

    function toDatetimeLocal(isoStr) {
        if (!isoStr) return '';
        var d = new Date(isoStr);
        var pad = function (n) { return String(n).padStart(2, '0'); };
        return d.getFullYear() + '-' + pad(d.getMonth() + 1) + '-' + pad(d.getDate()) +
               'T' + pad(d.getHours()) + ':' + pad(d.getMinutes());
    }

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

    return { init: init };
})();
