import { SCREEN_WIDTH, SCREEN_HEIGHT, SAFE_AREA_TOP, UI_BASE } from '../render';

/**
 * 队伍选择页面
 * 多人模式时显示：创建队伍 / 加入队伍
 */
export default class TeamScreen {
  constructor(onAction) {
    this.onAction = onAction;
    this.visible = true;

    // 按钮配置
    this.buttons = [
      {
        id: 'create',
        text: '创建队伍',
        subText: '创建新房间邀请好友',
        icon: '👑',
        y: SCREEN_HEIGHT * 0.38,
        selected: true,
      },
      {
        id: 'join',
        text: '加入队伍',
        subText: '输入房间号加入游戏',
        icon: '🔗',
        y: SCREEN_HEIGHT * 0.55,
        selected: false,
      }
    ];

    // 按钮尺寸
    this.btnWidth = UI_BASE * 0.7;
    this.btnHeight = SCREEN_HEIGHT * 0.12;

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

  /**
   * 绑定触摸事件
   */
  _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._backBtnArea) {
      const { x: bx, y: by, w: bw, h: bh } = this._backBtnArea;
      if (x >= bx && x <= bx + bw && y >= by && y <= by + bh) {
        this.visible = false;
        this.destroy();
        if (this.onAction) this.onAction('back');
        return;
      }
    }

