/**
 * UI del formulario de eventos: tarjetas de entrada clonables, capacidad, oferta y campos personalizados.
 *
 * Depende de jQuery (SB Admin 2) y de las plantillas `#rt-ticket-template` / `#rt-cf-row-template` en Blade.
 * {@see resources/views/dashboard/events/_form.blade.php}
 */
(function ($) {
    'use strict';

    /** Valores de `capacity_strategy` alineados a {@see \App\Enums\TicketCapacityStrategy}. */
    var CAP_UNLIMITED = 'unlimited';
    var CAP_PER = 'per_ticket';
    var CAP_SHARED = 'shared_pool';

    /** Abre el cuerpo desplegable de una tarjeta de entrada (collapse Bootstrap). */
    function expandTicketBody($card) {
        var $panel = $card.children('[id^="rt-ticket-collapse-"]');
        if (!$panel.length || typeof $panel.collapse !== 'function') {
            return;
        }
        if (!$panel.hasClass('show')) {
            $panel.collapse('show');
        }
    }

    /** Asegura que todas las entradas muestren sus campos (útil al añadir una nueva sin perder la vista de las anteriores). */
    function expandAllTicketBodies() {
        $('#rt-tickets-container .rt-ticket-card').each(function () {
            expandTicketBody($(this));
        });
    }

    /** Renombra cabeceras "Entrada N" tras añadir o quitar tarjetas. */
    function refreshTicketCardTitles() {
        var i18n = window.rtEventFormI18n || {};
        var label = i18n.ticketLabel || 'Entrada';
        var $cards = $('#rt-tickets-container .rt-ticket-card');
        $cards.each(function (idx) {
            $(this).find('.rt-ticket-card-label').text(label + ' ' + (idx + 1));
        });
        var n = $cards.length;
        var msg = i18n.atLeastOneTicket || '';
        $cards.find('.rt-remove-ticket').prop('disabled', n <= 1).attr('title', n <= 1 ? msg : '');
    }

    /** Muestra/oculta filas de cupo según la estrategia seleccionada. */
    function toggleCapacityRows($card) {
        var v = $card.find('.rt-capacity-strategy').val();
        var $shared = $card.find('.rt-row-shared');
        var $cap = $card.find('.rt-row-capacity');
        var $lblOwn = $card.find('.rt-label-capacity-own');
        var $lblShared = $card.find('.rt-label-capacity-shared');
        $shared.toggleClass('d-none', v !== CAP_SHARED);
        $cap.toggleClass('d-none', v === CAP_UNLIMITED);
        $lblOwn.toggleClass('d-none', v === CAP_SHARED);
        $lblShared.toggleClass('d-none', v !== CAP_SHARED);
    }

    /** Checkbox "precio de oferta" + fila asociada. */
    function toggleSalePrice($card) {
        var on = $card.find('.rt-has-sale-price').is(':checked');
        $card.find('.rt-sale-price-row').toggleClass('d-none', !on);
    }

    /** Previsualiza el precio final (incluyendo comisión). */
    function refreshPricePreview($input) {
        var val = parseFloat($input.val());
        var $preview = $input.siblings('.rt-price-preview').find('.rt-final-price-val');
        if (isNaN(val) || val <= 0) {
            $preview.text('--');
            return;
        }
        var config = window.rtFeeConfig || { fixed: 2.99, percentage: 0.05 };
        // platform_fee = fixed + (base * percentage)
        var total = val + config.fixed + (val * config.percentage);
        $preview.text('$' + total.toFixed(2));
    }

    /** Textarea de opciones solo para select / radio / checkbox. */
    function toggleCfOptions($row) {
        var t = $row.find('.rt-cf-type').val();
        var show = t === 'select' || t === 'radio' || t === 'checkbox';
        $row.find('.rt-cf-options-wrap').toggleClass('d-none', !show);
    }

    /**
     * Registra manejadores en una tarjeta (inicial o clonada). Ojo: múltiples binds si se llama dos veces sobre el mismo nodo.
     */
    function bindTicketCard($card) {
        $card.find('.rt-capacity-strategy').on('change', function () {
            toggleCapacityRows($card);
        });
        $card.find('.rt-has-sale-price').on('change', function () {
            toggleSalePrice($card);
        });

        $card.find('.rt-ticket-price-input').on('input change', function () {
            refreshPricePreview($(this));
        });
        $card.find('.rt-ticket-price-input').each(function () {
            refreshPricePreview($(this));
        });

        $card.find('.rt-cf-type').on('change', function () {
            toggleCfOptions($(this).closest('.rt-custom-field-row'));
        });
        $card.find('.rt-custom-field-row').each(function () {
            toggleCfOptions($(this));
        });
        toggleCapacityRows($card);
        toggleSalePrice($card);

        if (window.rtInitTomSelectIn) {
            window.rtInitTomSelectIn($card[0]);
        }

        $card.find('.rt-remove-ticket').on('click', function () {
            if ($('#rt-tickets-container .rt-ticket-card').length <= 1) {
                return;
            }
            if (window.rtDestroyTomSelectIn) {
                window.rtDestroyTomSelectIn($card[0]);
            }
            $card.remove();
            refreshTicketCardTitles();
        });

        $card.find('.rt-add-custom-field').on('click', function () {
            var ti = String($card.data('ticket-index'));
            var $list = $card.find('.rt-custom-fields-list');
            var cfi = $list.find('.rt-custom-field-row').length;
            var tpl = $('#rt-cf-row-template').html();
            if (!tpl) {
                return;
            }
            var html = tpl.replace(/__TI__/g, ti).replace(/__CFI__/g, String(cfi));
            $list.append(html);
            var $row = $list.find('.rt-custom-field-row').last();
            $row.find('input[name*="[sort_order]"]').val(cfi);
            $row.find('.rt-remove-cf').on('click', function () {
                if (window.rtDestroyTomSelectIn) {
                    window.rtDestroyTomSelectIn($row[0]);
                }
                $row.remove();
            });
            $row.find('.rt-cf-type').on('change', function () {
                toggleCfOptions($row);
            });
            toggleCfOptions($row);
            if (window.rtInitTomSelectIn) {
                window.rtInitTomSelectIn($row[0]);
            }
        });

        $card.find('.rt-remove-cf').on('click', function () {
            var $row = $(this).closest('.rt-custom-field-row');
            if (window.rtDestroyTomSelectIn) {
                window.rtDestroyTomSelectIn($row[0]);
            }
            $row.remove();
        });
    }

    /**
     * Punto de entrada desde Blade: `startIndex` = siguiente índice libre en `tickets[n]`.
     *
     * @param {number} startIndex
     */
    window.rtInitEventTickets = function (startIndex) {
        window.rtNextTicketIndex = typeof startIndex === 'number' ? startIndex : 0;

        $('#rt-tickets-container .rt-ticket-card').each(function () {
            bindTicketCard($(this));
        });
        refreshTicketCardTitles();

        $('#rt-add-ticket')
            .off('click.rtAddTicket')
            .on('click.rtAddTicket', function () {
                var tpl = $('#rt-ticket-template').html();
                if (!tpl) {
                    return;
                }
                var idx = window.rtNextTicketIndex++;
                var html = tpl.replace(/__INDEX__/g, String(idx));
                var $node = $(html);
                $node.attr('data-ticket-index', idx);
                $('#rt-tickets-container').append($node);
                bindTicketCard($node);
                refreshTicketCardTitles();
                expandAllTicketBodies();
                if ($node[0] && typeof $node[0].scrollIntoView === 'function') {
                    $node[0].scrollIntoView({ behavior: 'smooth', block: 'nearest' });
                }
            });

        $(document)
            .off('shown.bs.collapse.rtTicketPanel hidden.bs.collapse.rtTicketPanel')
            .on('shown.bs.collapse.rtTicketPanel hidden.bs.collapse.rtTicketPanel', '[id^="rt-ticket-collapse-"]', function (e) {
                var sel = '#' + e.target.id;
                var $btn = $('[data-target="' + sel + '"]');
                if (!$btn.length) {
                    return;
                }
                var open = e.type.indexOf('shown') === 0;
                $btn.attr('aria-expanded', open ? 'true' : 'false');
                $btn.find('.rt-ticket-chevron').toggleClass('rt-chevron-open', open);
            });
    };
})(window.jQuery);
