/**
 * Mali CRUD V2 - Advanced Features JavaScript
 * Additional features for advanced form elements
 */

(function() {
    'use strict';

    // ==================== REPEATER ====================
    document.addEventListener('click', function(e) {
        if (e.target.closest('.add-repeater-item')) {
            const repeater = e.target.closest('.repeater');
            const template = repeater.querySelector('.repeater-template');
            const items = repeater.querySelector('.repeater-items');
            const index = items.querySelectorAll('.repeater-item').length;

            const html = template.innerHTML.replace(/__INDEX__/g, index);
            const div = document.createElement('div');
            div.innerHTML = html;
            items.appendChild(div.firstElementChild);
        }

        if (e.target.closest('.remove-repeater-item')) {
            e.target.closest('.repeater-item').remove();
        }
    });

    // ==================== KEY-VALUE PAIRS ====================
    document.addEventListener('click', function(e) {
        if (e.target.closest('.add-kv')) {
            const container = e.target.closest('.key-value-pairs');
            const row = document.createElement('div');
            row.className = 'row key-value-row mb-2';
            row.innerHTML = `
                <div class="col-5">
                    <input type="text" name="${container.id}[keys][]" class="form-control" placeholder="${__('Key')}">
                </div>
                <div class="col-5">
                    <input type="text" name="${container.id}[values][]" class="form-control" placeholder="${__('Value')}">
                </div>
                <div class="col-2">
                    <button type="button" class="btn btn-danger remove-kv">
                        <i class="fa fa-trash"></i>
                    </button>
                </div>
            `;
            container.insertBefore(row, e.target);
        }

        if (e.target.closest('.remove-kv')) {
            e.target.closest('.key-value-row').remove();
        }
    });

    // ==================== INLINE TABLE EDITOR ====================
    document.addEventListener('click', function(e) {
        if (e.target.closest('.add-row')) {
            const table = e.target.closest('.inline-table-editor').querySelector('table tbody');
            const columns = table.closest('.inline-table-editor').querySelectorAll('thead th');
            const rowCount = table.querySelectorAll('tr').length;
            const name = table.closest('.inline-table-editor').querySelector('input').name.split('[')[0];

            let html = '<tr>';
            columns.forEach((col, index) => {
                if (index < columns.length - 1) {
                    const colKey = col.textContent.toLowerCase().replace(/\s+/g, '_');
                    html += `<td><input type="text" name="${name}[${rowCount}][${colKey}]" class="form-control form-control-sm"></td>`;
                }
            });
            html += `<td><button type="button" class="btn btn-sm btn-danger remove-row"><i class="fa fa-trash"></i></button></td>`;
            html += '</tr>';

            table.insertAdjacentHTML('beforeend', html);
        }

        if (e.target.closest('.remove-row')) {
            e.target.closest('tr').remove();
        }
    });

    // ==================== SLUG GENERATOR ====================
    document.addEventListener('click', function(e) {
        if (e.target.closest('.regenerate-slug')) {
            const input = e.target.closest('.input-group').querySelector('.slug-input');
            const sourceField = input.dataset.source;
            const sourceInput = document.querySelector(`[name="${sourceField}"]`);

            if (sourceInput) {
                const slug = sourceInput.value
                    .toLowerCase()
                    .replace(/[^a-z0-9\s-]/g, '')
                    .replace(/\s+/g, '-')
                    .replace(/-+/g, '-')
                    .trim('-');
                input.value = slug;
            }
        }
    });

    // ==================== SIGNATURE PAD ====================
    function initSignaturePads() {
        document.querySelectorAll('.signature-pad').forEach(canvas => {
            if (canvas.dataset.initialized) return;

            const ctx = canvas.getContext('2d');
            let isDrawing = false;
            let lastX = 0;
            let lastY = 0;

            ctx.strokeStyle = '#000';
            ctx.lineWidth = 2;
            ctx.lineCap = 'round';

            function startDrawing(e) {
                isDrawing = true;
                const rect = canvas.getBoundingClientRect();
                lastX = (e.clientX || e.touches[0].clientX) - rect.left;
                lastY = (e.clientY || e.touches[0].clientY) - rect.top;
            }

            function draw(e) {
                if (!isDrawing) return;
                e.preventDefault();

                const rect = canvas.getBoundingClientRect();
                const currentX = (e.clientX || e.touches[0].clientX) - rect.left;
                const currentY = (e.clientY || e.touches[0].clientY) - rect.top;

                ctx.beginPath();
                ctx.moveTo(lastX, lastY);
                ctx.lineTo(currentX, currentY);
                ctx.stroke();

                lastX = currentX;
                lastY = currentY;

                // Update hidden input
                const hiddenInput = canvas.parentElement.querySelector('.signature-data');
                if (hiddenInput) {
                    hiddenInput.value = canvas.toDataURL();
                }
            }

            function stopDrawing() {
                isDrawing = false;
            }

            canvas.addEventListener('mousedown', startDrawing);
            canvas.addEventListener('mousemove', draw);
            canvas.addEventListener('mouseup', stopDrawing);
            canvas.addEventListener('mouseout', stopDrawing);

            canvas.addEventListener('touchstart', startDrawing);
            canvas.addEventListener('touchmove', draw);
            canvas.addEventListener('touchend', stopDrawing);

            canvas.dataset.initialized = 'true';
        });
    }

    document.addEventListener('click', function(e) {
        if (e.target.closest('.clear-signature')) {
            const wrapper = e.target.closest('.signature-pad-wrapper');
            const canvas = wrapper.querySelector('.signature-pad');
            const ctx = canvas.getContext('2d');
            ctx.clearRect(0, 0, canvas.width, canvas.height);
            wrapper.querySelector('.signature-data').value = '';
        }
    });

    // ==================== RANGE SLIDER ====================
    document.addEventListener('input', function(e) {
        if (e.target.type === 'range') {
            const output = e.target.parentElement.querySelector('.range-value');
            if (output) {
                output.textContent = e.target.value;
            }
        }
    });

    // ==================== STAR RATING ====================
    document.addEventListener('change', function(e) {
        if (e.target.closest('.star-rating input[type="radio"]')) {
            const rating = e.target.closest('.star-rating');
            const inputs = rating.querySelectorAll('input');
            const value = e.target.value;

            inputs.forEach(input => {
                const label = input.nextElementSibling;
                if (input.value <= value) {
                    label.classList.add('text-warning');
                } else {
                    label.classList.remove('text-warning');
                }
            });
        }
    });

    // ==================== DUAL LISTBOX ====================
    document.addEventListener('click', function(e) {
        const btn = e.target.closest('.btn');
        if (!btn || !btn.closest('.dual-listbox')) return;

        const container = btn.closest('.dual-listbox');
        const available = container.querySelector('[id^="available-"]');
        const selected = container.querySelector('[id^="selected-"]');

        if (btn.textContent.includes('>>')) {
            // Move all to selected
            Array.from(available.options).forEach(opt => {
                opt.selected = false;
                selected.appendChild(opt);
            });
        } else if (btn.textContent.includes('<<')) {
            // Move all to available
            Array.from(selected.options).forEach(opt => {
                opt.selected = false;
                available.appendChild(opt);
            });
        } else if (btn.textContent.includes('>') && !btn.textContent.includes('>>')) {
            // Move selected to selected
            Array.from(available.selectedOptions).forEach(opt => {
                opt.selected = false;
                selected.appendChild(opt);
            });
        } else if (btn.textContent.includes('<') && !btn.textContent.includes('<<')) {
            // Move selected to available
            Array.from(selected.selectedOptions).forEach(opt => {
                opt.selected = false;
                available.appendChild(opt);
            });
        }
    });

    // ==================== ICON PICKER ====================
    document.addEventListener('click', function(e) {
        if (e.target.closest('.open-icon-picker')) {
            const input = e.target.closest('.icon-picker').querySelector('.icon-input');
            const preview = e.target.closest('.input-group').querySelector('i');

            // Simple icon picker modal
            const icons = [
                'fa fa-home', 'fa fa-user', 'fa fa-cog', 'fa fa-envelope',
                'fa fa-phone', 'fa fa-map-marker', 'fa fa-calendar', 'fa fa-search',
                'fa fa-plus', 'fa fa-edit', 'fa fa-trash', 'fa fa-save',
                'fa fa-download', 'fa fa-upload', 'fa fa-print', 'fa fa-share',
                'fa fa-heart', 'fa fa-star', 'fa fa-bell', 'fa fa-flag',
                'fa fa-tag', 'fa fa-bookmark', 'fa fa-image', 'fa fa-video',
                'fa fa-music', 'fa fa-file', 'fa fa-folder', 'fa fa-chart-bar',
            ];

            let html = '<div class="icon-picker-modal p-3">';
            html += '<h5>' + __('Select Icon') + '</h5>';
            html += '<div class="row">';
            icons.forEach(icon => {
                html += `<div class="col-2 mb-2">
                    <button type="button" class="btn btn-outline-secondary w-100 select-icon" data-icon="${icon}">
                        <i class="${icon} fa-lg"></i>
                    </button>
                </div>`;
            });
            html += '</div>';
            html += '</div>';

            // Show modal
            const modal = document.createElement('div');
            modal.className = 'modal fade';
            modal.innerHTML = `
                <div class="modal-dialog modal-lg">
                    <div class="modal-content">
                        <div class="modal-header">
                            <h5 class="modal-title">${__('Select Icon')}</h5>
                            <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                        </div>
                        <div class="modal-body">${html}</div>
                    </div>
                </div>
            `;
            document.body.appendChild(modal);

            const bsModal = new bootstrap.Modal(modal);
            bsModal.show();

            modal.addEventListener('click', function(ev) {
                if (ev.target.closest('.select-icon')) {
                    const icon = ev.target.closest('.select-icon').dataset.icon;
                    input.value = icon;
                    preview.className = icon;
                    bsModal.hide();
                    modal.remove();
                }
            });

            modal.addEventListener('hidden.bs.modal', function() {
                modal.remove();
            });
        }
    });

    // ==================== GALLERY SORTABLE ====================
    function initGallerySortable() {
        document.querySelectorAll('.gallery-preview').forEach(gallery => {
            if (gallery.dataset.sortableInitialized) return;

            // Simple drag and drop
            let draggedItem = null;

            gallery.addEventListener('dragstart', function(e) {
                draggedItem = e.target.closest('.gallery-item');
                e.target.closest('.gallery-item').style.opacity = '0.5';
            });

            gallery.addEventListener('dragend', function(e) {
                e.target.closest('.gallery-item').style.opacity = '1';
                draggedItem = null;
            });

            gallery.addEventListener('dragover', function(e) {
                e.preventDefault();
                const afterElement = getDragAfterElement(gallery, e.clientY);
                if (afterElement == null) {
                    gallery.appendChild(draggedItem);
                } else {
                    gallery.insertBefore(draggedItem, afterElement);
                }
            });

            gallery.querySelectorAll('.gallery-item').forEach(item => {
                item.draggable = true;
            });

            gallery.dataset.sortableInitialized = 'true';
        });
    }

    function getDragAfterElement(container, y) {
        const draggableElements = [...container.querySelectorAll('.gallery-item:not([style*="opacity: 0.5"])')];

        return draggableElements.reduce((closest, child) => {
            const box = child.getBoundingClientRect();
            const offset = y - box.top - box.height / 2;
            if (offset < 0 && offset > closest.offset) {
                return { offset: offset, element: child };
            } else {
                return closest;
            }
        }, { offset: Number.NEGATIVE_INFINITY }).element;
    }

    // ==================== INITIALIZE ====================
    document.addEventListener('DOMContentLoaded', function() {
        initSignaturePads();
        initGallerySortable();
    });

    // Re-initialize on modal shown
    document.addEventListener('shown.bs.modal', function() {
        initSignaturePads();
        initGallerySortable();
    });

})();
