/**
 * POS UI layer — touch/desktop modes and programmable touch keypad.
 * Persists preferences in localStorage per device.
 */
(function () {
  const STORAGE_MODE = 'pos_ui_mode';
  const STORAGE_PAD = 'pos_touch_pad_v1';

  const DEFAULT_PAD = [
    { type: 'digit', value: '7' }, { type: 'digit', value: '8' }, { type: 'digit', value: '9' }, { type: 'action', value: 'backspace' },
    { type: 'digit', value: '4' }, { type: 'digit', value: '5' }, { type: 'digit', value: '6' }, { type: 'action', value: 'clear' },
    { type: 'digit', value: '1' }, { type: 'digit', value: '2' }, { type: 'digit', value: '3' }, { type: 'amount', value: '50' },
    { type: 'digit', value: '0' }, { type: 'digit', value: '.' }, { type: 'action', value: 'exact' }, { type: 'amount', value: '100' },
    { type: 'amount', value: '20' }, { type: 'amount', value: '200' }, { type: 'amount', value: '500' }, { type: 'action', value: 'checkout' },
  ];

  let touchPadSlots = loadPad();
  let draftPad = null;

  function loadPad() {
    try {
      const raw = localStorage.getItem(STORAGE_PAD);
      if (raw) {
        const parsed = JSON.parse(raw);
        if (Array.isArray(parsed) && parsed.length) return parsed;
      }
    } catch (_) { /* ignore */ }
    return DEFAULT_PAD.map(s => ({ ...s }));
  }

  function savePad(slots) {
    touchPadSlots = slots.map(s => ({ ...s }));
    localStorage.setItem(STORAGE_PAD, JSON.stringify(touchPadSlots));
  }

  function getUiMode() {
    return localStorage.getItem(STORAGE_MODE) === 'touch' ? 'touch' : 'desktop';
  }

  function applyUiMode(mode) {
    const body = document.body;
    const isTouch = mode === 'touch';
    body.classList.toggle('pos-mode-touch', isTouch);
    body.classList.toggle('pos-mode-desktop', !isTouch);
    localStorage.setItem(STORAGE_MODE, mode);

    const desktopBtn = document.getElementById('uiModeDesktop');
    const touchBtn = document.getElementById('uiModeTouch');
    if (desktopBtn) {
      desktopBtn.classList.toggle('active', !isTouch);
      desktopBtn.setAttribute('aria-pressed', String(!isTouch));
    }
    if (touchBtn) {
      touchBtn.classList.toggle('active', isTouch);
      touchBtn.setAttribute('aria-pressed', String(isTouch));
    }

    const scan = document.getElementById('barcodeScan');
    const search = document.getElementById('productSearch');
    if (!isTouch && scan) {
      setTimeout(() => { try { scan.focus(); } catch (_) { } }, 80);
    }
    if (isTouch && search) {
      search.setAttribute('inputmode', 'search');
    }

    renderTouchPad();
    if (typeof window.posRerenderProducts === 'function') window.posRerenderProducts();
  }

  function labelForSlot(slot) {
    if (slot.type === 'digit') return slot.value;
    if (slot.type === 'amount') return '+' + slot.value;
    const map = {
      backspace: '⌫',
      clear: 'CLR',
      exact: 'Exact',
      checkout: 'Pay',
    };
    return map[slot.value] || slot.value;
  }

  function subLabelForSlot(slot) {
    if (slot.type === 'amount') return 'add';
    if (slot.type === 'action') {
      if (slot.value === 'backspace') return 'delete';
      if (slot.value === 'exact') return 'tendered';
      if (slot.value === 'checkout') return 'checkout';
    }
    return '';
  }

  function getAmountField() {
    return document.getElementById('amountTendered');
  }

  function readAmountValue() {
    const el = getAmountField();
    if (!el) return '';
    return String(el.value || '').replace(/[^\d.]/g, '');
  }

  function writeAmountValue(val) {
    const el = getAmountField();
    if (!el) return;
    el.value = val;
    el.dispatchEvent(new Event('input', { bubbles: true }));
  }

  function handlePadAction(slot) {
    const el = getAmountField();
    if (!el) return;

    if (slot.type === 'digit') {
      let cur = readAmountValue();
      if (slot.value === '.' && cur.includes('.')) return;
      if (cur === '0' && slot.value !== '.') cur = '';
      writeAmountValue(cur + slot.value);
      return;
    }

    if (slot.type === 'amount') {
      const add = parseFloat(slot.value) || 0;
      const cur = parseFloat(readAmountValue()) || 0;
      writeAmountValue(String(Math.round((cur + add) * 100) / 100));
      return;
    }

    if (slot.type === 'action') {
      if (slot.value === 'backspace') {
        writeAmountValue(readAmountValue().slice(0, -1));
      } else if (slot.value === 'clear') {
        writeAmountValue('');
      } else if (slot.value === 'exact') {
        const totalEl = document.getElementById('total');
        if (totalEl) {
          const total = parseFloat(totalEl.textContent.replace(/[^0-9.\-]/g, '')) || 0;
          writeAmountValue(String(total));
        }
      } else if (slot.value === 'checkout') {
        const btn = document.getElementById('confirmBtn');
        if (btn) btn.click();
      }
    }
  }

  function renderTouchPad() {
    const grid = document.getElementById('touchPadGrid');
    if (!grid) return;
    grid.innerHTML = '';
    if (!document.body.classList.contains('pos-mode-touch')) return;

    touchPadSlots.forEach((slot, idx) => {
      const btn = document.createElement('button');
      btn.type = 'button';
      btn.className = 'touch-pad-key';
      if (slot.type === 'action') btn.classList.add('action');
      if (slot.type === 'amount') btn.classList.add('amount');
      if (slot.value === 'checkout') btn.classList.add('wide');

      const main = document.createElement('span');
      main.textContent = labelForSlot(slot);
      btn.appendChild(main);
      const sub = subLabelForSlot(slot);
      if (sub) {
        const subEl = document.createElement('span');
        subEl.className = 'sub';
        subEl.textContent = sub;
        btn.appendChild(subEl);
      }
      btn.dataset.index = String(idx);
      btn.addEventListener('click', () => handlePadAction(slot));
      grid.appendChild(btn);
    });
  }

  function renderConfigEditor() {
    const list = document.getElementById('touchPadConfigList');
    if (!list) return;
    list.innerHTML = '';
    draftPad.forEach((slot, i) => {
      const row = document.createElement('div');
      row.className = 'touch-slot-row';

      const typeSel = document.createElement('select');
      ['digit', 'amount', 'action'].forEach(t => {
        const o = document.createElement('option');
        o.value = t;
        o.textContent = t;
        if (slot.type === t) o.selected = true;
        typeSel.appendChild(o);
      });

      const valInput = document.createElement('input');
      valInput.placeholder = 'Value';
      valInput.value = slot.value || '';

      const hint = document.createElement('span');
      hint.className = 'small text-secondary';
      hint.textContent = previewSlot(slot);

      typeSel.addEventListener('change', () => {
        slot.type = typeSel.value;
        if (slot.type === 'digit' && !slot.value) slot.value = '0';
        if (slot.type === 'amount' && !slot.value) slot.value = '10';
        if (slot.type === 'action' && !slot.value) slot.value = 'clear';
        valInput.value = slot.value;
        hint.textContent = previewSlot(slot);
      });
      valInput.addEventListener('input', () => {
        slot.value = valInput.value.trim();
        hint.textContent = previewSlot(slot);
      });

      const del = document.createElement('button');
      del.type = 'button';
      del.className = 'btn btn-sm btn-outline-danger';
      del.innerHTML = '<i class="bi bi-trash"></i>';
      del.addEventListener('click', () => {
        draftPad.splice(i, 1);
        renderConfigEditor();
      });

      row.appendChild(typeSel);
      row.appendChild(valInput);
      row.appendChild(hint);
      row.appendChild(del);
      list.appendChild(row);
    });
  }

  function previewSlot(slot) {
    return labelForSlot(slot) + (subLabelForSlot(slot) ? ' · ' + subLabelForSlot(slot) : '');
  }

  function openConfigModal() {
    draftPad = touchPadSlots.map(s => ({ ...s }));
    renderConfigEditor();
    const el = document.getElementById('touchPadConfigModal');
    if (el) new bootstrap.Modal(el).show();
  }

  function bindKeyboardShortcuts() {
    document.addEventListener('keydown', (e) => {
      if (document.body.classList.contains('pos-mode-touch')) return;
      if (e.target && (e.target.tagName === 'INPUT' || e.target.tagName === 'TEXTAREA' || e.target.tagName === 'SELECT')) {
        if (e.key !== 'F2' && e.key !== 'F9') return;
      }
      if (e.key === 'F2') {
        e.preventDefault();
        const scan = document.getElementById('barcodeScan');
        if (scan) scan.focus();
      }
      if (e.key === 'F9') {
        e.preventDefault();
        const btn = document.getElementById('confirmBtn');
        if (btn && document.getElementById('salesModePanel')?.style.display !== 'none') btn.click();
      }
    });
  }

  function init() {
    applyUiMode(getUiMode());

    document.getElementById('uiModeDesktop')?.addEventListener('click', () => applyUiMode('desktop'));
    document.getElementById('uiModeTouch')?.addEventListener('click', () => applyUiMode('touch'));

    document.getElementById('configureTouchPadBtn')?.addEventListener('click', openConfigModal);
    document.getElementById('saveTouchPadBtn')?.addEventListener('click', () => {
      savePad(draftPad);
      renderTouchPad();
      bootstrap.Modal.getInstance(document.getElementById('touchPadConfigModal'))?.hide();
    });
    document.getElementById('resetTouchPadBtn')?.addEventListener('click', () => {
      draftPad = DEFAULT_PAD.map(s => ({ ...s }));
      renderConfigEditor();
    });
    document.getElementById('addTouchPadRowBtn')?.addEventListener('click', () => {
      draftPad.push({ type: 'digit', value: '0' });
      renderConfigEditor();
    });

    bindKeyboardShortcuts();

    window.posUi = {
      getMode: getUiMode,
      setMode: applyUiMode,
      refreshTouchPad: renderTouchPad,
    };
  }

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