// In-game modal system — replaces all native confirm()/alert() with 60fps animated popups
// GPU-composited animations using transform + opacity only

import * as audio from './audio.js';
import * as juice from './juice.js';

let modalEl = null;
let backdropEl = null;
let resolvePromise = null;

function ensureContainer() {
  if (backdropEl) return;

  backdropEl = document.createElement('div');
  backdropEl.id = 'game-modal-backdrop';
  backdropEl.style.cssText = `
    position:fixed;inset:0;z-index:9000;
    background:rgba(0,0,0,0);
    display:none;align-items:center;justify-content:center;
    will-change:background-color;
    -webkit-tap-highlight-color:transparent;
  `;

  modalEl = document.createElement('div');
  modalEl.id = 'game-modal';
  modalEl.style.cssText = `
    will-change:transform,opacity;
    transform:scale(0.85) translateY(12px);
    opacity:0;
    max-width:320px;width:calc(100% - 48px);
    background:#1a1a2e;
    border:1px solid rgba(255,255,255,0.08);
    border-radius:20px;
    padding:28px 24px 20px;
    box-shadow:0 24px 64px rgba(0,0,0,0.7),0 0 0 1px rgba(228,172,56,0.08);
    text-align:center;
    pointer-events:auto;
  `;

  backdropEl.appendChild(modalEl);
  document.body.appendChild(backdropEl);
}

function animateIn() {
  backdropEl.style.display = 'flex';
  // Force layout to enable transition
  backdropEl.offsetHeight;

  requestAnimationFrame(() => {
    backdropEl.style.transition = 'background-color 250ms ease-out';
    backdropEl.style.backgroundColor = 'rgba(0,0,0,0.75)';

    modalEl.style.transition = 'transform 350ms cubic-bezier(0.34,1.56,0.64,1), opacity 200ms ease-out';
    modalEl.style.transform = 'scale(1) translateY(0)';
    modalEl.style.opacity = '1';
  });
}

function animateOut() {
  return new Promise(resolve => {
    backdropEl.style.transition = 'background-color 200ms ease-in';
    backdropEl.style.backgroundColor = 'rgba(0,0,0,0)';

    modalEl.style.transition = 'transform 200ms cubic-bezier(0.4,0,1,1), opacity 150ms ease-in';
    modalEl.style.transform = 'scale(0.9) translateY(8px)';
    modalEl.style.opacity = '0';

    setTimeout(() => {
      backdropEl.style.display = 'none';
      resolve();
    }, 220);
  });
}

/**
 * Show a confirmation modal (replaces native confirm())
 * Returns a Promise<boolean>
 */
export function confirm(message, options = {}) {
  const {
    title = '',
    confirmText = 'تأكيد',
    cancelText = 'إلغاء',
    confirmColor = '#E4AC38',
    danger = false,
    icon = ''
  } = options;

  ensureContainer();
  audio.play('click');

  const btnColor = danger ? '#EF4444' : confirmColor;

  modalEl.innerHTML = `
    ${icon ? `<div style="font-size:48px;margin-bottom:12px;animation:modalIconPop 400ms cubic-bezier(0.34,1.56,0.64,1) both;">${icon}</div>` : ''}
    ${title ? `<div style="font-size:18px;font-weight:800;color:#f8fafc;margin-bottom:8px;">${title}</div>` : ''}
    <div style="font-size:15px;color:#cbd5e1;line-height:1.5;margin-bottom:24px;${!title && !icon ? 'margin-top:4px;' : ''}">${message}</div>
    <div style="display:flex;gap:10px;">
      <button id="modal-cancel" style="
        flex:1;padding:14px 16px;border-radius:12px;border:1px solid rgba(255,255,255,0.1);
        background:rgba(255,255,255,0.04);color:#94a3b8;font-size:14px;font-weight:600;
        cursor:pointer;font-family:inherit;
        will-change:transform;transition:transform 100ms ease,background 100ms ease;
      ">${cancelText}</button>
      <button id="modal-confirm" style="
        flex:1;padding:14px 16px;border-radius:12px;border:none;
        background:${btnColor};color:#1a1a1a;font-size:14px;font-weight:700;
        cursor:pointer;font-family:inherit;
        will-change:transform;transition:transform 100ms ease;
      ">${confirmText}</button>
    </div>
    <style>
      @keyframes modalIconPop { from{transform:scale(0);opacity:0} to{transform:scale(1);opacity:1} }
      #modal-cancel:active { transform:scale(0.95); background:rgba(255,255,255,0.08); }
      #modal-confirm:active { transform:scale(0.95); }
    </style>
  `;

  // Reset for animation
  modalEl.style.transform = 'scale(0.85) translateY(12px)';
  modalEl.style.opacity = '0';
  animateIn();

  return new Promise(resolve => {
    resolvePromise = resolve;

    const confirmBtn = modalEl.querySelector('#modal-confirm');
    const cancelBtn = modalEl.querySelector('#modal-cancel');

    confirmBtn.addEventListener('click', async () => {
      audio.play('click');
      juice.hapticLight?.();
      await animateOut();
      resolve(true);
    });

    cancelBtn.addEventListener('click', async () => {
      audio.play('click');
      await animateOut();
      resolve(false);
    });

    // Backdrop tap = cancel
    backdropEl.addEventListener('click', async (e) => {
      if (e.target === backdropEl) {
        audio.play('click');
        await animateOut();
        resolve(false);
      }
    }, { once: true });
  });
}

/**
 * Show an alert/info modal (replaces native alert())
 * Returns a Promise<void>
 */
export function alert(message, options = {}) {
  const { title = '', buttonText = 'حسناً', icon = '' } = options;

  ensureContainer();
  audio.play('notification');

  modalEl.innerHTML = `
    ${icon ? `<div style="font-size:48px;margin-bottom:12px;animation:modalIconPop 400ms cubic-bezier(0.34,1.56,0.64,1) both;">${icon}</div>` : ''}
    ${title ? `<div style="font-size:18px;font-weight:800;color:#f8fafc;margin-bottom:8px;">${title}</div>` : ''}
    <div style="font-size:15px;color:#cbd5e1;line-height:1.5;margin-bottom:24px;">${message}</div>
    <button id="modal-ok" style="
      width:100%;padding:14px 16px;border-radius:12px;border:none;
      background:#E4AC38;color:#1a1a1a;font-size:14px;font-weight:700;
      cursor:pointer;font-family:inherit;
      will-change:transform;transition:transform 100ms ease;
    ">${buttonText}</button>
    <style>
      @keyframes modalIconPop { from{transform:scale(0);opacity:0} to{transform:scale(1);opacity:1} }
      #modal-ok:active { transform:scale(0.95); }
    </style>
  `;

  modalEl.style.transform = 'scale(0.85) translateY(12px)';
  modalEl.style.opacity = '0';
  animateIn();

  return new Promise(resolve => {
    modalEl.querySelector('#modal-ok').addEventListener('click', async () => {
      audio.play('click');
      juice.hapticLight?.();
      await animateOut();
      resolve();
    });

    backdropEl.addEventListener('click', async (e) => {
      if (e.target === backdropEl) {
        await animateOut();
        resolve();
      }
    }, { once: true });
  });
}

export function isOpen() {
  return backdropEl?.style.display === 'flex';
}
