/* =====================================================================
   SIPIUTANG — Skrip Antarmuka
   ===================================================================== */
(function () {
  'use strict';

  const SP = window.SP = {};
  SP.baseUrl = (document.querySelector('meta[name="base-url"]') || {}).content || '/';
  SP.csrf    = (document.querySelector('meta[name="csrf-token"]') || {}).content || '';

  SP.url = function (path) {
    return SP.baseUrl.replace(/\/$/, '') + '/' + String(path).replace(/^\//, '');
  };

  // ------------------------------------------------------------- Format
  SP.rp = function (v, dec) {
    dec = dec || 0;
    const n = Number(v) || 0;
    const s = Math.abs(n).toLocaleString('id-ID', { minimumFractionDigits: dec, maximumFractionDigits: dec });
    return (n < 0 ? '(Rp ' + s + ')' : 'Rp ' + s);
  };
  SP.nf = function (v, dec) {
    return (Number(v) || 0).toLocaleString('id-ID', { minimumFractionDigits: dec || 0, maximumFractionDigits: dec || 0 });
  };
  SP.rpShort = function (v) {
    const n = Number(v) || 0, a = Math.abs(n);
    let out;
    if (a >= 1e12) out = (n / 1e12).toLocaleString('id-ID', { maximumFractionDigits: 2 }) + ' T';
    else if (a >= 1e9) out = (n / 1e9).toLocaleString('id-ID', { maximumFractionDigits: 2 }) + ' M';
    else if (a >= 1e6) out = (n / 1e6).toLocaleString('id-ID', { maximumFractionDigits: 1 }) + ' Jt';
    else if (a >= 1e3) out = (n / 1e3).toLocaleString('id-ID', { maximumFractionDigits: 0 }) + ' rb';
    else out = n.toLocaleString('id-ID');
    return 'Rp ' + out;
  };

  // ------------------------------------------------------------- Sidebar
  function initSidebar() {
    const body = document.body;
    const open = () => body.classList.add('sidebar-open');
    const close = () => body.classList.remove('sidebar-open');
    document.querySelectorAll('.topbar-toggle').forEach(b => b.addEventListener('click', open));
    document.querySelectorAll('.sidebar-close, .sidebar-backdrop').forEach(b => b.addEventListener('click', close));
    document.addEventListener('keydown', e => { if (e.key === 'Escape') close(); });
  }

  // ------------------------------------------------------------- Loading
  SP.loading = function (on) {
    const el = document.getElementById('loadingOverlay');
    if (el) el.classList.toggle('show', !!on);
  };

  // ------------------------------------------------------------- Konfirmasi
  function initConfirm() {
    const modalEl = document.getElementById('modalKonfirmasi');
    if (!modalEl || !window.bootstrap) return;
    const modal = new bootstrap.Modal(modalEl);
    const msgEl = document.getElementById('modalKonfirmasiPesan');
    const okBtn = document.getElementById('modalKonfirmasiOk');
    let pending = null;

    document.addEventListener('click', function (e) {
      const t = e.target.closest('[data-konfirmasi]');
      if (!t) return;
      e.preventDefault();
      pending = t;
      msgEl.textContent = t.getAttribute('data-konfirmasi') || 'Apakah Anda yakin ingin melanjutkan?';
      okBtn.className = 'btn btn-' + (t.getAttribute('data-konfirmasi-warna') || 'danger');
      okBtn.textContent = t.getAttribute('data-konfirmasi-ok') || 'Ya, Lanjutkan';
      modal.show();
    });

    okBtn.addEventListener('click', function () {
      if (!pending) return;
      modal.hide();
      const form = pending.closest('form');
      if (pending.tagName === 'A' && pending.href) { window.location.href = pending.href; }
      else if (form) { SP.loading(true); form.submit(); }
      pending = null;
    });
  }

  // ------------------------------------------------------------- Input uang
  function initMoneyInputs() {
    document.querySelectorAll('input[data-uang]').forEach(function (inp) {
      const fmt = () => {
        const raw = inp.value.replace(/[^\d,-]/g, '').replace(',', '.');
        if (raw === '' || raw === '-') return;
        const n = parseFloat(raw);
        if (isNaN(n)) return;
        inp.value = n.toLocaleString('id-ID', { maximumFractionDigits: 2 });
      };
      inp.addEventListener('blur', fmt);
      if (inp.value) fmt();
      const form = inp.closest('form');
      if (form && !form.dataset.uangBound) {
        form.dataset.uangBound = '1';
        form.addEventListener('submit', function () {
          form.querySelectorAll('input[data-uang]').forEach(function (i2) {
            i2.value = String(i2.value).replace(/\./g, '').replace(',', '.');
          });
        });
      }
    });
  }

  // ------------------------------------------------------------- Auto-submit filter
  function initAutoFilter() {
    document.querySelectorAll('[data-auto-submit]').forEach(function (el) {
      el.addEventListener('change', function () {
        SP.loading(true);
        el.closest('form').submit();
      });
    });
  }

  // ------------------------------------------------------------- Pilih semua
  function initCheckAll() {
    document.querySelectorAll('[data-check-all]').forEach(function (master) {
      const sel = master.getAttribute('data-check-all');
      master.addEventListener('change', function () {
        document.querySelectorAll(sel).forEach(cb => { cb.checked = master.checked; });
        updateBulkBar();
      });
    });
    document.addEventListener('change', function (e) {
      if (e.target.matches('.row-check')) updateBulkBar();
    });
    function updateBulkBar() {
      const n = document.querySelectorAll('.row-check:checked').length;
      document.querySelectorAll('[data-bulk-bar]').forEach(function (bar) {
        bar.classList.toggle('d-none', n === 0);
        const c = bar.querySelector('[data-bulk-count]');
        if (c) c.textContent = n;
      });
    }
  }

  // ------------------------------------------------------------- Kolom tampil
  function initColumnToggle() {
    document.querySelectorAll('[data-col-toggle]').forEach(function (cb) {
      const key = cb.getAttribute('data-col-toggle');
      const store = 'sp_col_' + (document.body.dataset.page || 'x') + '_' + key;
      const saved = localStorage.getItem(store);
      if (saved !== null) cb.checked = saved === '1';
      apply(cb, key);
      cb.addEventListener('change', function () {
        localStorage.setItem(store, cb.checked ? '1' : '0');
        apply(cb, key);
      });
    });
    function apply(cb, key) {
      document.querySelectorAll('[data-col="' + key + '"]').forEach(function (td) {
        td.style.display = cb.checked ? '' : 'none';
      });
    }
  }

  // ------------------------------------------------------------- Chart helper
  SP.palette = ['#1f3864', '#2e86de', '#00b894', '#f39c12', '#e74c3c', '#8e44ad',
                '#16a085', '#d35400', '#2c3e50', '#7f8c8d', '#c0392b', '#27ae60'];

  SP.chartDefaults = function () {
    if (!window.Chart) return;
    Chart.defaults.font.family = '"Inter","Segoe UI",system-ui,Arial,sans-serif';
    Chart.defaults.font.size = 11;
    Chart.defaults.color = '#5a6478';
    Chart.defaults.plugins.legend.labels.boxWidth = 11;
    Chart.defaults.plugins.legend.labels.boxHeight = 11;
    Chart.defaults.plugins.legend.labels.usePointStyle = true;
    Chart.defaults.plugins.tooltip.backgroundColor = 'rgba(28,36,52,.94)';
    Chart.defaults.plugins.tooltip.padding = 9;
    Chart.defaults.plugins.tooltip.cornerRadius = 6;
    Chart.defaults.maintainAspectRatio = false;
  };

  SP.moneyAxis = {
    ticks: { callback: function (v) { return SP.rpShort(v); } },
    grid: { color: 'rgba(0,0,0,.05)' }
  };

  SP.moneyTooltip = {
    callbacks: {
      label: function (c) {
        const lbl = c.dataset.label ? c.dataset.label + ': ' : '';
        return lbl + SP.rp(c.parsed.y !== undefined && c.parsed.y !== null ? c.parsed.y : c.parsed);
      }
    }
  };

  SP.makeChart = function (canvasId, config) {
    const el = document.getElementById(canvasId);
    if (!el || !window.Chart) return null;
    if (el._chart) el._chart.destroy();
    el._chart = new Chart(el.getContext('2d'), config);
    return el._chart;
  };

  // ------------------------------------------------------------- AJAX
  SP.post = function (url, data) {
    const body = new FormData();
    Object.keys(data || {}).forEach(function (k) {
      const v = data[k];
      if (Array.isArray(v) || (v && typeof v === 'object')) body.append(k, JSON.stringify(v));
      else body.append(k, v === null || v === undefined ? '' : v);
    });
    body.append('_token', SP.csrf);
    return fetch(url, {
      method: 'POST', body: body,
      headers: { 'X-Requested-With': 'XMLHttpRequest', 'X-CSRF-Token': SP.csrf }
    }).then(function (r) { return r.json(); });
  };

  SP.get = function (url, params) {
    const q = new URLSearchParams(params || {}).toString();
    return fetch(url + (q ? (url.includes('?') ? '&' : '?') + q : ''), {
      headers: { 'X-Requested-With': 'XMLHttpRequest' }
    }).then(function (r) { return r.json(); });
  };

  // ------------------------------------------------------------- Toast
  SP.toast = function (msg, type) {
    type = type || 'success';
    let box = document.getElementById('spToastBox');
    if (!box) {
      box = document.createElement('div');
      box.id = 'spToastBox';
      box.className = 'toast-container position-fixed bottom-0 end-0 p-3';
      box.style.zIndex = 2100;
      document.body.appendChild(box);
    }
    const el = document.createElement('div');
    el.className = 'toast align-items-center text-bg-' + type + ' border-0 show';
    el.innerHTML = '<div class="d-flex"><div class="toast-body">' +
      String(msg).replace(/[<>&]/g, c => ({ '<': '&lt;', '>': '&gt;', '&': '&amp;' }[c])) +
      '</div><button type="button" class="btn-close btn-close-white me-2 m-auto" data-bs-dismiss="toast"></button></div>';
    box.appendChild(el);
    setTimeout(function () { el.classList.remove('show'); setTimeout(() => el.remove(), 400); }, 4200);
  };

  // ------------------------------------------------------------- Pencarian invoice (autocomplete)
  SP.invoiceSearch = function (inputEl, onPick, filterFn) {
    let timer = null;
    const box = document.createElement('div');
    box.className = 'list-group position-absolute shadow';
    box.style.cssText = 'z-index:1080;max-height:270px;overflow:auto;display:none;min-width:340px';
    inputEl.parentNode.style.position = 'relative';
    inputEl.parentNode.appendChild(box);

    inputEl.addEventListener('input', function () {
      clearTimeout(timer);
      const q = inputEl.value.trim();
      if (q.length < 2) { box.style.display = 'none'; return; }
      timer = setTimeout(function () {
        SP.get(SP.url('/invoice/cari'), { q: q, outstanding: filterFn ? 1 : 0 }).then(function (res) {
          box.innerHTML = '';
          if (!res.data || !res.data.length) {
            box.innerHTML = '<div class="list-group-item small text-muted">Tidak ada invoice yang cocok.</div>';
          }
          (res.data || []).forEach(function (row) {
            const a = document.createElement('button');
            a.type = 'button';
            a.className = 'list-group-item list-group-item-action py-1';
            a.innerHTML = '<div class="d-flex justify-content-between gap-2"><span><strong>' + row.invoice_no +
              '</strong><br><small class="text-muted">' + (row.customer_name || '-') + '</small></span>' +
              '<span class="text-end small">' + SP.rp(row.outstanding_amount) +
              '<br><span class="text-muted">JT ' + (row.due_date_fmt || '-') + '</span></span></div>';
            a.addEventListener('click', function () {
              onPick(row);
              box.style.display = 'none';
              inputEl.value = '';
            });
            box.appendChild(a);
          });
          box.style.display = 'block';
        });
      }, 280);
    });
    document.addEventListener('click', function (e) {
      if (!box.contains(e.target) && e.target !== inputEl) box.style.display = 'none';
    });
  };

  // ------------------------------------------------------------- Init
  document.addEventListener('DOMContentLoaded', function () {
    initSidebar();
    initConfirm();
    initMoneyInputs();
    initAutoFilter();
    initCheckAll();
    initColumnToggle();
    SP.chartDefaults();

    // Sembunyikan overlay saat navigasi kembali
    window.addEventListener('pageshow', function () { SP.loading(false); });

    // Tooltip Bootstrap
    if (window.bootstrap) {
      document.querySelectorAll('[data-bs-toggle="tooltip"]').forEach(el => new bootstrap.Tooltip(el));
    }

    // Tandai form yang sedang dikirim
    document.querySelectorAll('form[data-loading]').forEach(function (f) {
      f.addEventListener('submit', function () { SP.loading(true); });
    });
  });
})();
