/* =====================================================
   File: /ui/js/cash_party_picker_fix.js
   Purpose: Cash Entry Party Search + Quick Party Add
   Design: Pledge-style party picker
   ===================================================== */

(function () {
  'use strict';

  if (window.CASH_PARTY_PICKER_FIX_LOADED) return;
  window.CASH_PARTY_PICKER_FIX_LOADED = true;

  var API = {
    partyList: '../api/customers/party_list.php',
    partyAdd: '../api/customers/party_add.php'
  };

  var allParties = [];
  var lastSearchText = '';

  function $(id) {
    return document.getElementById(id);
  }

  function esc(v) {
    return String(v == null ? '' : v).replace(/[&<>"']/g, function (m) {
      return {
        '&': '&amp;',
        '<': '&lt;',
        '>': '&gt;',
        '"': '&quot;',
        "'": '&#039;'
      }[m];
    });
  }

  async function fetchJson(url, options) {
    options = options || {};

    var res = await fetch(url, Object.assign({
      credentials: 'same-origin',
      cache: 'no-store'
    }, options));

    var text = await res.text();

    try {
      return JSON.parse(text);
    } catch (e) {
      throw new Error(text.substring(0, 180));
    }
  }

  function getRows(data) {
    if (Array.isArray(data)) return data;

    if (data && Array.isArray(data.data)) return data.data;
    if (data && data.data && Array.isArray(data.data.parties)) return data.data.parties;
    if (data && data.data && Array.isArray(data.data.customers)) return data.data.customers;
    if (data && data.data && Array.isArray(data.data.rows)) return data.data.rows;
    if (data && data.data && Array.isArray(data.data.items)) return data.data.items;

    if (data && Array.isArray(data.parties)) return data.parties;
    if (data && Array.isArray(data.customers)) return data.customers;
    if (data && Array.isArray(data.rows)) return data.rows;
    if (data && Array.isArray(data.items)) return data.items;

    return [];
  }

  function normalizeParty(p) {
    p = p || {};

    return {
      id: p.id || p.party_id || p.customer_id || '',
      name: p.name || p.party_name || p.customer_name || p.full_name || '',
      phone: p.phone || p.mobile || p.mobile_no || p.phone_number || p.contact || '',
      address: p.address || p.location || '',
      type: p.type || p.party_type || p.category || ''
    };
  }

  function injectStyle() {
    if ($('cashPartyPickerStyle')) return;

    var style = document.createElement('style');
    style.id = 'cashPartyPickerStyle';
    style.textContent = `
      .cash-party-live-box{
        margin-top:10px;
        background:#071122;
        border:1px solid rgba(245,184,0,.45);
        border-radius:16px;
        max-height:320px;
        overflow:auto;
        display:none;
        box-shadow:0 18px 40px rgba(0,0,0,.35);
      }
      .cash-party-live-box.show{display:block}

      .cash-party-item{
        padding:16px 18px;
        border-bottom:1px solid rgba(26,45,80,.85);
        cursor:pointer;
      }
      .cash-party-item:last-child{border-bottom:0}
      .cash-party-item:active{background:rgba(245,184,0,.08)}

      .cash-party-name{
        color:#E8F0FE;
        font-size:21px;
        font-weight:900;
        line-height:1.25;
      }
      .cash-party-phone{
        color:#A8BEE4;
        font-size:16px;
        margin-top:6px;
        font-weight:800;
      }
      .cash-party-badges{
        margin-top:8px;
        display:flex;
        gap:7px;
        flex-wrap:wrap;
      }
      .cash-party-badge{
        display:inline-block;
        padding:4px 10px;
        border-radius:999px;
        background:rgba(245,184,0,.16);
        color:#F5B800;
        font-size:12px;
        font-weight:900;
      }
      .cash-party-badge.customer{
        background:rgba(79,142,247,.18);
        color:#60A5FA;
      }

      .cash-party-add-row{
        padding:17px;
        text-align:center;
        color:#34D399;
        background:rgba(16,185,129,.11);
        font-size:20px;
        font-weight:900;
        cursor:pointer;
      }

      .cash-party-selected{
        margin-top:9px;
        padding:12px 14px;
        border-radius:14px;
        background:rgba(16,185,129,.12);
        color:#34D399;
        border:1px solid rgba(16,185,129,.35);
        font-size:16px;
        font-weight:900;
        display:none;
      }
      .cash-party-selected.show{display:block}

      .cash-party-modal{
        position:fixed;
        inset:0;
        background:rgba(0,0,0,.76);
        display:none;
        align-items:center;
        justify-content:center;
        z-index:99999;
        padding:16px;
      }
      .cash-party-modal.show{display:flex}

      .cash-party-box{
        width:100%;
        max-width:430px;
        background:#0F1A30;
        border:1px solid rgba(245,184,0,.38);
        border-radius:22px;
        box-shadow:0 24px 70px rgba(0,0,0,.65);
        overflow:hidden;
      }

      .cash-party-head{
        padding:18px 20px;
        display:flex;
        align-items:center;
        justify-content:space-between;
        border-bottom:1px solid #1A2D50;
        background:rgba(255,255,255,.035);
      }
      .cash-party-title{
        color:#F5B800;
        font-size:23px;
        font-weight:900;
      }
      .cash-party-x{
        width:46px;
        height:46px;
        border-radius:14px;
        border:1px solid rgba(239,68,68,.35);
        background:rgba(239,68,68,.12);
        color:#EF4444;
        font-size:28px;
        line-height:1;
        cursor:pointer;
      }

      .cash-party-body{padding:20px}
      .cash-party-body label{
        display:block;
        color:#6F8DB5;
        font-size:17px;
        font-weight:900;
        margin-bottom:8px;
      }
      .cash-party-body input,
      .cash-party-body textarea{
        width:100%;
        background:#060E1C;
        border:1px solid #1A2D50;
        color:#E8F0FE;
        border-radius:14px;
        padding:16px;
        font-size:19px;
        font-weight:800;
        outline:none;
        margin-bottom:15px;
      }
      .cash-party-body textarea{
        min-height:95px;
        resize:vertical;
      }
      .cash-party-body input:focus,
      .cash-party-body textarea:focus{
        border-color:rgba(245,184,0,.65);
      }

      .cash-party-msg{
        min-height:24px;
        font-size:16px;
        font-weight:900;
        margin-bottom:12px;
      }

      .cash-party-actions{
        display:grid;
        grid-template-columns:1fr 1fr;
        gap:12px;
      }
      .cash-party-actions button{
        border:none;
        border-radius:15px;
        padding:16px 12px;
        font-size:20px;
        font-weight:900;
        cursor:pointer;
      }
      .cash-party-cancel{
        background:#24324F;
        color:#DBEAFE;
      }
      .cash-party-save{
        background:linear-gradient(135deg,#10B981,#059669);
        color:#fff;
      }
    `;

    document.head.appendChild(style);
  }

  function ensureUI() {
    var search = $('party_search');
    var select = $('party_id');

    if (!search || !select) return false;

    var oldBox = $('partyLiveBox');
    if (oldBox) oldBox.remove();

    var box = $('cashPartyLiveBox');
    if (!box) {
      box = document.createElement('div');
      box.id = 'cashPartyLiveBox';
      box.className = 'cash-party-live-box';
      search.insertAdjacentElement('afterend', box);
    }

    var pill = $('cashSelectedPartyPill');
    if (!pill) {
      pill = document.createElement('div');
      pill.id = 'cashSelectedPartyPill';
      pill.className = 'cash-party-selected';
      select.insertAdjacentElement('afterend', pill);
    }

    if (!$('cashQuickPartyModal')) {
      var modal = document.createElement('div');
      modal.id = 'cashQuickPartyModal';
      modal.className = 'cash-party-modal';
      modal.innerHTML =
        '<div class="cash-party-box">' +
          '<div class="cash-party-head">' +
            '<div class="cash-party-title">+ নতুন পার্টি Entry</div>' +
            '<button type="button" class="cash-party-x" id="cashPartyCloseBtn">×</button>' +
          '</div>' +
          '<div class="cash-party-body">' +
            '<label>পার্টির নাম *</label>' +
            '<input type="text" id="cashPartyName" placeholder="যেমন: হালিম">' +

            '<label>মোবাইল নাম্বার *</label>' +
            '<input type="text" id="cashPartyPhone" placeholder="যেমন: 017xxxxxxxx">' +

            '<label>ঠিকানা</label>' +
            '<textarea id="cashPartyAddress" placeholder="ঠিকানা লিখুন..."></textarea>' +

            '<div id="cashPartyMsg" class="cash-party-msg"></div>' +

            '<div class="cash-party-actions">' +
              '<button type="button" class="cash-party-cancel" id="cashPartyCancelBtn">বন্ধ</button>' +
              '<button type="button" class="cash-party-save" id="cashPartySaveBtn">সেভ করুন</button>' +
            '</div>' +
          '</div>' +
        '</div>';

      document.body.appendChild(modal);
    }

    return true;
  }

  function renderHiddenSelect(selectedId) {
    var select = $('party_id');
    if (!select) return;

    var html = '<option value="">— পার্টি নির্বাচন করুন —</option>';

    allParties.map(normalizeParty).forEach(function (p) {
      var label = p.phone ? p.name + ' — ' + p.phone : p.name;
      html += '<option value="' + esc(p.id) + '">' + esc(label) + '</option>';
    });

    select.innerHTML = html;

    if (selectedId) select.value = String(selectedId);
  }

  function renderLiveList(query) {
    query = query || '';
    lastSearchText = query;

    var box = $('cashPartyLiveBox');
    if (!box) return;

    var q = query.trim().toLowerCase();

    var rows = allParties.map(normalizeParty).filter(function (p) {
      if (!q) return true;

      return String(p.name).toLowerCase().indexOf(q) !== -1 ||
             String(p.phone).toLowerCase().indexOf(q) !== -1;
    }).slice(0, 25);

    var html = '';

    rows.forEach(function (p) {
      html +=
        '<div class="cash-party-item" data-party-id="' + esc(p.id) + '" data-party-name="' + esc(p.name) + '" data-party-phone="' + esc(p.phone) + '">' +
          '<div class="cash-party-name">' + esc(p.name || 'নাম নেই') + '</div>' +
          '<div class="cash-party-phone">📞 ' + esc(p.phone || 'মোবাইল নেই') + '</div>' +
          '<div class="cash-party-badges">' +
            '<span class="cash-party-badge customer">গ্রাহক</span>' +
            '<span class="cash-party-badge">পার্টি</span>' +
          '</div>' +
        '</div>';
    });

    if (!rows.length && q) {
      html += '<div class="cash-party-item"><div class="cash-party-name">কোনো পার্টি পাওয়া যায়নি</div><div class="cash-party-phone">নতুন পার্টি যোগ করতে নিচে চাপুন</div></div>';
    }

    html += '<div class="cash-party-add-row" id="cashPartyAddFromList">+ নতুন পার্টি যোগ করুন</div>';

    box.innerHTML = html;
    box.classList.add('show');
  }

  function selectParty(id, name, phone) {
    var select = $('party_id');
    var search = $('party_search');
    var box = $('cashPartyLiveBox');
    var pill = $('cashSelectedPartyPill');

    if (select) select.value = String(id || '');
    if (search) search.value = phone ? name + ' — ' + phone : name;

    if (pill) {
      pill.textContent = 'নির্বাচিত: ' + (phone ? name + ' — ' + phone : name);
      pill.classList.add('show');
    }

    if (box) box.classList.remove('show');
  }

  async function loadParties() {
    if (!ensureUI()) return;

    try {
      var data = await fetchJson(API.partyList);
      allParties = getRows(data);
      renderHiddenSelect();
    } catch (err) {
      console.error('Party load error:', err);
      allParties = [];
    }
  }

  function openModal(prefill) {
    prefill = prefill || lastSearchText || '';

    var modal = $('cashQuickPartyModal');
    var name = $('cashPartyName');
    var phone = $('cashPartyPhone');
    var address = $('cashPartyAddress');
    var msg = $('cashPartyMsg');

    if (!modal) return;

    name.value = '';
    phone.value = '';
    address.value = '';
    msg.textContent = '';
    msg.style.color = '';

    if (/^\d+$/.test(prefill.trim())) {
      phone.value = prefill.trim();
    } else {
      name.value = prefill.trim();
    }

    modal.classList.add('show');

    setTimeout(function () {
      if (name.value) phone.focus();
      else name.focus();
    }, 100);
  }

  function closeModal() {
    var modal = $('cashQuickPartyModal');
    if (modal) modal.classList.remove('show');
  }

  async function saveParty() {
    var name = $('cashPartyName').value.trim();
    var phone = $('cashPartyPhone').value.trim();
    var address = $('cashPartyAddress').value.trim();
    var msg = $('cashPartyMsg');

    if (!name) {
      msg.textContent = 'পার্টির নাম দিন';
      msg.style.color = '#F87171';
      return;
    }

    if (!phone) {
      msg.textContent = 'মোবাইল নাম্বার দিন';
      msg.style.color = '#F87171';
      return;
    }

    msg.textContent = 'সেভ হচ্ছে...';
    msg.style.color = '#F5B800';

    try {
      var fd = new FormData();

      fd.append('name', name);
      fd.append('party_name', name);
      fd.append('customer_name', name);

      fd.append('phone', phone);
      fd.append('mobile', phone);
      fd.append('mobile_no', phone);
      fd.append('contact', phone);

      fd.append('address', address);
      fd.append('type', 'customer');
      fd.append('party_type', 'customer');
      fd.append('status', 'active');

      var data = await fetchJson(API.partyAdd, {
        method: 'POST',
        body: fd
      });

      if (data.success || data.status || data.ok) {
        msg.textContent = 'পার্টি সফলভাবে যোগ হয়েছে';
        msg.style.color = '#34D399';

        await loadParties();

        var found = allParties.map(normalizeParty).filter(function (p) {
          return String(p.phone) === String(phone);
        })[0];

        if (found) {
          selectParty(found.id, found.name, found.phone);
        } else {
          $('party_search').value = name + ' — ' + phone;
        }

        setTimeout(closeModal, 700);
      } else {
        msg.textContent = data.message || data.error || 'পার্টি যোগ করা যায়নি';
        msg.style.color = '#F87171';
      }

    } catch (err) {
      console.error('Party add error:', err);
      msg.textContent = 'সার্ভার সমস্যা: ' + err.message;
      msg.style.color = '#F87171';
    }
  }

  function bindEvents() {
    document.addEventListener('click', function (e) {
      var item = e.target.closest('.cash-party-item');
      if (item && item.getAttribute('data-party-id')) {
        e.preventDefault();
        selectParty(
          item.getAttribute('data-party-id'),
          item.getAttribute('data-party-name'),
          item.getAttribute('data-party-phone')
        );
        return;
      }

      if (e.target.closest('#cashPartyAddFromList')) {
        e.preventDefault();
        openModal(lastSearchText);
        return;
      }

      if (e.target.closest('#cashPartyCloseBtn') || e.target.closest('#cashPartyCancelBtn')) {
        e.preventDefault();
        closeModal();
        return;
      }

      if (e.target.closest('#cashPartySaveBtn')) {
        e.preventDefault();
        saveParty();
        return;
      }

      if (e.target === $('cashQuickPartyModal')) {
        closeModal();
      }
    }, true);

    document.addEventListener('click', function (e) {
      if (e.target.closest('#quickPartyBtn')) {
        e.preventDefault();
        e.stopImmediatePropagation();
        openModal(lastSearchText);
      }

      if (e.target.closest('#party_search')) {
        renderLiveList($('party_search').value);
      }
    }, true);

    var search = $('party_search');
    if (search) {
      search.addEventListener('input', function () {
        renderLiveList(this.value);
      });

      search.addEventListener('focus', function () {
        renderLiveList(this.value);
      });
    }

    var select = $('party_id');
    if (select) {
      select.addEventListener('change', function () {
        var id = this.value;
        if (!id) return;

        var found = allParties.map(normalizeParty).filter(function (p) {
          return String(p.id) === String(id);
        })[0];

        if (found) {
          selectParty(found.id, found.name, found.phone);
        }
      });
    }
  }

  function init() {
    injectStyle();

    if (!ensureUI()) {
      setTimeout(init, 400);
      return;
    }

    bindEvents();
    loadParties();
  }

  if (document.readyState === 'loading') {
    document.addEventListener('DOMContentLoaded', init);
  } else {
    init();
  }

})();