import { SCREEN_WIDTH, SCREEN_HEIGHT, SAFE_AREA_TOP, UI_BASE } from '../render';
import { BUBBLE_RADIUS, BUBBLE_COLORS, drawBubble3D, EVEN_ROW_COLS, ODD_ROW_COLS, GRID_OFFSET_X } from '../bubble/bubble';

/**
 * 欢迎页面类
 * 首页保留原背景与标题，直接展示创建/加入队伍入口
 */
export default class WelcomeScreen {
  constructor(onModeSelect) {
    this.onModeSelect = onModeSelect;
    this.visible = true;

    // 预生成背景泡泡（顶部4行装饰）
    this.bgBubbles = this._generateBgBubbles();

    // 按钮配置
    this.buttons = [
      {
        id: 'create',
        text: '创建队伍',
        icon: '👑',
        y: SCREEN_HEIGHT * 0.48,
        selected: true,
      },
      {
        id: 'join',
        text: '加入队伍',
        icon: '🔗',
        y: SCREEN_HEIGHT * 0.62,
        selected: false,
      }
    ];

    // 按钮尺寸
    this.btnWidth = UI_BASE * 0.62;
    this.btnHeight = SCREEN_HEIGHT * 0.1;

    // 绑定触摸事件
    this._bindTouch();
  }

  /**
   * 生成背景装饰泡泡（顶部4行）
   */
  _generateBgBubbles() {
    const bubbles = [];
    const rows = 4;
    const R = BUBBLE_RADIUS;
    const colorPool = [1, 2, 3, 4, 5, 6];

    for (let row = 0; row < rows; row++) {
      const cols = row % 2 === 0 ? EVEN_ROW_COLS : ODD_ROW_COLS;
      for (let col = 0; col < cols; col++) {
        const x = GRID_OFFSET_X + (row % 2 === 0
          ? col * 2 * R + R
          : col * 2 * R + 2 * R);
        const y = row * (R * Math.sqrt(3)) + R + SAFE_AREA_TOP;

        // 背景装饰球限定在当前前6种颜色顺序内
        const color = colorPool[Math.floor(Math.random() * colorPool.length)];
        bubbles.push({ x, y, color, row, col });
      }
    }
    return bubbles;
  }

  /**
   * 绑定触摸事件
   */
  _bindTouch() {
    this._touchHandler = this._onTouch.bind(this);
    wx.onTouchStart(this._touchHandler);
  }

  /**
   * 解绑触摸事件
   */
  destroy() {
    wx.offTouchStart(this._touchHandler);
  }

  /**
   * 处理触摸事件
   */
  _onTouch(e) {
    if (!this.visible) return;

    const touch = e.touches[0];
    const x = touch.clientX;
    const y = touch.clientY;

    // 检查昵称编辑按钮
    if (this._editBtnArea) {
      const { x: bx, y: by, w: bw, h: bh } = this._editBtnArea;
      if (x >= bx && x <= bx + bw && y >= by && y <= by + bh) {
        this._showEditNickname();
        return;
      }
    }

    // 检查点击了哪个按钮
    for (const btn of this.buttons) {
      const btnX = (SCREEN_WIDTH - this.btnWidth) / 2;
      const btnY = btn.y - this.btnHeight / 2;

      if (x >= btnX && x <= btnX + this.btnWidth &&
          y >= btnY && y <= btnY + this.btnHeight) {
        // 选中效果
        this.buttons.forEach(b => b.selected = false);
        btn.selected = true;

        // 延迟触发，让用户看到选中效果
        GameGlobal.setTimeout(() => {
          this.visible = false;
          this.destroy();
          if (this.onModeSelect) {
            this.onModeSelect(btn.id);
          }
        }, 150);
        break;
      }
    }
  }

  /**
   * 渲染欢迎页面
   */
  render(ctx) {
    if (!this.visible) return;

    // 1. 绘制背景泡泡
    this._renderBgBubbles(ctx);

    // 2. 绘制深色蒙层
    this._renderOverlay(ctx);

    // 3. 绘制标题
    this._renderTitle(ctx);

    // 4. 绘制按钮
    this._renderButtons(ctx);

    // 5. 绘制昵称栏
    this._renderNicknameBar(ctx);
  }

  /**
   * 绘制背景泡泡
   */
  _renderBgBubbles(ctx) {
    for (const bubble of this.bgBubbles) {
      drawBubble3D(ctx, bubble.x, bubble.y, BUBBLE_RADIUS, bubble.color);
    }
  }

  /**
   * 绘制半透明蒙层
   */
  _renderOverlay(ctx) {
    // 懒初始化缓存蒙层渐变
    if (!this._overlayGrad) {
      this._overlayGrad = ctx.createLinearGradient(0, 0, 0, SCREEN_HEIGHT);
      this._overlayGrad.addColorStop(0, 'rgba(20, 5, 40, 0.85)');
      this._overlayGrad.addColorStop(0.5, 'rgba(25, 8, 50, 0.90)');
      this._overlayGrad.addColorStop(1, 'rgba(15, 3, 30, 0.95)');
    }
    ctx.fillStyle = this._overlayGrad;
    ctx.fillRect(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT);
  }

