jQuery(function($){
    var bnfCount = 1;

    // Precompleaza beneficiarul #1 cu datele organizatiei din Setari
    function prefillBnf1() {
        if ( typeof bf177 === 'undefined' ) return;
        var b = $('[data-bnf="1"]');
        if ( ! b.length ) return;

        if ( bf177.org_nume )    b.find('[name="denB[1]"]').val( bf177.org_nume );
        if ( bf177.org_cif )     b.find('[name="cuiB[1]"]').val( bf177.org_cif );
        if ( bf177.org_iban )    b.find('[name="ibanB[1]"]').val( bf177.org_iban );
        if ( bf177.org_strada )  b.find('[name="stradaB[1]"]').val( bf177.org_strada );
        if ( bf177.org_info )    b.find('[name="infoB[1]"]').val( bf177.org_info );
        if ( bf177.org_sector )  b.find('[name="sectorB[1]"]').val( bf177.org_sector );
        if ( bf177.org_localit ) b.find('[name="localitateB[1]"]').val( bf177.org_localit );
        if ( bf177.org_codpost ) b.find('[name="codPostalB[1]"]').val( bf177.org_codpost );
        if ( bf177.org_telefon ) b.find('[name="telB[1]"]').val( bf177.org_telefon );
        if ( bf177.org_email )   b.find('[name="emailB[1]"]').val( bf177.org_email );

        // Selecteaza judetul
        if ( bf177.org_judet ) {
            b.find('[name="judetB[1]"] option').each(function(){
                if ( $(this).val() === bf177.org_judet ) {
                    $(this).prop('selected', true);
                    return false;
                }
            });
        }

        // Bifeaza automat tipul 1 (ONG/cult) pentru primul beneficiar
        b.find('[name="tipB[1]"][value="1"]').prop('checked', true);
    }

    prefillBnf1();

    // Calcul suma ramasa
    function calcSuma(){
        var max = parseInt($('[name=sumaMax]').val()) || 0;
        var ant = parseInt($('[name=sumaAnt]').val()) || 0;
        $('#bf177_sumaRest').val(Math.max(0, max - ant));
    }
    $('[name=sumaMax], [name=sumaAnt]').on('input', calcSuma);

    // Cerere rectificativa toggle
    $('#bf177_d_rec, #bf177_d_rec_notif').on('change', function(){
        var show = $('#bf177_d_rec').is(':checked') || $('#bf177_d_rec_notif').is(':checked');
        $('#bf177_rectif_data').toggle(show);
    });

    // Adauga beneficiar
    $('#bf177-add-bnf').on('click', function(){
        bnfCount++;
        var template = $('#bf177-bnf-template').html();
        var html = template
            .replace(/\{\{NR\}\}/g, bnfCount)
            .replace(/Nr\. Crt\. \{\{NR\}\}/g, 'Nr. Crt. ' + bnfCount)
            .replace(/Beneficiar \{\{NR\}\}/g, 'Beneficiar ' + bnfCount);
        $('#bf177-beneficiari-wrap').append(html);
        // Scroll la noul beneficiar
        var newBnf = $('#bf177-beneficiari-wrap .bf177-beneficiar-block:last');
        $('html,body').animate({scrollTop: newBnf.offset().top - 80}, 400);
    });

    // Sterge beneficiar (delegat)
    $(document).on('click', '.bf177-btn-delete-bnf', function(){
        if ( $('.bf177-beneficiar-block').length <= 1 ) {
            alert('Trebuie să existe cel puțin un beneficiar.');
            return;
        }
        if ( confirm('Ștergi acest beneficiar?') ) {
            $(this).closest('.bf177-beneficiar-block').slideUp(300, function(){ $(this).remove(); });
        }
    });

    // Submit
    $('#bf177-form').on('submit', function(e){
        e.preventDefault();

        // Validare rapida campuri required
        var errors = [];
        $('#bf177-form [required]').each(function(){
            var el = $(this);
            if ( el.is(':radio') ) {
                var name = el.attr('name');
                if ( !$('#bf177-form [name="'+name+'"]:checked').length ) {
                    var block = el.closest('.bf177-beneficiar-block');
                    var nr = block.length ? block.data('bnf') : '';
                    errors.push('Beneficiar ' + nr + ': Selectează tipul beneficiarului.');
                }
            } else if ( el.is(':checkbox') ) {
                if ( !el.is(':checked') ) {
                    errors.push( el.closest('.bf177-field, .bf177-row').find('label').first().text().replace('*','').trim() );
                }
            } else if ( !$.trim(el.val()) ) {
                var label = el.closest('.bf177-field').find('label').first().text().replace('*','').trim();
                if (label) errors.push(label);
            }
        });

        // Deduplica
        errors = [...new Set(errors)];

        if ( errors.length ) {
            showMsg('<strong>Câmpuri obligatorii necompletate:</strong><br>' + errors.slice(0,5).join('<br>') + (errors.length > 5 ? '<br>...și altele' : ''), 'error');
            return;
        }

        var btn = $('#bf177-submit');
        btn.prop('disabled', true);
        btn.find('.bf177-btn-text').hide();
        btn.find('.bf177-btn-loading').show();
        $('#bf177-msg').hide();

        $.ajax({
            url: bf177.ajax_url,
            type: 'POST',
            data: $('#bf177-form').serialize() + '&action=bf177_submit',
            success: function(res){
                btn.prop('disabled', false);
                btn.find('.bf177-btn-text').show();
                btn.find('.bf177-btn-loading').hide();

                if ( res.success ) {
                    showMsg(res.data.message, 'success');

                    // Descarca XML automat
                    if ( res.data.xml && res.data.filename ) {
                        var blob = b64toBlob(res.data.xml, 'application/xml');
                        var url  = URL.createObjectURL(blob);
                        var a    = document.createElement('a');
                        a.href  = url;
                        a.download = res.data.filename;
                        document.body.appendChild(a);
                        a.click();
                        document.body.removeChild(a);
                        URL.revokeObjectURL(url);
                    }

                    $('html,body').animate({scrollTop: $('#bf177-msg').offset().top - 80}, 400);
                } else {
                    showMsg(res.data.message || 'Eroare la procesare.', 'error');
                }
            },
            error: function(){
                btn.prop('disabled', false);
                btn.find('.bf177-btn-text').show();
                btn.find('.bf177-btn-loading').hide();
                showMsg('Eroare de conexiune. Încearcă din nou.', 'error');
            }
        });
    });

    function showMsg(msg, type){
        $('#bf177-msg').removeClass('success error').addClass(type).html(msg).show();
    }

    function b64toBlob(b64, mime) {
        var bytes = atob(b64);
        var arr   = new Uint8Array(bytes.length);
        for (var i = 0; i < bytes.length; i++) arr[i] = bytes.charCodeAt(i);
        return new Blob([arr], {type: mime});
    }
});
