class Autofit {
  constructor(options = {}) {
    this.options = {
      designWidth: 1920,
      designHeight: 1080,
      container: '#app',
      ...options
    };
    this.container = null;
  }

  init() {
    // 获取容器元素
    this.container = document.querySelector(this.options.container);
    if (!this.container) {
      console.error(`Container ${this.options.container} not found`);
      return;
    }

    // 初始适配
    this.fit();

    // 监听窗口 resize 事件
    window.addEventListener('resize', this.fit.bind(this));
  }

  fit() {
    if (!this.container) return;

    const { designWidth, designHeight } = this.options;
    const windowWidth = window.innerWidth;
    const windowHeight = window.innerHeight;

    // 计算缩放比例
    const scaleX = windowWidth / designWidth;
    const scaleY = windowHeight / designHeight;
    const scale = Math.min(scaleX, scaleY);

    // 计算偏移量
    const offsetX = (windowWidth - designWidth * scale) / 2;
    const offsetY = (windowHeight - designHeight * scale) / 2;

    // 应用变换
    this.container.style.transform = `scale(${scale}) translate(${offsetX / scale}px, ${offsetY / scale}px)`;
    this.container.style.transformOrigin = '0 0';
    this.container.style.width = `${designWidth}px`;
    this.container.style.height = `${designHeight}px`;
    this.container.style.position = 'absolute';
    this.container.style.left = '0';
    this.container.style.top = '0';
  }

  destroy() {
    window.removeEventListener('resize', this.fit.bind(this));
  }
}

export default Autofit;