  /**
   * 绘制标题
   */
  _renderTitle(ctx) {
    const centerX = SCREEN_WIDTH / 2;
    const titleY = SCREEN_HEIGHT * 0.22;

    // 标题阴影
    ctx.fillStyle = 'rgba(0, 0, 0, 0.5)';
    ctx.font = `bold ${UI_BASE * 0.12}px Arial`;
    ctx.textAlign = 'center';
    ctx.textBaseline = 'middle';
    ctx.fillText('伙伴泡泡', centerX + 3, titleY + 3);

    // 标题渐变（缓存）
    if (!this._titleGrad) {
      this._titleGrad = ctx.createLinearGradient(0, titleY - 30, 0, titleY + 30);
      this._titleGrad.addColorStop(0, '#FFD700');
      this._titleGrad.addColorStop(0.5, '#FFA500');
      this._titleGrad.addColorStop(1, '#FF6347');
    }

    ctx.fillStyle = this._titleGrad;
    ctx.font = `bold ${UI_BASE * 0.12}px Arial`;
    ctx.textAlign = 'center';
    ctx.textBaseline = 'middle';
    ctx.fillText('伙伴泡泡', centerX, titleY);

    // 副标题
    ctx.fillStyle = 'rgba(200, 180, 255, 0.8)';
    ctx.font = `${UI_BASE * 0.04}px Arial`;
    ctx.fillText('经典消除 · 休闲益智', centerX, titleY + SCREEN_HEIGHT * 0.07);
  }

  /**
   * 绘制模式选择按钮
   */
  _renderButtons(ctx) {
    const centerX = SCREEN_WIDTH / 2;
    const tipY = this.buttons[0].y - this.btnHeight * 1.05;

    for (const btn of this.buttons) {
      const btnX = centerX - this.btnWidth / 2;
      const btnY = btn.y - this.btnHeight / 2;

      // 按钮圆角半径
      const cornerRadius = this.btnHeight * 0.25;

      // 绘制按钮阴影
      ctx.fillStyle = 'rgba(0, 0, 0, 0.3)';
      this._drawRoundRect(ctx, btnX + 3, btnY + 3, this.btnWidth, this.btnHeight, cornerRadius);
      ctx.fill();

      // 绘制按钮背景
      if (btn.selected) {
        // 选中状态：渐变紫色（缓存）
        const cacheKey = `_btnGrad_${btn.id}`;
        if (!this[cacheKey]) {
          this[cacheKey] = ctx.createLinearGradient(0, btnY, 0, btnY + this.btnHeight);
          this[cacheKey].addColorStop(0, '#8B5CF6');
          this[cacheKey].addColorStop(0.5, '#7C3AED');
          this[cacheKey].addColorStop(1, '#6D28D9');
        }
        ctx.fillStyle = this[cacheKey];
      } else {
        // 未选中：半透明深色
        ctx.fillStyle = 'rgba(60, 40, 100, 0.7)';
      }

      this._drawRoundRect(ctx, btnX, btnY, this.btnWidth, this.btnHeight, cornerRadius);
      ctx.fill();

      // 绘制按钮边框
      ctx.strokeStyle = btn.selected ? 'rgba(167, 139, 250, 0.8)' : 'rgba(120, 100, 160, 0.5)';
      ctx.lineWidth = btn.selected ? 3 : 2;
      this._drawRoundRect(ctx, btnX, btnY, this.btnWidth, this.btnHeight, cornerRadius);
      ctx.stroke();

      // 绘制图标底
      const iconX = btnX + this.btnHeight * 0.52;
      const iconY = btn.y;
      const iconR = this.btnHeight * 0.28;
      ctx.fillStyle = btn.selected ? 'rgba(255, 255, 255, 0.2)' : 'rgba(255, 255, 255, 0.1)';
      ctx.beginPath();
      ctx.arc(iconX, iconY, iconR, 0, Math.PI * 2);
      ctx.fill();

      // 绘制图标
      ctx.fillStyle = btn.selected ? '#FFFFFF' : 'rgba(255, 255, 255, 0.75)';
      ctx.font = `${iconR * 1.2}px Arial`;
      ctx.textAlign = 'center';
      ctx.textBaseline = 'middle';
      ctx.fillText(btn.icon, iconX, iconY);

      // 绘制按钮文字
      const textX = btnX + this.btnHeight * 0.95;
      ctx.textAlign = 'left';
      ctx.fillStyle = btn.selected ? '#FFFFFF' : 'rgba(255, 255, 255, 0.84)';
      ctx.font = `bold ${UI_BASE * 0.043}px Arial`;
      ctx.fillText(btn.text, textX, btn.y);

      // 选中状态：右侧小指示器
      if (btn.selected) {
        const indicatorX = btnX + this.btnWidth - this.btnHeight * 0.38;
        ctx.fillStyle = '#FFD700';
        ctx.font = `bold ${UI_BASE * 0.053}px Arial`;
        ctx.textAlign = 'center';
        ctx.fillText('›', indicatorX, btn.y);
      }
    }

    // 按钮区提示
    ctx.fillStyle = 'rgba(170, 155, 210, 0.62)';
    ctx.font = `${UI_BASE * 0.03}px Arial`;
    ctx.textAlign = 'center';
    ctx.fillText('请选择游戏模式', centerX, tipY);
  }

