import re

with open("static/js/bottom-bar.js", "r") as f:
    text = f.read()

events = """
    function bindDynamicActions() {
        const listContainer = byId('bbTabsContent');
        if (!listContainer) return;

        listContainer.addEventListener('click', function (e) {
            const target = e.target;
            const btn = target.closest('button');
            if (!btn) return;

            if (btn.id === 'btnNextTask') {
                console.log("-> Beder backend om næste opgave...");
                btn.innerHTML = '<span class="spinner-border spinner-border-sm" role="status" aria-hidden="true"></span> Omsætter kalender og SLA...';
                btn.disabled = true;
                
                fetch('/api/v1/bottom_bar/next_task', { method: 'POST' })
                .then(r => r.json())
                .then(data => {
                    const task = data.task;
                    btn.innerHTML = '<i class="bi bi-magic me-2"></i>Du fik tildelt: ' + task.title + ' (Sag #' + task.case_id + ') <span class="badge bg-light text-dark ms-2">' + data.free_time_calculated + 'm fri</span>';
                    btn.classList.add('btn-success');
                    btn.classList.remove('btn-primary');
                })
                .catch(err => {
                    console.error("Fejl:", err);
                    btn.innerHTML = "Fejl - prøv igen";
                    btn.disabled = false;
                });
            }
        });
    }

    document.addEventListener('DOMContentLoaded', function () {"""

text = text.replace("    document.addEventListener('DOMContentLoaded', function () {", events)
text = text.replace("        bindSheetToggle();", "        bindSheetToggle();\n        bindDynamicActions();")

with open("static/js/bottom-bar.js", "w") as f:
    f.write(text)
