{{-- Dropdown --}}
    <ul class="mx-1 navbar-nav"><li>

        {{-- Activate --}}
        <a id="taxDropdownApplication" role="button" href="#"
            data-toggle="dropdown" aria-haspopup="true" aria-expanded="true" v-pre
            title="Desglosar Impuestos" class="px-0 mx-1 fixed-width oculto-impresion btn btn-secondary apply-taxes-button"
        ><i class="fas fa-coins"></i></a>

        {{-- Structure --}}
        <div aria-labelledby="taxDropdownApplication" class="dropdown-menu drop-filter" style="width: 60%;">
            <form method="post" id="tax_application_from" autocomplete="off"
                enctype="multipart/form-data" class="container px-1 mb-3"
            >@csrf

                {{-- Header --}}
                <div class="px-2 py-2 mb-2 g-2 d-flex align-items-center justify-content-start border-bottom">
                    {{-- Title --}}
                    <div class="d-flex align-items-center justify-content-start">
                        {{-- Title --}}
                        <span class="mx-1 text-start text-uppercase harsi-color font-weight-bolder" style="font-size: 1.1rem">
                            {{ __('reports')['shared']['tax_breakdown_form']['title'] }}
                        </span>
                    </div>

                    {{-- Buttons --}}
                    <div class="d-flex align-items-center justify-content-end">
                        {{-- Reset --}}
                        <button type="button" onclick="resetBreakdown()"
                            class="py-1 mx-1 btn btn-secondary fw-semi-bold"
                        >
                            Reset
                        </button>

                        {{-- Submit Button --}}
                        <button type="submit" class="py-1 mx-2 btn harsi-button fw-semi-bold" style="font-size: 1rem">
                            {{ __('common_actions')['apply'] }}
                        </button>
                    </div>
                </div>

                {{-- Content --}}
                <div class="px-3 flex-column d-flex justify-content-start align-items-start g-1">

                    {{-- Buttons --}}
                    <div class="justify-content-start align-items-baseline">
                        <button type="button" id="add_tax_to_breakdown"
                            class="py-0 btn btn-outline-primary"
                        >
                            <span class="d-inline-flex align-items-end g-0">
                                <i class="fas fa-coins"></i>
                                <small style="font-size: 0.5rem">✚</small>
                            </span>&nbsp;
                            {{ __('common_actions')['add'] }}
                        </button>
                    </div>

                    {{-- Content --}}
                    <div id="tax_breakdown" class="g-1 d-flex flex-column"></div>
                </div>

            </form>
        </div>

    </li></ul>

