/* Flexi Access Bank – Main JS */
'use strict';

// Auto-dismiss alerts after 5s
document.querySelectorAll('.alert').forEach(el => {
  setTimeout(() => {
    const bsAlert = bootstrap.Alert.getOrCreateInstance(el);
    bsAlert && bsAlert.close();
  }, 5000);
});

// Format card number input
const cardInput = document.getElementById('card_number');
if (cardInput) {
  cardInput.addEventListener('input', function() {
    let val = this.value.replace(/\D/g, '').substring(0, 16);
    this.value = val.replace(/(.{4})/g, '$1 ').trim();
  });
}

// Confirm before sensitive actions
document.querySelectorAll('[data-confirm]').forEach(el => {
  el.addEventListener('click', function(e) {
    if (!confirm(this.dataset.confirm)) e.preventDefault();
  });
});

// Amount formatter on blur
document.querySelectorAll('.amount-input').forEach(el => {
  el.addEventListener('blur', function() {
    const v = parseFloat(this.value.replace(/,/g, ''));
    if (!isNaN(v)) this.value = v.toFixed(2);
  });
});

// Copy to clipboard
document.querySelectorAll('[data-copy]').forEach(el => {
  el.addEventListener('click', function() {
    navigator.clipboard.writeText(this.dataset.copy).then(() => {
      const orig = this.innerHTML;
      this.innerHTML = '<i class="fa fa-check"></i> Copied!';
      setTimeout(() => this.innerHTML = orig, 2000);
    });
  });
});

// Transfer type toggle
const transferTypeSelect = document.getElementById('transfer_type');
const intlFields = document.getElementById('intl_fields');
if (transferTypeSelect && intlFields) {
  const toggle = () => {
    intlFields.style.display = transferTypeSelect.value === 'international' ? '' : 'none';
  };
  transferTypeSelect.addEventListener('change', toggle);
  toggle();
}

// Mini chart helper
function renderMiniChart(canvasId, labels, data, color) {
  const canvas = document.getElementById(canvasId);
  if (!canvas) return;
  new Chart(canvas, {
    type: 'line',
    data: {
      labels,
      datasets: [{
        data,
        borderColor: color,
        backgroundColor: color + '22',
        fill: true,
        tension: 0.4,
        pointRadius: 0,
        borderWidth: 2,
      }]
    },
    options: {
      responsive: true,
      maintainAspectRatio: false,
      plugins: { legend: { display: false }, tooltip: { mode: 'index', intersect: false } },
      scales: { x: { display: false }, y: { display: false } },
    }
  });
}

// Expose globally
window.renderMiniChart = renderMiniChart;
