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

const TEAM_NAME_MAP = {
  A: '深耕队',
  B: '致远队',
};

function getTeamDisplayName(team) {
  return TEAM_NAME_MAP[team] || team;
}

/**
 * 多人模式游戏结束 - 队伍比分对比页面
 * 显示两队总分对比和每个队员的分数
 */
export default class TeamResultScreen {
  constructor({ myTeam, myPlayerId, myNickname, players, scores, onConfirm }) {
    this.myTeam = myTeam;           // 'A' | 'B'
    this.myPlayerId = myPlayerId;
    // 以本地存储的昵称为准，确保真机上一定能匹配到自己
    try { this.myNickname = wx.getStorageSync('player_nickname') || myNickname || ''; } catch (_) { this.myNickname = myNickname || ''; }
    this.players = players || [];   // 玩家列表 {playerId, nickname, team}
    this.scores = scores || {};     // 分数 {playerId: score}
    this.onConfirm = onConfirm;
    this.visible = true;
    this._frame = 0;

    // 计算队伍分数
    this._calculateTeamScores();

    // 初始化布局
    this._initLayout();

    // 触摸处理
    this._touchHandler = this._onTouch.bind(this);
    wx.onTouchStart(this._touchHandler);
  }

  _initLayout() {
    const cx = SCREEN_WIDTH / 2;
    // 确认按钮
    const btnW = UI_BASE * 0.55;
    const btnH = SCREEN_HEIGHT * 0.06;
    this._confirmBtn = {
      x: cx - btnW / 2,
      y: SCREEN_HEIGHT * 0.88,
      w: btnW,
      h: btnH,
      r: btnH / 2
    };
  }

  _calculateTeamScores() {
    this.teamAScore = 0;
    this.teamBScore = 0;
    this.teamAPlayers = [];
    this.teamBPlayers = [];

    this.players.forEach(player => {
      const score = this.scores[player.playerId] || 0;
      const playerData = { ...player, score };

      if (player.team === 'A') {
        this.teamAScore += score;
        this.teamAPlayers.push(playerData);
      } else {
        this.teamBScore += score;
        this.teamBPlayers.push(playerData);
      }
    });

    // 按分数排序
    this.teamAPlayers.sort((a, b) => b.score - a.score);
    this.teamBPlayers.sort((a, b) => b.score - a.score);

    // 判断胜负
    this.isWin = this.myTeam === 'A'
      ? this.teamAScore > this.teamBScore
      : this.teamBScore > this.teamAScore;
    this.isDraw = this.teamAScore === this.teamBScore;
  }

  /**
   * 动态更新分数（服务端广播对手分数后调用）
   * @param {Object} newScores {playerId: score}
   */
  updateScores(newScores) {
    this.scores = { ...this.scores, ...newScores };
    this._calculateTeamScores();
  }

  destroy() {
    wx.offTouchStart(this._touchHandler);
  }

  _onTouch(e) {
    if (!this.visible) return;
    const { clientX: x, clientY: y } = e.touches[0];

    // 检查是否点击按钮
    const btn = this._confirmBtn;
    if (x >= btn.x && x <= btn.x + btn.w && y >= btn.y && y <= btn.y + btn.h) {
      this.visible = false;
      this.destroy();
      this.onConfirm && this.onConfirm();
    }
  }

  update() {
    this._frame++;
  }

  render(ctx) {
    if (!this.visible) return;
    this.update();

    this._drawBg(ctx);
    this._drawTitle(ctx);
    this._drawTeamScores(ctx);
    this._drawPlayerList(ctx);
    this._drawConfirmBtn(ctx);
  }

  _drawBg(ctx) {
    // 深色背景
    const g = ctx.createLinearGradient(0, 0, 0, SCREEN_HEIGHT);
    g.addColorStop(0, '#1a0f2e');
    g.addColorStop(0.5, '#251240');
    g.addColorStop(1, '#1a0f2e');
    ctx.fillStyle = g;
    ctx.fillRect(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT);

    // 星点装饰
    ctx.fillStyle = 'rgba(139,92,246,0.09)';
    for (let i = 0; i < 24; i++) {
      ctx.beginPath();
      ctx.arc((i * 79) % SCREEN_WIDTH, (i * 53 + 60) % SCREEN_HEIGHT, 1.5 + (i % 3), 0, Math.PI * 2);
      ctx.fill();
    }
  }

  _drawTitle(ctx) {
    const cx = SCREEN_WIDTH / 2;
    const titleY = SCREEN_HEIGHT * 0.08;

    ctx.textAlign = 'center';
    ctx.textBaseline = 'middle';

    // 结果标题
    ctx.font = `bold ${UI_BASE * 0.08}px Arial`;
    const resultText = this.isDraw ? '平局!' : this.isWin ? '胜利!' : '失败!';
    const resultColor = this.isDraw ? '#FCD34D' : this.isWin ? '#10B981' : '#EF4444';

    ctx.shadowColor = resultColor + '80';
    ctx.shadowBlur = 20;
    ctx.fillStyle = resultColor;
    ctx.fillText(resultText, cx, titleY);
    ctx.shadowBlur = 0;

    // 副标题
    ctx.font = `${UI_BASE * 0.035}px Arial`;
    ctx.fillStyle = 'rgba(196,181,253,0.7)';
    ctx.fillText('队伍比分对比', cx, titleY + SCREEN_HEIGHT * 0.055);
  }