    // 检查昵称编辑按钮
    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.onAction) {
            this.onAction(btn.id);
          }
        }, 150);
        break;
      }
    }
  }

  /**
   * 渲染队伍选择页面
   */
  render(ctx) {
    if (!this.visible) return;

    // 1. 绘制深色背景
    this._renderBackground(ctx);

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

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

    // 4. 绘制返回按钮
    this._renderBackButton(ctx);

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

    // 6. 绘制底部提示
    this._renderFooter(ctx);
  }

  /**
   * 绘制背景
   */
  _renderBackground(ctx) {
    // 深紫渐变背景
    const grad = ctx.createLinearGradient(0, 0, 0, SCREEN_HEIGHT);
    grad.addColorStop(0, '#1a0f2e');
    grad.addColorStop(0.5, '#251240');
    grad.addColorStop(1, '#1a0f2e');

    ctx.fillStyle = grad;
    ctx.fillRect(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT);

    // 装饰性圆点
    ctx.fillStyle = 'rgba(139, 92, 246, 0.1)';
    for (let i = 0; i < 20; i++) {
      const x = (i * 73) % SCREEN_WIDTH;
      const y = (i * 47 + 100) % SCREEN_HEIGHT;
      const r = 2 + (i % 4);
      ctx.beginPath();
      ctx.arc(x, y, r, 0, Math.PI * 2);
      ctx.fill();
    }
  }

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

    // 多人游戏标签
    ctx.textAlign = 'center';
    ctx.textBaseline = 'middle';
    ctx.font = `bold ${UI_BASE * 0.037}px Arial`;
    ctx.fillStyle = 'rgba(167, 139, 250, 0.8)';
    ctx.fillText('MULTIPLAYER', centerX, titleY - SCREEN_HEIGHT * 0.055);

    // 主标题阴影
    ctx.fillStyle = 'rgba(0, 0, 0, 0.5)';
    ctx.font = `bold ${UI_BASE * 0.1}px Arial`;
    ctx.fillText('多人模式', centerX + 3, titleY + 3);

    // 主标题渐变
    const titleGrad = ctx.createLinearGradient(centerX - 80, titleY - 30, centerX + 80, titleY + 30);
    titleGrad.addColorStop(0, '#C4B5FD');
    titleGrad.addColorStop(0.5, '#A78BFA');
    titleGrad.addColorStop(1, '#8B5CF6');

    ctx.fillStyle = titleGrad;
    ctx.font = `bold ${UI_BASE * 0.1}px Arial`;
    ctx.fillText('多人模式', centerX, titleY);

    // 副标题
    ctx.fillStyle = 'rgba(200, 180, 255, 0.6)';
    ctx.font = `${UI_BASE * 0.035}px Arial`;
    ctx.fillText('与好友一起畅玩伙伴泡泡', centerX, titleY + SCREEN_HEIGHT * 0.06);
  }

  /**
   * 绘制按钮
   */
  _renderButtons(ctx) {
    const centerX = SCREEN_WIDTH / 2;

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

      // 圆角半径
      const cornerRadius = 16;

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

      // 绘制按钮背景
      if (btn.selected) {
        // 选中状态：渐变紫色
        const btnGrad = ctx.createLinearGradient(btnX, btnY, btnX, btnY + this.btnHeight);
        btnGrad.addColorStop(0, 'rgba(139, 92, 246, 0.95)');
        btnGrad.addColorStop(0.5, 'rgba(124, 58, 237, 0.95)');
        btnGrad.addColorStop(1, 'rgba(109, 40, 217, 0.95)');
        ctx.fillStyle = btnGrad;
      } else {
        // 未选中：半透明深色
        ctx.fillStyle = 'rgba(60, 40, 100, 0.6)';
      }

      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.4)';
      ctx.lineWidth = btn.selected ? 2.5 : 1.5;
      this._drawRoundRect(ctx, btnX, btnY, this.btnWidth, this.btnHeight, cornerRadius);
      ctx.stroke();

      // 绘制图标背景圆
      const iconX = btnX + this.btnHeight * 0.5;
      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.textAlign = 'center';
      ctx.textBaseline = 'middle';
      ctx.font = `${iconR * 1.2}px Arial`;
      ctx.fillText(btn.icon, iconX, iconY);

      // 绘制主文字
      ctx.textAlign = 'left';
      ctx.textBaseline = 'middle';
      ctx.fillStyle = btn.selected ? '#FFFFFF' : 'rgba(255, 255, 255, 0.8)';
      ctx.font = `bold ${UI_BASE * 0.045}px Arial`;
      ctx.fillText(btn.text, btnX + this.btnHeight * 0.95, btn.y - 8);

      // 绘制副标题
      ctx.fillStyle = btn.selected ? 'rgba(221, 214, 254, 0.8)' : 'rgba(180, 170, 200, 0.6)';
      ctx.font = `${UI_BASE * 0.03}px Arial`;
      ctx.fillText(btn.subText, btnX + this.btnHeight * 0.95, btn.y + 14);

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

  /**
   * 绘制返回按钮（左上角）
   */
  _renderBackButton(ctx) {
    const btnX = 16;
    const btnY = SAFE_AREA_TOP + 12;
    const btnW = 72;
    const btnH = 36;
    const r = 18;

    // 存储点击区域
    this._backBtnArea = { x: btnX, y: btnY, w: btnW, h: btnH };

    ctx.save();

    // 按钮背景
    ctx.fillStyle = 'rgba(60, 40, 100, 0.6)';
    this._drawRoundRect(ctx, btnX, btnY, btnW, btnH, r);
    ctx.fill();

    // 边框
    ctx.strokeStyle = 'rgba(167, 139, 250, 0.5)';
    ctx.lineWidth = 1.5;
    this._drawRoundRect(ctx, btnX, btnY, btnW, btnH, r);
    ctx.stroke();

    // 文字
    ctx.textAlign = 'center';
    ctx.textBaseline = 'middle';
    ctx.font = `bold ${UI_BASE * 0.035}px Arial`;
    ctx.fillStyle = 'rgba(221, 214, 254, 0.9)';
    ctx.fillText('< 返回', btnX + btnW / 2, btnY + btnH / 2);

    ctx.restore();
  }

  /**
   * 绘制昵称栏（底部显示昵称 + 编辑按钮）
   */
  _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.5)';
    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 = 52, editH = 26, editR = 13, gap = 10;
    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(221,214,254,0.9)';
    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.7)');
    bg.addColorStop(1, 'rgba(109,40,217,0.75)');
    ctx.fillStyle = bg;
    this._drawRoundRect(ctx, editX, editY, editW, editH, editR);
    ctx.fill();
    ctx.shadowBlur = 0;
    ctx.strokeStyle = 'rgba(196,181,253,0.5)';
    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.028}px Arial`;
    ctx.fillStyle = '#fff';
    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 });
      },
    });
  }

  /**
   * 绘制底部提示
   */
  _renderFooter(ctx) {
    const centerX = SCREEN_WIDTH / 2;
    const footerY = SCREEN_HEIGHT * 0.95;

    ctx.textAlign = 'center';
    ctx.textBaseline = 'middle';
    ctx.fillStyle = 'rgba(150, 140, 180, 0.4)';
    ctx.font = `${UI_BASE * 0.026}px Arial`;
    ctx.fillText('点击选择操作 · 创建或加入游戏房间', centerX, footerY);
  }

  /**
   * 绘制圆角矩形
   */
  _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();
  }
}
