/**
 * Unified Party Search Component v2
 *
 * Two ways to use:
 *
 * 1. Auto-init (HTML):
 *    <input class="party-search" data-role="locker" data-target="hiddenIdField">
 *
 * 2. Programmatic (from JS):
 *    const ps = initPartySearch('containerId', {
 *      role: 'locker',           // customer | supplier | pledge | karigar | locker | all
 *      apiBase: '../api',        // optional
 *      placeholder: '...',       // optional
 *      onSelect: function(p) {}  // callback when party selected
 *    });
 *    ps.getParty();   // returns selected party or null
 *    ps.clear();      // clear selection
 *    ps.setParty(p);  // pre-fill (for edit mode)
 */
(function () {
  'use strict';

  const API_BASE = '../api/parties';
  const DEBOUNCE_MS = 250;
  const instances = new Map();
  let modalTarget = null;

  function normApiBase(base) {
    if (!base) return API_BASE;
    base = base.replace(/\/$/, '');
    return base.endsWith('/parties') ? base : base + '/parties';
  }

  // ============ STYLES ============
  function injectStyles() {
    if (document.getElementById('ps-styles')) return;
    const s = document.createElement('style');
    s.id = 'ps-styles';
    s.textContent = `
      .ps-wrap { position: relative; }
      .ps-dropdown {
        position: absolute; top: calc(100% + 4px); left: 0; right: 0;
        background: #0F1A30; border: 1px solid #2A3550; border-radius: 10px;
        max-height: 340px; overflow-y: auto; z-index: 1000;
        box-shadow: 0 10px 30px rgba(0,0,0,0.5); display: none;
      }
      .ps-dropdown.active { display: block; }
      .ps-item { padding: 14px 16px; border-bottom: 1px solid #1A2540; cursor: pointer; }
      .ps-item:last-child { border-bottom: none; }
      .ps-item:active { background: #1A2540; }
      .ps-name { font-size: 17px; font-weight: 700; color: #F5B800; }
      .ps-meta { font-size: 14px; color: #B0B8C8; margin-top: 4px; }
      .ps-badges { display: flex; gap: 6px; margin-top: 6px; flex-wrap: wrap; }
      .ps-badge { font-size: 11px; padding: 3px 8px; border-radius: 10px; background: #1A2540; color: #B0B8C8; }
      .ps-add { padding: 16px; background: #1A2540; color: #F5B800; text-align: center; font-weight: 700; cursor: pointer; border-top: 2px solid #F5B800; }
      .ps-add:active { background: #2A3550; }
      .ps-empty { padding: 16px; text-align: center; color: #B0B8C8; }
      .ps-selected {
        padding: 10px 14px; background: #1A2540; border: 1px solid #F5B800;
        border-radius: 8px; margin-top: 8px; display: none; position: relative;
      }
      .ps-selected.show { display: block; }
      .ps-selected .ps-s-name { color: #F5B800; font-weight: 700; font-size: 15px; }
      .ps-selected .ps-s-meta { color: #B0B8C8; font-size: 13px; margin-top: 2px; }
      .ps-selected .ps-s-x {
        position: absolute; top: 8px; right: 10px; background: none; border: none;
        color: #FF6060; font-size: 20px; cursor: pointer; padding: 0; line-height: 1;
      }

      .ps-mbg { position: fixed; inset: 0; background: rgba(0,0,0,0.75); z-index: 9998; display: none; }
      .ps-mbg.active { display: block; }
      .ps-modal {
        position: fixed; top: 50%; left: 50%; transform: translate(-50%, -50%);
        background: #0F1A30; border: 1px solid #2A3550; border-radius: 14px;
        width: calc(100% - 24px); max-width: 480px; max-height: 92vh;
        overflow-y: auto; z-index: 9999; display: none;
      }
      .ps-modal.active { display: block; }
      .ps-mhead { padding: 16px; border-bottom: 1px solid #2A3550; font-size: 20px; font-weight: 700; color: #F5B800; }
      .ps-mbody { padding: 16px; }
      .ps-mbody label { display: block; font-size: 14px; color: #B0B8C8; margin: 12px 0 6px; }
      .ps-mbody input[type="text"], .ps-mbody input[type="tel"] {
        width: 100%; padding: 12px 14px; background: #080F1E; border: 1px solid #2A3550;
        border-radius: 8px; color: #FFF; font-size: 16px; box-sizing: border-box;
      }
      .ps-roles { display: grid; grid-template-columns: 1fr 1fr; gap: 8px; margin-top: 8px; }
      .ps-rchk {
        display: flex; align-items: center; gap: 10px; padding: 12px;
        background: #080F1E; border: 1px solid #2A3550; border-radius: 8px; cursor: pointer;
      }
      .ps-rchk input { width: 20px; height: 20px; margin: 0; flex-shrink: 0; }
      .ps-rchk.checked { background: #1A2540; border-color: #F5B800; }
      .ps-rchk span { font-size: 15px; color: #FFF; }
      .ps-mfoot { padding: 16px; border-top: 1px solid #2A3550; display: flex; gap: 8px; }
      .ps-btn { flex: 1; padding: 14px; border: none; border-radius: 8px; font-size: 16px; font-weight: 700; cursor: pointer; }
      .ps-bp { background: #F5B800; color: #000; }
      .ps-bs { background: #2A3550; color: #FFF; }
      .ps-err { background: #4A1A1A; color: #FF8080; padding: 12px; border-radius: 8px; margin-top: 12px; font-size: 14px; }
      .ps-ok { background: #1A4A2A; color: #80FF80; padding: 12px; border-radius: 8px; margin-top: 12px; font-size: 14px; }
    `;
    document.head.appendChild(s);
  }

  // ============ ATTACH ============
  function attach(input, opts) {
    opts = opts || {};
    if (typeof input === 'string') input = document.querySelector(input);
    if (!input || instances.has(input)) return instances.get(input) || null;

    const wrap = document.createElement('div');
    wrap.className = 'ps-wrap';
    input.parentNode.insertBefore(wrap, input);
    wrap.appendChild(input);

    const dropdown = document.createElement('div');
    dropdown.className = 'ps-dropdown';
    wrap.appendChild(dropdown);

    const inst = {
      input: input, wrap: wrap, dropdown: dropdown,
      role: opts.role || input.dataset.role || 'all',
      target: opts.target || input.dataset.target || null,
      onSelect: opts.onSelect || null,
      timer: null,
      selected: null,
      apiBase: API_BASE,
    };
    instances.set(input, inst);
    return inst;
  }

  function findByWrap(wrap) {
    for (const [, inst] of instances) if (inst.wrap === wrap) return inst;
    return null;
  }

  // ============ SEARCH ============
  async function doSearch(inst, q) {
    try {
      const url = `${inst.apiBase}/search_party.php?q=${encodeURIComponent(q)}&role=${inst.role}&limit=10`;
      const r = await fetch(url, { credentials: 'same-origin' });
      return await r.json();
    } catch (e) {
      return { success: false, parties: [] };
    }
  }

  function render(inst, data, q) {
    const dd = inst.dropdown;
    dd.innerHTML = '';
    if (data.success && data.parties.length) {
      data.parties.forEach(p => {
        const item = document.createElement('div');
        item.className = 'ps-item';
        item.dataset.party = JSON.stringify(p);
        const b = [];
        if (+p.is_customer) b.push('কাস্টমার');
        if (+p.is_supplier) b.push('সাপ্লায়ার');
        if (+p.is_pledge) b.push('বন্ধক');
        if (+p.is_karigar) b.push('কারিগর');
        if (+p.is_locker) b.push('লকার');
        item.innerHTML = `
          <div class="ps-name">${esc(p.name)}</div>
          <div class="ps-meta">${esc(p.phone || '—')} • ${esc(p.address || '—')}</div>
          <div class="ps-badges">${b.map(x => `<span class="ps-badge">${x}</span>`).join('')}</div>
        `;
        dd.appendChild(item);
      });
    } else {
      const e = document.createElement('div');
      e.className = 'ps-empty';
      e.textContent = q ? `"${q}" পাওয়া যায়নি` : 'কোনো party নেই';
      dd.appendChild(e);
    }
    const add = document.createElement('div');
    add.className = 'ps-add';
    add.textContent = q ? `+ "${q}" নামে নতুন party যোগ করুন` : `+ নতুন party যোগ করুন`;
    dd.appendChild(add);
    dd.classList.add('active');
  }

  function esc(s) { const d = document.createElement('div'); d.textContent = s == null ? '' : s; return d.innerHTML; }

  function select(inst, party) {
    inst.selected = party;
    inst.input.value = party.name;
    if (inst.target) {
      const h = document.getElementById(inst.target);
      if (h) h.value = party.id;
    }
    inst.dropdown.classList.remove('active');
    if (inst.onSelect) inst.onSelect(party);
    inst.input.dispatchEvent(new CustomEvent('party-selected', { detail: party, bubbles: true }));
  }

  // ============ MODAL ============
  function buildModal() {
    if (document.getElementById('ps-modal')) return;
    const bg = document.createElement('div');
    bg.className = 'ps-mbg'; bg.id = 'ps-mbg';
    const m = document.createElement('div');
    m.className = 'ps-modal'; m.id = 'ps-modal';
    m.innerHTML = `
      <div class="ps-mhead">+ নতুন Party</div>
      <div class="ps-mbody">
        <label>নাম <span style="color:#FF6060">*</span></label>
        <input type="text" id="ps-name" autocomplete="off">
        <label>ফোন</label>
        <input type="tel" id="ps-phone" autocomplete="off">
        <label>ঠিকানা</label>
        <input type="text" id="ps-addr" autocomplete="off">
        <label>Note</label>
        <input type="text" id="ps-note" autocomplete="off">
        <label>Role (একাধিক হতে পারে)</label>
        <div class="ps-roles">
          <label class="ps-rchk"><input type="checkbox" value="is_customer"><span>কাস্টমার</span></label>
          <label class="ps-rchk"><input type="checkbox" value="is_supplier"><span>সাপ্লায়ার</span></label>
          <label class="ps-rchk"><input type="checkbox" value="is_pledge"><span>বন্ধক</span></label>
          <label class="ps-rchk"><input type="checkbox" value="is_karigar"><span>কারিগর</span></label>
          <label class="ps-rchk"><input type="checkbox" value="is_locker"><span>লকার</span></label>
        </div>
        <div id="ps-msg"></div>
      </div>
      <div class="ps-mfoot">
        <button class="ps-btn ps-bs" id="ps-cancel">বাতিল</button>
        <button class="ps-btn ps-bp" id="ps-save">সংরক্ষণ</button>
      </div>
    `;
    document.body.appendChild(bg);
    document.body.appendChild(m);
  }

  function openModal(inst, prefill) {
    buildModal();
    modalTarget = inst;
    ['ps-name','ps-phone','ps-addr','ps-note'].forEach(id => document.getElementById(id).value = '');
    document.getElementById('ps-name').value = prefill || '';
    document.getElementById('ps-msg').innerHTML = '';
    document.querySelectorAll('.ps-rchk input').forEach(c => {
      c.checked = false;
      c.parentElement.classList.remove('checked');
    });
    if (inst.role !== 'all') {
      const chk = document.querySelector(`.ps-rchk input[value="is_${inst.role}"]`);
      if (chk) { chk.checked = true; chk.parentElement.classList.add('checked'); }
    }
    document.getElementById('ps-mbg').classList.add('active');
    document.getElementById('ps-modal').classList.add('active');
    setTimeout(() => document.getElementById('ps-name').focus(), 100);
  }

  function closeModal() {
    const bg = document.getElementById('ps-mbg');
    const md = document.getElementById('ps-modal');
    if (bg) bg.classList.remove('active');
    if (md) md.classList.remove('active');
    modalTarget = null;
  }

  async function saveNew() {
    const msg = document.getElementById('ps-msg');
    msg.innerHTML = '';
    const data = {
      name: document.getElementById('ps-name').value.trim(),
      phone: document.getElementById('ps-phone').value.trim(),
      address: document.getElementById('ps-addr').value.trim(),
      note: document.getElementById('ps-note').value.trim(),
      is_customer: 0, is_supplier: 0, is_pledge: 0, is_karigar: 0, is_locker: 0,
    };
    document.querySelectorAll('.ps-rchk input:checked').forEach(c => data[c.value] = 1);

    if (!data.name) { msg.innerHTML = '<div class="ps-err">⚠️ নাম দিতে হবে</div>'; return; }

    const btn = document.getElementById('ps-save');
    btn.disabled = true; btn.textContent = 'সংরক্ষণ হচ্ছে...';
    const base = (modalTarget && modalTarget.apiBase) ? modalTarget.apiBase : API_BASE;
    try {
      const r = await fetch(`${base}/quick_add_party.php`, {
        method: 'POST', credentials: 'same-origin',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(data)
      });
      const res = await r.json();
      if (res.success) {
        msg.innerHTML = `<div class="ps-ok">${res.message}</div>`;
        setTimeout(() => { if (modalTarget) select(modalTarget, res.party); closeModal(); }, 600);
      } else if (res.duplicate) {
        msg.innerHTML = `
          <div class="ps-err">${res.message}<br>
          <button class="ps-btn ps-bp" style="margin-top:8px;padding:8px 12px;font-size:14px"
                  onclick="PartySearch._use(${res.existing.id})">
          এই party-ই ব্যবহার করুন</button></div>`;
      } else {
        msg.innerHTML = `<div class="ps-err">${res.message || 'ত্রুটি'}</div>`;
      }
    } catch (e) {
      msg.innerHTML = `<div class="ps-err">নেটওয়ার্ক ত্রুটি</div>`;
    } finally {
      btn.disabled = false; btn.textContent = 'সংরক্ষণ';
    }
  }

  async function useExisting(id) {
    if (!modalTarget) return;
    const base = modalTarget.apiBase || API_BASE;
    const r = await fetch(`${base}/search_party.php?role=all&limit=50`, { credentials: 'same-origin' });
    const d = await r.json();
    const p = d.parties.find(x => +x.id === +id);
    if (p) { select(modalTarget, p); closeModal(); }
  }

  // ============ DOCUMENT EVENT DELEGATION ============
  document.addEventListener('input', e => {
    const inst = instances.get(e.target);
    if (!inst) return;
    clearTimeout(inst.timer);
    inst.timer = setTimeout(async () => {
      const data = await doSearch(inst, e.target.value.trim());
      render(inst, data, e.target.value.trim());
    }, DEBOUNCE_MS);
  });

  document.addEventListener('focusin', e => {
    const inst = instances.get(e.target);
    if (!inst) return;
    if (e.target.value.trim() === '') {
      doSearch(inst, '').then(d => render(inst, d, ''));
    }
  });

  document.addEventListener('click', e => {
    instances.forEach(inst => {
      if (!inst.wrap.contains(e.target)) inst.dropdown.classList.remove('active');
    });
    const item = e.target.closest('.ps-item');
    if (item) {
      const inst = findByWrap(item.closest('.ps-wrap'));
      if (inst) select(inst, JSON.parse(item.dataset.party));
      return;
    }
    if (e.target.closest('.ps-add')) {
      const inst = findByWrap(e.target.closest('.ps-wrap'));
      if (inst) openModal(inst, inst.input.value.trim());
      return;
    }
    if (e.target.id === 'ps-cancel' || e.target.id === 'ps-mbg') return closeModal();
    if (e.target.id === 'ps-save') return saveNew();
    const lbl = e.target.closest('.ps-rchk');
    if (lbl) setTimeout(() => {
      const c = lbl.querySelector('input');
      lbl.classList.toggle('checked', c.checked);
    }, 0);
  });

  // ============ AUTO-INIT (data-attribute style) ============
  function autoInit() {
    document.querySelectorAll('input.party-search').forEach(el => {
      if (!instances.has(el)) attach(el);
    });
  }

  // ============ PROGRAMMATIC API (used by lockers.js, pawn.js, etc.) ============
  window.initPartySearch = function (containerId, opts) {
    opts = opts || {};
    const container = typeof containerId === 'string'
      ? document.getElementById(containerId)
      : containerId;
    if (!container) {
      console.error('initPartySearch: container not found:', containerId);
      return null;
    }

    let input = container.querySelector('input.party-search');
    if (!input) {
      input = document.createElement('input');
      input.type = 'text';
      input.className = 'party-search';
      input.style.width = '100%';
      input.style.padding = '12px 14px';
      input.style.borderRadius = '8px';
      input.style.border = '1px solid #1e3a5f';
      input.style.background = '#0a1628';
      input.style.color = '#fff';
      input.style.fontSize = '16px';
      input.style.outline = 'none';
      input.style.boxSizing = 'border-box';
      input.placeholder = opts.placeholder || 'নাম বা ফোন দিয়ে খুঁজুন...';
      container.appendChild(input);
    } else if (opts.placeholder) {
      input.placeholder = opts.placeholder;
    }

    if (opts.role) input.dataset.role = opts.role;

    const inst = attach(input, {
      role: opts.role,
      onSelect: opts.onSelect
    });
    if (!inst) return null;

    inst.apiBase = normApiBase(opts.apiBase);

    inst.getParty = function () { return inst.selected || null; };
    inst.clear = function () {
      inst.selected = null;
      inst.input.value = '';
      if (inst.dropdown) inst.dropdown.classList.remove('active');
    };
    inst.setParty = function (party) {
      if (!party) return;
      inst.selected = party;
      inst.input.value = party.name || '';
    };

    return inst;
  };

  // Backward-compatible global
  window.PartySearch = { attach: attach, autoInit: autoInit, _use: useExisting };

  // Init
  injectStyles();
  if (document.readyState === 'loading') {
    document.addEventListener('DOMContentLoaded', autoInit);
  } else { autoInit(); }
})();