  _drawTeamScores(ctx) {
    const cx = SCREEN_WIDTH / 2;
    const cardY = SCREEN_HEIGHT * 0.16;
    const cardW = UI_BASE * 0.88;
    const cardH = SCREEN_HEIGHT * 0.18;
    const cardX = cx - cardW / 2;

    // 卡片背景
    ctx.save();
    ctx.shadowColor = 'rgba(0,0,0,0.5)';
    ctx.shadowBlur = 20;
    ctx.shadowOffsetY = 8;
    const bg = ctx.createLinearGradient(cardX, cardY, cardX, cardY + cardH);
    bg.addColorStop(0, 'rgba(72,40,140,0.9)');
    bg.addColorStop(1, 'rgba(36,18,80,0.95)');
    ctx.fillStyle = bg;
    this._rr(ctx, cardX, cardY, cardW, cardH, 16);
    ctx.fill();
    ctx.shadowBlur = 0;
    ctx.strokeStyle = 'rgba(139,92,246,0.4)';
    ctx.lineWidth = 1.5;
    this._rr(ctx, cardX, cardY, cardW, cardH, 16);
    ctx.stroke();
    ctx.restore();

    // A队分数（左侧）
    const teamAX = cardX + cardW * 0.25;
    this._drawTeamScore(ctx, teamAX, cardY + cardH / 2, 'A', this.teamAScore);

    // VS（中间）
    ctx.textAlign = 'center';
    ctx.textBaseline = 'middle';
    ctx.font = `bold ${UI_BASE * 0.06}px Arial`;
    ctx.fillStyle = 'rgba(251,191,36,0.8)';
    ctx.fillText('VS', cx, cardY + cardH / 2);

    // B队分数（右侧）
    const teamBX = cardX + cardW * 0.75;
    this._drawTeamScore(ctx, teamBX, cardY + cardH / 2, 'B', this.teamBScore);
  }

  _drawTeamScore(ctx, x, y, team, score) {
    const isTeamA = team === 'A';
    const color = isTeamA ? '#8B5CF6' : '#EC4899';
    const isMyTeam = this.myTeam === team;

    // 判断该队是否是赢家
    const isWinner = (team === 'A' && this.teamAScore > this.teamBScore)
                  || (team === 'B' && this.teamBScore > this.teamAScore);

    ctx.save();

    // 队伍标签
    ctx.textAlign = 'center';
    ctx.textBaseline = 'middle';
    ctx.font = `bold ${UI_BASE * 0.04}px Arial`;
    ctx.fillStyle = color;
    ctx.fillText(`${getTeamDisplayName(team)}${isMyTeam ? '(你)' : ''}`, x, y - SCREEN_HEIGHT * 0.035);

    // 分数（赢方金色发光，输方灰色暗淡）
    ctx.font = `bold ${UI_BASE * 0.09}px Arial`;
    if (this.isDraw || isWinner) {
      const scoreGrad = ctx.createLinearGradient(x - 40, y, x + 40, y);
      scoreGrad.addColorStop(0, '#FDE68A');
      scoreGrad.addColorStop(0.5, '#FCD34D');
      scoreGrad.addColorStop(1, '#F59E0B');
      ctx.fillStyle = scoreGrad;
      ctx.shadowColor = 'rgba(251,191,36,0.5)';
      ctx.shadowBlur = 15;
    } else {
      ctx.fillStyle = 'rgba(160,150,140,0.5)';
    }
    ctx.fillText(String(score), x, y + SCREEN_HEIGHT * 0.025);
    ctx.shadowBlur = 0;

    ctx.restore();
  }

  _drawPlayerList(ctx) {
    const cx = SCREEN_WIDTH / 2;
    const startY = SCREEN_HEIGHT * 0.38;
    const cardW = UI_BASE * 0.42;
    const cardH = SCREEN_HEIGHT * 0.45;

    // A队列表（左侧）
    this._drawTeamPlayerList(ctx, cx - cardW - 8, startY, cardW, cardH, 'A', this.teamAPlayers);

    // B队列表（右侧）
    this._drawTeamPlayerList(ctx, cx + 8, startY, cardW, cardH, 'B', this.teamBPlayers);
  }