  /**
   * 绘制底部昵称栏
   */
  _renderNicknameBar(ctx) {
    const nickname = GameGlobal.databus.nickname || '未设置昵称';
    const cx = SCREEN_WIDTH / 2;
    const barY = SCREEN_HEIGHT * 0.86;

    ctx.save();

    // 标签
    ctx.textAlign = 'center';
    ctx.textBaseline = 'middle';
    ctx.font = `${UI_BASE * 0.028}px Arial`;
    ctx.fillStyle = 'rgba(167, 139, 250, 0.55)';
    ctx.fillText('当前昵称', cx, barY - SCREEN_HEIGHT * 0.035);

    // 昵称与改名按钮整体居中
    ctx.font = `bold ${UI_BASE * 0.04}px Arial`;
    const nickW = ctx.measureText(nickname).width;
    const editW = 66;
    const editH = 32;
    const editR = 16;
    const gap = 12;
    const totalW = nickW + gap + editW;
    const nickX = cx - totalW / 2;
    const editX = nickX + nickW + gap;
    const editY = barY + 4 - editH / 2;

    this._editBtnArea = { x: editX, y: editY, w: editW, h: editH };

    // 昵称文字
    ctx.textAlign = 'left';
    ctx.fillStyle = 'rgba(236, 232, 255, 0.92)';
    ctx.fillText(nickname, nickX, barY + 4);

    // 改名按钮
    ctx.save();
    ctx.shadowColor = 'rgba(139, 92, 246, 0.4)';
    ctx.shadowBlur = 8;
    const bg = ctx.createLinearGradient(editX, editY, editX, editY + editH);
    bg.addColorStop(0, 'rgba(139, 92, 246, 0.75)');
    bg.addColorStop(1, 'rgba(109, 40, 217, 0.8)');
    ctx.fillStyle = bg;
    this._drawRoundRect(ctx, editX, editY, editW, editH, editR);
    ctx.fill();
    ctx.shadowBlur = 0;
    ctx.strokeStyle = 'rgba(196, 181, 253, 0.55)';
    ctx.lineWidth = 1.2;
    this._drawRoundRect(ctx, editX, editY, editW, editH, editR);
    ctx.stroke();
    ctx.restore();

    ctx.textAlign = 'center';
    ctx.textBaseline = 'middle';
    ctx.font = `bold ${UI_BASE * 0.026}px Arial`;
    ctx.fillStyle = '#FFFFFF';
    ctx.fillText('✏ 改名', editX + editW / 2, editY + editH / 2);

    ctx.restore();
  }

  /**
   * 弹出昵称修改框
   */
  _showEditNickname() {
    const current = GameGlobal.databus.nickname || '';
    wx.showModal({
      title: '修改昵称',
      content: '',
      editable: true,
      placeholderText: current || '请输入昵称（1~8字符）',
      confirmText: '确认',
      cancelText: '取消',
      success: (res) => {
        if (!res.confirm) return;
        const input = (res.content || '').trim();
        if (!input || input.length > 8) {
          wx.showToast({ title: '昵称 1~8 个字符', icon: 'error', duration: 3000 });
          return;
        }
        GameGlobal.databus.nickname = input;
        try { wx.setStorageSync('player_nickname', input); } catch (_) {}
        wx.showToast({ title: '昵称已更新', icon: 'success', duration: 1200 });
      },
    });
  }

  /**
   * 绘制圆角矩形
   */
  _drawRoundRect(ctx, x, y, width, height, radius) {
    ctx.beginPath();
    ctx.moveTo(x + radius, y);
    ctx.lineTo(x + width - radius, y);
    ctx.quadraticCurveTo(x + width, y, x + width, y + radius);
    ctx.lineTo(x + width, y + height - radius);
    ctx.quadraticCurveTo(x + width, y + height, x + width - radius, y + height);
    ctx.lineTo(x + radius, y + height);
    ctx.quadraticCurveTo(x, y + height, x, y + height - radius);
    ctx.lineTo(x, y + radius);
    ctx.quadraticCurveTo(x, y, x + radius, y);
    ctx.closePath();
  }
}