{{-- Control Scripts --}}
    {{-- General Controls --}}
    <script>
        $(document).ready(function(){
          // Avoid unexpected Dropdown Close
            $('.drop-filter').on('click', function (e) {
                e.stopPropagation(); // Evita que el dropdown se cierre al hacer clic dentro
            });
        });
    </script>

    {{-- Breakdown Controls --}}
    <script>
      // Triggers & Interactions
        $(document).ready(function(){
          // Add Tax Row
            $('#add_tax_to_breakdown').on('click', function (e) {
                const row =`
                    <div class="tax-row d-flex g-0_5 justify-content-center align-items-center">

                        {{-- Delete Button --}}
                        <button onclick="$(this).parent().remove();" type="button"
                            class="px-2 py-1 mt-4 rounded-circle btn btn-outline-danger"
                            style="padding: 0rem 0.355rem !important"
                        >
                            <i class="fa fa-times"></i>
                        </button>

                        {{-- Module --}}
                        <div class="d-flex flex-column align-items-start"
                            style="width: 17.5%;"
                        >
                            <label class="external-label fw-semi-bold">
                                {{ __('neutral_words')['module'] }}
                            </label>

                            <select name="tax_module[]" class="form-control">
                                <option value="lodging">{{ __('entity_forms')['reservation']['sections']['lodging'] }}</option>
                                <option value="consumption">{{ __('entity_forms')['reservation']['sections']['consumption'] }}</option>
                                <option value="extras">{{ __('entity_forms')['reservation']['sections']['extras'] }}</option>
                            </select>
                        </div>

                        {{-- Name --}}
                        <div class="d-flex flex-column align-items-start">
                            <label for="tax_names[]" class="external-label fw-semi-bold">
                                {{ __('entity_fields')['common']['name'] }}
                            </label>

                            <input type="text" name="tax_names[]" required
                                placeholder="Ej. IVA, ISH..." class="form-control">
                        </div>

                        {{-- Rate --}}
                        <div class="d-flex flex-column align-items-start"
                            style="width: 17.5%;"
                        >
                            <label for="tax_rate[]" class="external-label fw-semi-bold">
                                {{ __('entity_forms')['tax_prod_serv']['placeholders']['rate'] }}
                            </label>

                            <input type="number" name="tax_rate[]" required
                                step="0.000001" value="0.0" onchange="roundDecimals(this, 6)"
                                placeholder="0.0%" class="form-control">
                        </div>

                        {{-- Tax Type --}}
                        <div class="d-flex flex-column align-items-start">
                            <label for="tax_type[]" class="external-label fw-semi-bold">
                                {{ __('entity_fields')['common']['type'] }}
                            </label>

                            <select name="tax_type[]" class="form-control tax-type-select">
                                <option value="transfer">{{ __('neutral_words')['transfer'] }}</option>
                                <option value="withholding">{{ __('neutral_words')['withholding'] }}</option>
                            </select>
                        </div>

                        {{-- Application Type --}}
                        <div class="d-flex flex-column align-items-start"
                            style="width: 22.5%;"
                        >
                            <label for="tax_application[]" class="external-label fw-semi-bold">
                                {{ __('entity_fields')['common']['form'] }}
                            </label>

                            <select name="tax_application[]" class="form-control tax-application-select">
                                <option value="base">{{ __('reports')['shared']['tax_breakdown_form']['base_option'] }}</option>
                                <option value="base_plus_transfers">{{ __('reports')['shared']['tax_breakdown_form']['base_plus_transfers_option'] }}</option>
                            </select>
                        </div>

                    </div>
                `;

                $('#tax_breakdown').append(row);
            });

          // Submit Breakdown Form
            $('#tax_application_from').on('submit', function (e) {
                e.preventDefault();

              //* Extract Form Data
                const form_data = parseFormData( $('#tax_application_from').serializeArray() );

              //* Validations
                if (!form_data?.tax_names?.length) {
                    showToast(
                        `{{ __('common_responses_and_messages')['data_not_loaded'] }}`,
                        "#C34808", "#78350F"
                    );
                    return;
                }

              //* Build Taxes
                const taxes = {
                    lodging: [],
                    consumption: [],
                    extras: []
                };

                for (let i = 0; i < form_data.tax_names.length; i++) {
                    const module = form_data.tax_module[i];

                    taxes[module].push({
                        name: form_data.tax_names[i],
                        rate: form_data.tax_rate[i],
                        type: form_data.tax_type[i],
                        application: form_data.tax_application[i]
                    });
                }

              //* Update Breakdown Configuration
                HOTEL_TAX_BREAKDOWN_ENGINE.taxes = taxes;
                HOTEL_TAX_BREAKDOWN_ENGINE.is_applied = true;

              //* Apply Taxes
                HOTEL_TAX_BREAKDOWN_ENGINE.is_notified = false;
                applyHotelTaxes();
            });

          // On define Tax Application
            $(document).on('change', '.tax-type-select', function () {
              // Control Data
                const row = $(this).closest('.tax-row');
                const applicationSelect = row.find('.tax-application-select');
                const type = $(this).val();

              // Apply Restrictions
                if (type === 'withholding') { // Withholdings
                    applicationSelect.val('base');
                    applicationSelect .find('option[value="base_plus_transfers"]')
                        .prop('disabled', true);
                } else { // Transfers
                    applicationSelect.find('option[value="base_plus_transfers"]')
                        .prop('disabled', false);
                }

            });
        });

        function resetBreakdown() {
          //* Clear Section
            $('#tax_breakdown').empty(); // Form Taxes
            $('.dynamic-tax-row').remove(); // Footer Breakdown
            $('#tax_breakdown_disclaimer').empty(); // Disclaimer

          //* Spread Page Actions
            spreadResetActions()

          //* Update Breakdown Configuration
            HOTEL_TAX_BREAKDOWN_ENGINE.taxes = [];
            HOTEL_TAX_BREAKDOWN_ENGINE.is_applied = false;

            $(HOTEL_TAX_BREAKDOWN_ENGINE.total_selector)
                .text( formatCurrency(HOTEL_TAX_BREAKDOWN_ENGINE.total));
        }

      // Render Interactions
        function calculateReverseBreakdown({total, taxes}) {
          // Control Data
            let factor = 1;

          // Transfers Factor
            let transfer_factor = 1;

            taxes.forEach(tax => {
                if (
                    (tax.type === 'transfer') && (tax.application === 'base')
                ) {
                    transfer_factor += taxToDecimal(tax.rate);
                }
            });

          // Global Factor
            taxes.forEach(tax => {
                let contribution = taxToDecimal(tax.rate);

                // Base + Transfers
                if (tax.application === 'base_plus_transfers')
                    contribution = transfer_factor * taxToDecimal(tax.rate);

                if (tax.type === 'transfer') {
                    factor += contribution;
                } else {
                    factor -= contribution;
                }
            });

          // Apply Reverse Taxes
            const raw_subtotal = total / factor;
            const subtotal = parseFloat(raw_subtotal.toFixed(6));

            // Build Breakdown
            const breakdown = taxes.map(tax => {
                let base = subtotal;

                if (tax.application === 'base_plus_transfers') {
                    base = subtotal * transfer_factor;
                }

                const sign = (tax.type === 'transfer') ? "+" : "-";

                const amount = base * taxToDecimal(tax.rate);
                return { ...tax, sign, amount};
            });

          // Return Data
            return {
                subtotal,
                total,
                factor,
                breakdown
            };
        }

        function calculateGroupedBreakdown({totals, taxes}) {
            const grouped = {};

            Object.keys(totals).forEach(module => {
                if (module === 'final') return;

                grouped[module] = calculateReverseBreakdown({
                    total: totals[module],
                    taxes: taxes[module] || []
                });
            });
            return grouped;
        }

        function renderSectionBreakdown({section, result}) {
          // Extract Config
            const config = HOTEL_TAX_BREAKDOWN_ENGINE.sections[section];
                if (!config) return;

          // Control Data
            const container = $(config.container_selector);
            container.find('.dynamic-breakdown').remove();

          // Show Disclaimer
            $('#tax_breakdown_disclaimer').html(`
                <small class="text-muted small">
                    * {{ __('reports')['shared']['tax_breakdown_form']['warning_application'] }}
                </small>
            `);

          // Adjust Visuals
            

          // Render Taxes
            let html = `
                <div class="dynamic-breakdown">
                    {{-- Base Subtotal --}}
                    <div class="small text-muted d-flex justify-content-between">
                        <span class="fw-semi-bold">{{ __('reports')['shared']['tax_breakdown_form']['base_computed'] }}</span>
                        <span class="fw-semi-bold">${formatCurrency(result.subtotal)}</span>
                    </div>
            `;

            result.breakdown.forEach(tax => {
                const sign = (tax.type === 'transfer') ? '+' : '-';

                const color = (tax.type === 'transfer')
                        ? 'text-success' : 'text-danger';

                html += `
                    <div class="small d-flex justify-content-between">
                        <span class="text-muted">${tax.name} (${sign}${tax.rate}%)</span>
                        <span class="off-color ${color}">
                            ${sign} ${formatCurrency(tax.amount)}
                        </span>
                    </div>
                `;
            });

          // Re render Total
            container.append(html);
        }

      // Render Support
        function applyHotelTaxes() {
          // Compute Tax Breakdown
            const result =
                calculateGroupedBreakdown({
                    totals: HOTEL_TAX_BREAKDOWN_ENGINE.totals,
                    taxes: HOTEL_TAX_BREAKDOWN_ENGINE.taxes
                });

          // Render Breakdown
            renderHotelBreakdown(result);

          // Notify Render
            if (!HOTEL_TAX_BREAKDOWN_ENGINE.is_notified) {
                showToast(
                    "{{ __('reports')['shared']['tax_breakdown_form']['applying_taxes'] }}",
                    "#057A55", "#046C4E"
                )

                HOTEL_TAX_BREAKDOWN_ENGINE.is_notified = true;
            }
        }

        function taxToDecimal(rate) {
            const parsed = parseFloat(rate);
                if (parsed > 1) return parsed / 100;

            return parsed;
        }

    </script>

    {{-- Support Functions --}}
    <script>
      // Messages
        function showToast(text, gradient_from, gradient_to) {
            Toastify({
                text,
                duration: 4000,
                close: false,
                gravity: "top",
                position: "right",
                avatar: "{{ asset('images/toast-info-icon.png') }}",

                selector: document.body,
                offset: { x: 0, y: 24 },
                style: {
                    background: `linear-gradient(to right, ${gradient_from}, ${gradient_to})`,
                },
            }).showToast();
        }

      // Format Data
        function roundDecimals(input, decimal_limit = 2, default_value = 0.0) {
            let valor = parseFloat(input.value);

            if (isNaN(valor)) valor= default_value;

            const result = parseFloat(valor.toFixed(decimal_limit));
            const exceedsTwoDecimals = /\d\.\d{3,}/.test(valor);

            let parse_value = 0;
            if (exceedsTwoDecimals) {
                parse_value = Math.abs(result).toFixed(decimal_limit);
            } else {
                parse_value = Math.abs(result === 0 ? 0 : valor).toFixed(decimal_limit);
            }

            input.value = removeUnnecessaryDecimal(parse_value);
            return;
        }

        function strToStrPercentage(number, {decimals = 2, is_low_decimal = true} = {}) {
            let percentage_quantity;
            if (is_low_decimal) {
                percentage_quantity = (parseFloat(number) * 100).toFixed(decimals);
            } else {
                percentage_quantity = parseFloat(number).toFixed(decimals);
            }

            percentage_quantity = removeUnnecessaryDecimal(percentage_quantity);
            return `${percentage_quantity}%`;
        }

      // Parsers
        function parseFormData(brute_data) {
            const result = {};

            brute_data.forEach(({ name, value }) => {
                const cleanName = name.replace(/\[\]$/, ""); // Remove "[]" from input groups

                // Si ya existe y es un array → agregamos
                if (result.hasOwnProperty(cleanName)) {
                    if (Array.isArray(result[cleanName])) {
                        result[cleanName].push(value);
                    } else {
                        // Convertir valor previo a array
                        result[cleanName] = [result[cleanName], value];
                    }
                } else {
                    // Si el nombre termina con [] => crear como array
                    if (name.endsWith("[]")) {
                        result[cleanName] = [value];
                    } else {
                        result[cleanName] = value;
                    }
                }
            });

            return result;
        }
    </script>