  _drawTeamPlayerList(ctx, x, y, w, h, team, players) {
    const isTeamA = team === 'A';
    const color = isTeamA ? '#8B5CF6' : '#EC4899';
    const headerTitleY = y + 24;
    const headerDividerY = y + 40;
    const startListY = y + 72;

    // 卡片背景
    ctx.save();
    ctx.fillStyle = 'rgba(30,15,60,0.6)';
    ctx.strokeStyle = color + '60';
    ctx.lineWidth = 1.5;
    this._rr(ctx, x, y, w, h, 12);
    ctx.fill();
    ctx.stroke();
    ctx.restore();

    // 标题
    ctx.textAlign = 'center';
    ctx.textBaseline = 'middle';
    ctx.font = `bold ${UI_BASE * 0.032}px Arial`;
    ctx.fillStyle = color;
    ctx.fillText(`${getTeamDisplayName(team)}成员`, x + w / 2, headerTitleY);

    // 分割线
    ctx.strokeStyle = color + '40';
    ctx.lineWidth = 1;
    ctx.beginPath();
    ctx.moveTo(x + 10, headerDividerY);
    ctx.lineTo(x + w - 10, headerDividerY);
    ctx.stroke();

    // 玩家列表
    const rowHeight = SCREEN_HEIGHT * 0.055;

    players.forEach((player, index) => {
      const rowY = startListY + index * rowHeight;
      // 通过 playerId 精确匹配自己（昵称可能重复）
      const isMe = this.myPlayerId != null && player.playerId === this.myPlayerId;

      // 背景高亮（如果是自己）
      if (isMe) {
        ctx.save();
        ctx.fillStyle = color + '25';
        this._rr(ctx, x + 4, rowY - rowHeight / 2 + 2, w - 8, rowHeight - 4, 6);
        ctx.fill();
        ctx.restore();
      }

      // 排名
      ctx.textAlign = 'center';
      ctx.textBaseline = 'middle';
      ctx.font = `bold ${UI_BASE * 0.025}px Arial`;
      ctx.fillStyle = index === 0 ? '#FCD34D' : 'rgba(196,181,253,0.6)';
      ctx.fillText(String(index + 1), x + 18, rowY);

      // 昵称
      ctx.textAlign = 'left';
      ctx.font = `${UI_BASE * 0.024}px Arial`;
      ctx.fillStyle = isMe ? '#fff' : 'rgba(196,181,253,0.85)';
      const nickname = player.nickname || `玩家${player.playerId}`;
      const displayName = nickname.length > 6 ? nickname.slice(0, 6) + '...' : nickname;
      ctx.fillText(displayName + (isMe ? '(你)' : ''), x + 32, rowY);

      // 分数
      ctx.textAlign = 'right';
      ctx.font = `bold ${UI_BASE * 0.026}px Arial`;
      ctx.fillStyle = '#FCD34D';
      ctx.fillText(String(player.score), x + w - 12, rowY);
    });

    // 如果没有玩家，显示空状态
    if (players.length === 0) {
      ctx.textAlign = 'center';
      ctx.textBaseline = 'middle';
      ctx.font = `${UI_BASE * 0.024}px Arial`;
      ctx.fillStyle = 'rgba(196,181,253,0.4)';
      ctx.fillText('暂无数据', x + w / 2, y + h / 2);
    }
  }

  _drawConfirmBtn(ctx) {
    const { x, y, w, h, r } = this._confirmBtn;
    const cx = x + w / 2;

    // 按钮背景渐变
    ctx.save();
    ctx.shadowColor = 'rgba(139,92,246,0.5)';
    ctx.shadowBlur = 15;
    ctx.shadowOffsetY = 4;

    const bg = ctx.createLinearGradient(x, y, x + w, y);
    bg.addColorStop(0, '#8B5CF6');
    bg.addColorStop(0.5, '#7C3AED');
    bg.addColorStop(1, '#6D28D9');
    ctx.fillStyle = bg;
    this._rr(ctx, x, y, w, h, r);
    ctx.fill();

    ctx.shadowBlur = 0;

    // 顶部高光
    ctx.save();
    this._rr(ctx, x, y, w, h, r);
    ctx.clip();
    const hl = ctx.createLinearGradient(x, y, x, y + h * 0.5);
    hl.addColorStop(0, 'rgba(255,255,255,0.2)');
    hl.addColorStop(1, 'rgba(255,255,255,0)');
    ctx.fillStyle = hl;
    ctx.fillRect(x, y, w, h * 0.5);
    ctx.restore();

    // 边框
    ctx.strokeStyle = 'rgba(196,181,253,0.4)';
    ctx.lineWidth = 1.5;
    this._rr(ctx, x, y, w, h, r);
    ctx.stroke();

    // 文字
    ctx.textAlign = 'center';
    ctx.textBaseline = 'middle';
    ctx.font = `bold ${UI_BASE * 0.035}px Arial`;
    ctx.fillStyle = '#FFFFFF';
    ctx.fillText('完成', cx, y + h / 2);

    ctx.restore();
  }

  _rr(ctx, x, y, w, h, r) {
    ctx.beginPath();
    ctx.moveTo(x + r, y);
    ctx.lineTo(x + w - r, y);
    ctx.quadraticCurveTo(x + w, y, x + w, y + r);
    ctx.lineTo(x + w, y + h - r);
    ctx.quadraticCurveTo(x + w, y + h, x + w - r, y + h);
    ctx.lineTo(x + r, y + h);
    ctx.quadraticCurveTo(x, y + h, x, y + h - r);
    ctx.lineTo(x, y + r);
    ctx.quadraticCurveTo(x, y, x + r, y);
    ctx.closePath();
  }
}
