document.addEventListener('DOMContentLoaded', function () {
    const selAll = document.getElementById('cutqueue_booking_system_select_all');
    const deleteBtn = document.getElementById('cutqueue_booking_system-float-delete');
    const checkboxes = document.querySelectorAll('input[name="cutqueue_booking_system_selected_bookings[]"]');

    function updateButtonVisibility() {
        const anyChecked = [...checkboxes].some(cb => cb.checked);
        deleteBtn.style.display = anyChecked ? 'block' : 'none';
    }

    if (selAll) {
        selAll.addEventListener('change', function () {
            checkboxes.forEach(cb => cb.checked = selAll.checked);
            updateButtonVisibility();
        });
    }
    checkboxes.forEach(cb => cb.addEventListener('change', updateButtonVisibility));

    const tzSelect = document.getElementById("store_timezone");

    if (tzSelect) {
        // Get browser timezone
        const userTimezone = Intl.DateTimeFormat().resolvedOptions().timeZone;

        // Try to find and select it
        for (const option of tzSelect.options) {
            if (option.value === userTimezone) {
                option.selected = true;
                break;
            }
        }
    }

    const storeSelect = document.getElementById("cutqueue-store-select");
    if (storeSelect) {

        if (!storeSelect.value && storeSelect.options.length > 0) {
            const firstValue = storeSelect.options[0].value;

            if (firstValue) {
                const url = new URL(window.location.href);
                url.searchParams.set("cutqueue_booking_system_store", firstValue);
                window.location.href = url.toString(); // force reload so PHP sees it
            }
        }
    }

    const select = document.getElementById('cutqueue_booking_system_payment_mode_select');
    if (select) {
        const stripeFields = document.querySelectorAll('.stripe-settings');

        function toggleStripeFields() {
            const show = (select.value === 'online');
            stripeFields.forEach(f => f.style.display = show ? '' : 'none');
        }
        toggleStripeFields();
        select.addEventListener('change', toggleStripeFields);
    }
});

const tableBody = document.getElementById("services-table-body");

if (tableBody) {

    tableBody.addEventListener("click", function (e) {
        const btn = e.target.closest(".edit-service");
        if (!btn) return;

        const row = btn.closest("tr");
        const nameCell = row.querySelector(".service-name");
        const durationCell = row.querySelector(".service-duration");
        const priceCell = row.querySelector(".service-price");

        // If row is already in edit mode, skip
        if (row.classList.contains("editing")) return;

        const currentName = nameCell.textContent.trim();
        const currentDuration = durationCell.textContent.trim();
        const currentPrice = priceCell.textContent.trim();

        // Replace text with inputs
        nameCell.innerHTML = `<input type="text" class="form-control form-control-sm" value="${currentName}" />`;
        durationCell.innerHTML = `<input type="number" class="form-control form-control-sm" value="${currentDuration}" />`;
        priceCell.innerHTML = `<input type="number" class="form-control form-control-sm" value="${currentPrice}" />`;

        // Replace buttons
        btn.outerHTML = `
        <button class="btn btn-sm btn-success save-service px-3 me-2">Save</button>
        <button class="btn btn-sm btn-secondary cancel-edit px-2 me-2">Cancel</button>
        `;

        row.classList.add("editing");
    });

    // Handle Save and Cancel
    tableBody.addEventListener("click", function (e) {
        const saveBtn = e.target.closest(".save-service");
        const cancelBtn = e.target.closest(".cancel-edit");

        if (saveBtn) {
            const row = saveBtn.closest("tr");
            const index = row.dataset.index;
            const nameInput = row.querySelector(".service-name input");
            const durationInput = row.querySelector(".service-duration input");
            const priceInput = row.querySelector(".service-price input");

            const updatedData = {
                action: "cutqueue_booking_system_update_service",
                index: index,
                name: nameInput.value.trim(),
                duration: durationInput.value.trim(),
                price: priceInput.value.trim(),
                cutqueue_booking_system_nonce: cutqueue_booking_system_formData.nonce,
                cutqueue_booking_system_store: cutqueue_booking_system_formData.store
            };

            fetch(cutqueue_booking_system_formData.ajaxUrl, {
                method: "POST",
                body: new URLSearchParams(updatedData)
            })
                .then(r => r.json())
                .then(res => {
                    if (res.success) {
                        nameInput.parentElement.textContent = updatedData.name;
                        durationInput.parentElement.textContent = updatedData.duration;
                        priceInput.parentElement.textContent = updatedData.price;

                        // Restore action buttons
                        row.querySelector(".save-service").outerHTML =
                            `<button class="btn btn-sm btn-warning me-2 edit-service px-3">Edit</button>`;
                        row.querySelector(".cancel-edit")?.remove();
                        row.classList.remove("editing");
                    } else {
                        alert(res.data || "Error updating service");
                    }
                })
                .catch(() => alert("Server error while saving."));
        }

        if (cancelBtn) {
            const row = cancelBtn.closest("tr");
            row.classList.remove("editing");
            const index = row.dataset.index;

            // Reload original values from DOM snapshot or refresh page if simpler
            location.reload();
        }
    });
}

function toggleRow(cb) { const row = cb.closest('tr'); row.querySelectorAll('select').forEach(s => s.disabled = cb.checked); }

function copyHours(fromDay) {
    const rows = document.querySelectorAll('tbody tr'); let fromRow;
    rows.forEach(r => { if (r.querySelector('td strong').textContent === fromDay) fromRow = r; });
    if (!fromRow) return;
    const openVal = fromRow.querySelector('select[name^="open_"]').value;
    const closeVal = fromRow.querySelector('select[name^="close_"]').value;
    rows.forEach(r => { if (r !== fromRow) { r.querySelector('select[name^="open_"]').value = openVal; r.querySelector('select[name^="close_"]').value = closeVal; } });
}

