(function($) {
  'use strict';

  /* ══════════════════════════════════════════
     CANVAS SEMNĂTURĂ — variabile globale
  ══════════════════════════════════════════ */
  var canvas       = null;
  var ctx          = null;
  var drawing      = false;
  var hasSig       = false;
  var canvasInited = false;

  function initCanvas() {
    if (canvasInited) return;
    canvas = document.getElementById('ovpspo-sig-canvas');
    if (!canvas) return;
    canvasInited = true;
    ctx = canvas.getContext('2d');
    var culoare = (typeof OVPSPO230 !== 'undefined' && OVPSPO230.culoare) ? OVPSPO230.culoare : '#0F408A';

    function resizeCanvas() {
      var ratio = window.devicePixelRatio || 1;
      var rect  = canvas.getBoundingClientRect();
      canvas.width  = rect.width  * ratio;
      canvas.height = 150         * ratio;
      ctx.scale(ratio, ratio);
      ctx.strokeStyle = culoare;
      ctx.lineWidth   = 2.5;
      ctx.lineCap     = 'round';
      ctx.lineJoin    = 'round';
    }
    resizeCanvas();
    window.addEventListener('resize', resizeCanvas);

    function getPos(e) {
      var rect = canvas.getBoundingClientRect();
      var src  = e.touches ? e.touches[0] : e;
      return { x: src.clientX - rect.left, y: src.clientY - rect.top };
    }
    canvas.addEventListener('mousedown',  function(e) { drawing=true; var p=getPos(e); ctx.beginPath(); ctx.moveTo(p.x,p.y); });
    canvas.addEventListener('mousemove',  function(e) { if(!drawing)return; var p=getPos(e); ctx.lineTo(p.x,p.y); ctx.stroke(); hasSig=true; });
    canvas.addEventListener('mouseup',    function()  { drawing=false; });
    canvas.addEventListener('mouseleave', function()  { drawing=false; });
    canvas.addEventListener('touchstart', function(e) { e.preventDefault(); drawing=true; var p=getPos(e); ctx.beginPath(); ctx.moveTo(p.x,p.y); }, {passive:false});
    canvas.addEventListener('touchmove',  function(e) { e.preventDefault(); if(!drawing)return; var p=getPos(e); ctx.lineTo(p.x,p.y); ctx.stroke(); hasSig=true; }, {passive:false});
    canvas.addEventListener('touchend',   function()  { drawing=false; });
  }

  /* ══════════════════════════════════════════
     HANDLERS — înregistrate O SINGURĂ DATĂ
     pe $(document) cu namespace .ovpspo230
  ══════════════════════════════════════════ */
  var handlersRegistered = false;

  function registerHandlers() {
    if (handlersRegistered) return;
    handlersRegistered = true;

    // Init canvas la primul contact cu formularul
    $(document).on('mousedown.ovpspo230 touchstart.ovpspo230', '.bf230-wrap', function() {
      initCanvas();
    });

    // Șterge semnătură
    $(document).on('click.ovpspo230', '#ovpspo-clear-sig', function() {
      initCanvas();
      if (!canvas || !ctx) return;
      var r = window.devicePixelRatio || 1;
      ctx.clearRect(0, 0, canvas.width / r, canvas.height / r);
      hasSig = false;
      $('#ovpspo-sig-data').val('');
    });

    // Radio perioadă
    $(document).on('click.ovpspo230', '.bf230-wrap .bf230-period-opt', function() {
      $(this).closest('.bf230-period').find('.bf230-period-opt').removeClass('selected');
      $(this).addClass('selected');
      $(this).find('input[type=radio]').prop('checked', true);
    });

    // Checkboxuri - input e hidden, label face toggle nativ
    // Citim starea DUPA ce browser-ul a procesat click-ul pe label
    $(document).on('change.ovpspo230', '.bf230-wrap input[type=checkbox]', function() {
      $(this).closest('.bf230-check-row').toggleClass('checked', $(this).prop('checked'));
    });
    // Click pe span (zona vizuala) - toggle manual pentru ca span nu e label
    $(document).on('click.ovpspo230', '.bf230-wrap .bf230-sq', function(e) {
      e.stopPropagation();
      var $inp = $(this).siblings('input[type=checkbox]');
      if (!$inp.length) $inp = $(this).closest('.bf230-check-row').find('input[type=checkbox]');
      $inp.prop('checked', !$inp.prop('checked')).trigger('change');
    });

    // Validare blur
    $(document).on('blur.ovpspo230', '#ovpspo-form input, #ovpspo-form select', function() {
      validateField($(this));
    });

    // Click pe buton Submit
    $(document).on('click.ovpspo230', '#ovpspo-submit', function(e) {
      e.preventDefault();
      e.stopPropagation();
      doSubmit();
    });

    // Submit nativ pe form (fallback)
    $(document).on('submit.ovpspo230', '#ovpspo-form', function(e) {
      e.preventDefault();
      doSubmit();
    });
  }

  /* ══════════════════════════════════════════
     VALIDARE
  ══════════════════════════════════════════ */
  function validateField($el) {
    var val      = $el.val() ? $el.val().trim() : '';
    var name     = $el.attr('name');
    var ok       = true;
    var required = ['nume','prenume','judet','localitate','strada','nr'];
    if (required.indexOf(name) !== -1 && !val) ok = false;
    if (name === 'cnp'   && val && !/^\d{13}$/.test(val))                       ok = false;
    if (name === 'email' && val && !/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(val))    ok = false;
    $el.toggleClass('bf230-invalid', !ok);
    $el.siblings('.bf230-err').toggleClass('show', !ok);
    return ok;
  }

  /* ══════════════════════════════════════════
     SUBMIT
  ══════════════════════════════════════════ */
  function doSubmit() {
    var valid = true;

    // Validare câmpuri
    $('#ovpspo-form input[type=text], #ovpspo-form input[type=email], #ovpspo-form select').each(function() {
      if (!validateField($(this))) valid = false;
    });

    // GDPR
    var gdprOk = $('#ovpspo-gdpr').prop('checked');
    $('#ovpspo-err-gdpr').toggleClass('show', !gdprOk);
    if (!gdprOk) valid = false;

    // Terms
    var termsOk = $('#ovpspo-terms').prop('checked');
    $('#ovpspo-err-terms').toggleClass('show', !termsOk);
    if (!termsOk) valid = false;

    // Semnătură
    initCanvas();
    if (canvas && hasSig) {
      $('#ovpspo-sig-data').val(canvas.toDataURL('image/png'));
    }
    var sigOk = hasSig;
    $('#ovpspo-err-sig').toggleClass('show', !sigOk);
    if (!sigOk) valid = false;

    if (!valid) {
      var $first = $('#ovpspo-form .bf230-invalid:first, .bf230-err.show:first');
      if ($first.length) {
        $('html,body').animate({ scrollTop: $first.offset().top - 100 }, 400);
      }
      return;
    }

    // Trimite AJAX
    var $btn = $('#ovpspo-submit');
    $btn.prop('disabled', true);
    $btn.find('.bf230-btn-text').hide();
    $btn.find('.bf230-btn-loading').show();
    $('#ovpspo-response').html('');

    var ajaxUrl = (typeof OVPSPO230 !== 'undefined' && OVPSPO230.ajax_url)
      ? OVPSPO230.ajax_url
      : (typeof ajaxurl !== 'undefined' ? ajaxurl : '/wp-admin/admin-ajax.php');

    $.ajax({
      url:  ajaxUrl,
      type: 'POST',
      data: $('#ovpspo-form').serialize(),
      success: function(res) {
        if (res && res.success) {
          $('#ovpspo-form').slideUp(300, function() {
            $('#ovpspo-response').html(
              '<div class="bf230-success">' +
              '<h3>Formular trimis cu succes!</h3>' +
              '<p>' + res.data.message + '</p></div>'
            );
            $('html,body').animate({ scrollTop: $('.bf230-wrap').offset().top - 40 }, 500);
          });
        } else {
          var msg = (res && res.data && res.data.message) ? res.data.message : 'A apărut o eroare. Încearcă din nou.';
          $('#ovpspo-response').html('<div class="bf230-error"><strong>Eroare:</strong> ' + msg + '</div>');
          $btn.prop('disabled', false);
          $btn.find('.bf230-btn-text').show();
          $btn.find('.bf230-btn-loading').hide();
        }
      },
      error: function(xhr, status, err) {
        $('#ovpspo-response').html('<div class="bf230-error">Eroare de conexiune (' + status + '). Încearcă din nou.</div>');
        $btn.prop('disabled', false);
        $btn.find('.bf230-btn-text').show();
        $btn.find('.bf230-btn-loading').hide();
      }
    });
  }

  /* ══════════════════════════════════════════
     INIT — apelat din mai multe surse
  ══════════════════════════════════════════ */
  function ovpspoInit230() {
    registerHandlers(); // guard intern — ruleaza o singura data
  }

  $(document).ready(function() { ovpspoInit230(); });
  $(window).on('load', function() { ovpspoInit230(); });

  // Hook Elementor
  $(window).on('elementor/frontend/init', function() {
    if (typeof elementorFrontend !== 'undefined') {
      elementorFrontend.hooks.addAction('frontend/element_ready/shortcode.default', function() {
        ovpspoInit230();
      });
    }
  });

})(jQuery);
