(function() {
  'use strict';

  var conditionsContainer = document.getElementById('js-conditions-container');
  var actionsContainer = document.getElementById('js-actions-container');
  var addConditionBtn = document.getElementById('js-add-condition');
  var addActionBtn = document.getElementById('js-add-action');
  var data = window.AutomationFormData || { integrations: [], emailTemplates: [], recipientLabels: {} };

  function getNextIndex(container) {
    var rows = container.querySelectorAll('.automation-row');
    var maxIdx = -1;
    rows.forEach(function(row) {
      var idx = parseInt(row.getAttribute('data-index') || '0', 10);
      if (idx > maxIdx) maxIdx = idx;
    });
    return maxIdx + 1;
  }

  function escapeHtml(str) {
    var div = document.createElement('div');
    div.textContent = str;
    return div.innerHTML;
  }

  function buildIntegrationCheckboxes(namePrefix) {
    var html = '<div class="checkbox-group">';
    data.integrations.forEach(function(integ) {
      html += '<label class="checkbox-label">'
        + '<input type="checkbox" name="' + namePrefix + '[integration_ids][]" value="' + integ.id + '"> '
        + escapeHtml(integ.name) + ' <span class="muted">(' + escapeHtml(integ.type) + ')</span>'
        + '</label>';
    });
    html += '</div>';
    return html;
  }

  function buildShipmentStatusCheckboxes(namePrefix) {
    var html = '<div class="checkbox-group">';
    Object.keys(data.shipmentStatusOptions || {}).forEach(function(statusKey) {
      var config = data.shipmentStatusOptions[statusKey] || {};
      var label = config.label || statusKey;
      html += '<label class="checkbox-label">'
        + '<input type="checkbox" name="' + namePrefix + '[shipment_status_keys][]" value="' + escapeHtml(statusKey) + '"> '
        + escapeHtml(label)
        + '</label>';
    });
    html += '</div>';
    return html;
  }

  function buildPaymentStatusCheckboxes(namePrefix) {
    var html = '<div class="checkbox-group">';
    Object.keys(data.paymentStatusOptions || {}).forEach(function(statusKey) {
      var label = data.paymentStatusOptions[statusKey] || statusKey;
      html += '<label class="checkbox-label">'
        + '<input type="checkbox" name="' + namePrefix + '[payment_status_keys][]" value="' + escapeHtml(statusKey) + '"> '
        + escapeHtml(label)
        + '</label>';
    });
    html += '</div>';
    return html;
  }

  function buildOrderStatusCheckboxes(namePrefix) {
    var html = '<div class="checkbox-group">';
    (data.orderStatusOptions || []).forEach(function(statusOption) {
      var code = (statusOption.code || '').toLowerCase().trim();
      var label = statusOption.name || code;
      html += '<label class="checkbox-label">'
        + '<input type="checkbox" name="' + namePrefix + '[order_status_codes][]" value="' + escapeHtml(code) + '"> '
        + escapeHtml(label)
        + '</label>';
    });
    html += '</div>';
    return html;
  }

  function buildDaysInStatusInput(namePrefix) {
    return '<input type="number" min="1" step="1" class="form-control" name="' + namePrefix + '[days]" placeholder="Liczba dni">';
  }

  function buildEmailActionConfig(namePrefix) {
    var html = '<select class="form-control" name="' + namePrefix + '[template_id]">'
      + '<option value="">-- Wybierz szablon --</option>';
    data.emailTemplates.forEach(function(tpl) {
      html += '<option value="' + tpl.id + '">' + escapeHtml(tpl.name) + '</option>';
    });
    html += '</select>';

    html += '<select class="form-control" name="' + namePrefix + '[recipient]">';
    Object.keys(data.recipientLabels).forEach(function(key) {
      html += '<option value="' + escapeHtml(key) + '">' + escapeHtml(data.recipientLabels[key]) + '</option>';
    });
    html += '</select>';

    return html;
  }

  function buildIssueReceiptActionConfig(namePrefix) {
    var html = '<select class="form-control" name="' + namePrefix + '[receipt_config_id]">'
      + '<option value="">-- Wybierz konfiguracje paragonu --</option>';
    (data.receiptConfigs || []).forEach(function(cfg) {
      html += '<option value="' + cfg.id + '">'
        + escapeHtml(cfg.name) + ' (' + escapeHtml(cfg.number_format || '') + ')'
        + '</option>';
    });
    html += '</select>';

    html += '<select class="form-control" name="' + namePrefix + '[issue_date_mode]">';
    (data.receiptIssueDateModes || []).forEach(function(mode) {
      var labels = data.receiptIssueDateModeLabels || {};
      var label = labels[mode] || mode;
      html += '<option value="' + escapeHtml(mode) + '">' + escapeHtml(label) + '</option>';
    });
    html += '</select>';

    html += '<select class="form-control" name="' + namePrefix + '[duplicate_policy]">';
    (data.receiptDuplicatePolicies || []).forEach(function(policy) {
      var labels = data.receiptDuplicatePolicyLabels || {};
      var label = labels[policy] || policy;
      html += '<option value="' + escapeHtml(policy) + '">' + escapeHtml(label) + '</option>';
    });
    html += '</select>';

    return html;
  }

  function buildShipmentStatusActionConfig(namePrefix) {
    var html = '<select class="form-control" name="' + namePrefix + '[shipment_status_key]">'
      + '<option value="">-- Wybierz docelowy status przesylki --</option>';

    Object.keys(data.shipmentStatusOptions || {}).forEach(function(statusKey) {
      var config = data.shipmentStatusOptions[statusKey] || {};
      var label = config.label || statusKey;
      html += '<option value="' + escapeHtml(statusKey) + '">' + escapeHtml(label) + '</option>';
    });

    html += '</select>';
    return html;
  }

  function buildOrderStatusActionConfig(namePrefix) {
    var html = '<select class="form-control" name="' + namePrefix + '[order_status_code]">'
      + '<option value="">-- Wybierz docelowy status zamowienia --</option>';

    (data.orderStatusOptions || []).forEach(function(statusOption) {
      html += '<option value="' + escapeHtml(statusOption.code || '') + '">'
        + escapeHtml(statusOption.name || statusOption.code || '')
        + '</option>';
    });

    html += '</select>';
    return html;
  }

  function addCondition() {
    var idx = getNextIndex(conditionsContainer);
    var namePrefix = 'conditions[' + idx + ']';

    var row = document.createElement('div');
    row.className = 'automation-row mt-8';
    row.setAttribute('data-index', idx);

    row.innerHTML = '<div class="automation-row__fields">'
      + '<select class="form-control automation-row__type" name="' + namePrefix + '[type]" onchange="window.AutomationForm.onConditionTypeChange(this)">'
      + '<option value="integration" selected>Integracja (kanal sprzedazy)</option>'
      + '<option value="shipment_status">Status przesylki</option>'
      + '<option value="payment_status">Status platnosci</option>'
      + '<option value="order_status">Status zamowienia</option>'
      + '<option value="days_in_status">Liczba dni w statusie</option>'
      + '</select>'
      + '<div class="automation-row__config">'
      + buildIntegrationCheckboxes(namePrefix)
      + '</div>'
      + '</div>'
      + '<button type="button" class="btn btn--sm btn--danger automation-row__remove" onclick="window.AutomationForm.removeRow(this)">&times;</button>';

    conditionsContainer.appendChild(row);
  }

  function addAction() {
    var idx = getNextIndex(actionsContainer);
    var namePrefix = 'actions[' + idx + ']';

    var row = document.createElement('div');
    row.className = 'automation-row mt-8';
    row.setAttribute('data-index', idx);

    row.innerHTML = '<div class="automation-row__fields">'
      + '<select class="form-control automation-row__type" name="' + namePrefix + '[type]" onchange="window.AutomationForm.onActionTypeChange(this)">'
      + '<option value="send_email" selected>Wyslij e-mail</option>'
      + '<option value="issue_receipt">Wystaw paragon</option>'
      + '<option value="update_shipment_status">Zmiana statusu przesylki</option>'
      + '<option value="update_order_status">Zmiana statusu zamowienia</option>'
      + '</select>'
      + '<div class="automation-row__config">'
      + buildEmailActionConfig(namePrefix)
      + '</div>'
      + '</div>'
      + '<button type="button" class="btn btn--sm btn--danger automation-row__remove" onclick="window.AutomationForm.removeRow(this)">&times;</button>';

    actionsContainer.appendChild(row);
  }

  function removeRow(btn) {
    var row = btn.closest('.automation-row');
    if (row) row.remove();
  }

  function onConditionTypeChange(select) {
    var row = select.closest('.automation-row');
    var configDiv = row.querySelector('.automation-row__config');
    var idx = row.getAttribute('data-index');
    var namePrefix = 'conditions[' + idx + ']';

    if (select.value === 'integration') {
      configDiv.innerHTML = buildIntegrationCheckboxes(namePrefix);
      return;
    }
    if (select.value === 'shipment_status') {
      configDiv.innerHTML = buildShipmentStatusCheckboxes(namePrefix);
      return;
    }
    if (select.value === 'payment_status') {
      configDiv.innerHTML = buildPaymentStatusCheckboxes(namePrefix);
      return;
    }
    if (select.value === 'order_status') {
      configDiv.innerHTML = buildOrderStatusCheckboxes(namePrefix);
      return;
    }
    if (select.value === 'days_in_status') {
      configDiv.innerHTML = buildDaysInStatusInput(namePrefix);
    }
  }

  function onActionTypeChange(select) {
    var row = select.closest('.automation-row');
    var configDiv = row.querySelector('.automation-row__config');
    var idx = row.getAttribute('data-index');
    var namePrefix = 'actions[' + idx + ']';

    if (select.value === 'send_email') {
      configDiv.innerHTML = buildEmailActionConfig(namePrefix);
      return;
    }
    if (select.value === 'issue_receipt') {
      configDiv.innerHTML = buildIssueReceiptActionConfig(namePrefix);
      return;
    }
    if (select.value === 'update_shipment_status') {
      configDiv.innerHTML = buildShipmentStatusActionConfig(namePrefix);
      return;
    }
    if (select.value === 'update_order_status') {
      configDiv.innerHTML = buildOrderStatusActionConfig(namePrefix);
    }
  }

  if (addConditionBtn) addConditionBtn.addEventListener('click', addCondition);
  if (addActionBtn) addActionBtn.addEventListener('click', addAction);

  window.AutomationForm = {
    removeRow: removeRow,
    onConditionTypeChange: onConditionTypeChange,
    onActionTypeChange: onActionTypeChange
  };
})();
