// 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';
import { t } from './i18n.js';

let modalEl = null;
let backdropEl = null;
let resolveStack = []; // Each open modal gets its own resolve function

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:var(--bg-card);
    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 = {}) {
  // If a modal is already open, dismiss previous modals (resolve false)
  while (resolveStack.length > 0) {
    const prev = resolveStack.pop();
    prev(false);
  }

  const {
    title = '',
    confirmText = t('common.confirm'),
    cancelText = t('common.cancel'),
    confirmColor = 'var(--gold)',
    danger = false,
    icon = ''
  } = options;

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

  const btnColor = danger ? 'var(--error)' : 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:var(--text-primary);margin-bottom:8px;">${title}</div>` : ''}
    <div style="font-size:15px;color:var(--text-light);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:var(--text-secondary);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:var(--bg-dark);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 => {
    const myResolve = (val) => {
      const idx = resolveStack.indexOf(myResolve);
      if (idx !== -1) resolveStack.splice(idx, 1);
      resolve(val);
    };
    resolveStack.push(myResolve);

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

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

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

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

/**
 * Show an alert/info modal (replaces native alert())
 * Returns a Promise<void>
 */
export function alert(message, options = {}) {
  const { title = '', buttonText = t('common.ok'), 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:var(--text-primary);margin-bottom:8px;">${title}</div>` : ''}
    <div style="font-size:15px;color:var(--text-light);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:var(--gold);color:var(--bg-dark);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';
}
