import { Transaction, VersionedTransaction } from '@solana/web3.js';
import { close } from './close';

export enum DEVICE_TYPE {
  IOS = 'ios',
  ANDROID = 'android',
  PC = 'PC',
}

export const getUserAgent = () => {
  const ua = navigator.userAgent.toLowerCase();
  const isIos =
    /(ios|ipad|iphone)/.test(ua) ||
    (ua.indexOf('macintosh') > -1 && 'ontouchend' in document);
  const isAndroid = /android/.test(ua);
  if (isIos) {
    return DEVICE_TYPE.IOS;
  }
  if (isAndroid) {
    return DEVICE_TYPE.ANDROID;
  }
  return DEVICE_TYPE.PC;
};

const terminalType = getUserAgent();
let origin = 'https://id.fsl.com';

function initModal(or?: string) {
  if (typeof window === undefined || !document) {
    return;
  }
  if (or) origin = or;
  // 创建遮罩层
  const overlay = document.createElement('div');
  overlay.id = 'custom-modal-overlay';
  overlay.style.position = 'fixed';
  overlay.style.top = '0';
  overlay.style.left = '0';
  overlay.style.width = '100vw';
  overlay.style.height = '100vh';
  overlay.style.backgroundColor = 'rgba(0, 0, 0, 0.6)';
  overlay.style.display = 'none'; // 初始隐藏
  overlay.style.flexDirection = 'column';
  overlay.style.justifyContent = 'center';
  overlay.style.alignItems = 'center';
  overlay.style.zIndex = '2147483647';

  // 创建容器
  const modalContainer = document.createElement('div');
  let closeBtn;
  modalContainer.style.position = 'relative';
  if (terminalType === DEVICE_TYPE.PC) {
    modalContainer.style.width = '390px';
    modalContainer.style.height = '844px';
    modalContainer.style.borderRadius = '8px';
    closeBtn = document.createElement('img');
    closeBtn.style.width = '32px';
    closeBtn.style.marginTop = '28px';
    closeBtn.src = close;
    closeBtn.addEventListener('click', () => {
      window.handleMessage &&
        window.handleMessage({
          data: {
            type: 'fsl_auth',
            data: {
              message: 'User action cancellation',
            },
          },
        });
      overlay.style.display = 'none';
      iframe.src = ''; // 可选：释放 iframe 页面资源
    });
  } else {
    overlay.style.justifyContent = 'start';
    modalContainer.style.width = '100%';
    modalContainer.style.height = window.innerHeight + 'px';
    window.addEventListener('resize', () => {
      modalContainer.style.height = window.innerHeight + 'px';
    });
  }
  modalContainer.style.backgroundColor = '#fff';
  modalContainer.style.overflow = 'hidden';
  modalContainer.style.boxShadow = '0 10px 40px rgba(0,0,0,0.3)';

  // 阻止冒泡（避免点击关闭）
  modalContainer.addEventListener('click', (e) => e.stopPropagation());

  // iframe
  const iframe = document.createElement('iframe');
  iframe.id = 'custom-modal-iframe';
  iframe.style.width = '100%';
  iframe.style.height = '100%';
  iframe.style.border = 'none';
  iframe.allow = `publickey-credentials-get ${origin}; publickey-credentials-create ${origin}`;

  modalContainer.appendChild(iframe);
  overlay.appendChild(modalContainer);
  closeBtn && overlay.appendChild(closeBtn);
  document.body.appendChild(overlay);
}

const closeModal = () => {
  const overlay = document.getElementById('custom-modal-overlay');
  const iframe = document.getElementById(
    'custom-modal-iframe',
  )! as HTMLIFrameElement;
  if (overlay && iframe) {
    overlay.style.display = 'none';
    iframe.src = '';
  }
};

// 公开接口
function showModal(url: string, silent?: boolean) {
  const overlay = document.getElementById('custom-modal-overlay');
  const iframe = document.getElementById(
    'custom-modal-iframe',
  ) as HTMLIFrameElement;
  if (overlay && iframe) {
    iframe.src = url;
    !silent && (overlay.style.display = 'flex');
  }
  return iframe;
}

const bufferToTransaction = (data: any[], versions: any[]) => {
  const handledBufferStrs = data;
  const transactions: Array<VersionedTransaction | Transaction> = [];
  try {
    for (let i = 0; i < versions.length; i++) {
      if (versions[i] === 0) {
        const newTransaction = VersionedTransaction.deserialize(
          Buffer.from(handledBufferStrs[i], 'base64'),
        );
        transactions.push(newTransaction);
      } else {
        const newTransaction = Transaction.from(
          Buffer.from(handledBufferStrs[i], 'base64'),
        );
        transactions.push(newTransaction);
      }
    }
  } catch (err: any) {
    console.log(err.message);
  }
  return transactions;
};

export { terminalType, initModal, closeModal, showModal, bufferToTransaction };
