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

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

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

/**
 * 加入房间后选择队伍页面
 * 显示 A队 / B队 两个选项
 * 构造时会查询房间队伍人数，若某队已满则按钮置灰禁用
 */
export default class JoinTeamSelectScreen {
  constructor(roomId, onSelect, onBack) {
    this.roomId = roomId;
    this.onSelect = onSelect;  // (team) => {}  team: 'A' | 'B'
    this.onBack = onBack;
    this.visible = true;

    // 队伍满员状态，查询前默认均可选
    this.teamAFull = false;
    this.teamBFull = false;
    this.teamACount = 0;
    this.teamBCount = 0;
    this.perTeamSeats = 0;
    this.loading = true;  // 查询期间显示 loading 状态

    this._initLayout();
    this._touchHandler = this._onTouch.bind(this);
    wx.onTouchStart(this._touchHandler);

    // 查询队伍人数
    this._fetchTeamInfo();
  }

  async _fetchTeamInfo() {
    try {
      const res = await api.rooms.check(this.roomId);
      if (res && res.ok) {
        this.perTeamSeats = res.perTeamSeats || 0;
        this.teamACount   = res.teamA || 0;
        this.teamBCount   = res.teamB || 0;
        this.teamAFull    = this.perTeamSeats > 0 && this.teamACount >= this.perTeamSeats;
        this.teamBFull    = this.perTeamSeats > 0 && this.teamBCount >= this.perTeamSeats;
      }
    } catch (err) {
      console.warn('[JoinTeamSelect] 查询队伍信息失败，默认允许选择:', err);
    } finally {
      this.loading = false;
    }
  }

  _initLayout() {
    const cx = SCREEN_WIDTH / 2;

    // A队按钮
    const btnW = UI_BASE * 0.7;
    const btnH = SCREEN_HEIGHT * 0.12;
    const gap = SCREEN_HEIGHT * 0.04;

    this._teamABtn = {
      x: cx - btnW / 2,
      y: SCREEN_HEIGHT * 0.38,
      w: btnW,
      h: btnH,
      r: btnH / 2,
      team: 'A'
    };

    // B队按钮
    this._teamBBtn = {
      x: cx - btnW / 2,
      y: SCREEN_HEIGHT * 0.38 + btnH + gap,
      w: btnW,
      h: btnH,
      r: btnH / 2,
      team: 'B'
    };

    // 返回按钮（左上角）
    this._backBtn = { x: 16, y: SAFE_AREA_TOP + 12, w: 72, h: 36, r: 18 };
  }

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

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

    if (this._hitRect(x, y, this._teamABtn)) {
      if (!this.teamAFull) this._selectTeam('A');
      return;
    }
    if (this._hitRect(x, y, this._teamBBtn)) {
      if (!this.teamBFull) this._selectTeam('B');
      return;
    }
    if (this._hitRect(x, y, this._backBtn)) {
      this.visible = false;
      this.destroy();
      this.onBack && this.onBack();
    }
  }

  async _selectTeam(team) {
    // 选择前先实时校验队伍是否还有空位
    try {
      const res = await api.rooms.check(this.roomId);
      if (res && res.ok) {
        this.perTeamSeats = res.perTeamSeats || 0;
        this.teamACount   = res.teamA || 0;
        this.teamBCount   = res.teamB || 0;
        this.teamAFull    = this.perTeamSeats > 0 && this.teamACount >= this.perTeamSeats;
        this.teamBFull    = this.perTeamSeats > 0 && this.teamBCount >= this.perTeamSeats;

        // 所选队伍已满，刷新按钮状态并提示
        if ((team === 'A' && this.teamAFull) || (team === 'B' && this.teamBFull)) {
          wx.showToast({ title: `${getTeamDisplayName(team)}已满，请选其他队伍`, icon: 'error', duration: 3000 });
          return;
        }
      }
    } catch (err) {
      console.warn('[JoinTeamSelect] 校验队伍失败，继续尝试加入:', err);
    }

    this.visible = false;
    this.destroy();
    this.onSelect && this.onSelect(team);
  }

  _hitRect(x, y, b) {
    return x >= b.x && x <= b.x + b.w && y >= b.y && y <= b.y + b.h;
  }

  render(ctx) {
    if (!this.visible) return;
    this._drawBg(ctx);
    this._drawTitle(ctx);
    this._drawRoomInfo(ctx);

    if (this.loading) {
      this._drawLoading(ctx);
    } else {
      this._drawTeamBtn(ctx, this._teamABtn, getTeamDisplayName('A'), '#8B5CF6', '#A78BFA', this.teamAFull, this.teamACount);
      this._drawTeamBtn(ctx, this._teamBBtn, getTeamDisplayName('B'), '#EC4899', '#F472B6', this.teamBFull, this.teamBCount);
    }

    this._drawBackBtn(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.08)';
    for (let i = 0; i < 22; i++) {
      ctx.beginPath();
      ctx.arc((i * 73) % SCREEN_WIDTH, (i * 47 + 80) % SCREEN_HEIGHT, 2 + (i % 4), 0, Math.PI * 2);
      ctx.fill();
    }
  }

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

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

    ctx.font = `bold ${UI_BASE * 0.035}px Arial`;
    ctx.fillStyle = 'rgba(167,139,250,0.65)';
    ctx.fillText('SELECT TEAM', cx, titleY - SCREEN_HEIGHT * 0.04);

    const sz = UI_BASE * 0.09;
    ctx.font = `bold ${sz}px Arial`;
    ctx.fillStyle = 'rgba(0,0,0,0.4)';
    ctx.fillText('选择队伍', cx + 2, titleY + 2);

    const tg = ctx.createLinearGradient(cx - 80, titleY - 20, cx + 80, titleY + 20);
    tg.addColorStop(0, '#C4B5FD');
    tg.addColorStop(0.5, '#A78BFA');
    tg.addColorStop(1, '#8B5CF6');
    ctx.fillStyle = tg;
    ctx.fillText('选择队伍', cx, titleY);
  }

  _drawRoomInfo(ctx) {
    const cx = SCREEN_WIDTH / 2;
    const y = SCREEN_HEIGHT * 0.28;

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

    ctx.font = `${UI_BASE * 0.032}px Arial`;
    ctx.fillStyle = 'rgba(200,180,255,0.6)';
    ctx.fillText('加入房间', cx, y);

    ctx.font = `bold ${UI_BASE * 0.12}px Arial`;
    ctx.fillStyle = '#FCD34D';
    ctx.shadowColor = 'rgba(251,191,36,0.4)';
    ctx.shadowBlur = 12;
    ctx.fillText(this.roomId, cx, y + SCREEN_HEIGHT * 0.05);
    ctx.shadowBlur = 0;
  }

  _drawLoading(ctx) {
    const cx = SCREEN_WIDTH / 2;
    const cy = SCREEN_HEIGHT * 0.52;
    ctx.textAlign = 'center';
    ctx.textBaseline = 'middle';
    ctx.font = `${UI_BASE * 0.038}px Arial`;
    ctx.fillStyle = 'rgba(196,181,253,0.6)';
    ctx.fillText('查询中...', cx, cy);
  }

  /**
   * @param {boolean} isFull  是否满员（置灰）
   * @param {number}  count   当前队伍人数
   */
  _drawTeamBtn(ctx, btn, label, colorStart, colorEnd, isFull, count) {
    const { x, y, w, h, r } = btn;
    const cx = x + w / 2;

    ctx.save();

    if (isFull) {
      // 置灰：无阴影，灰色渐变
      ctx.shadowBlur = 0;
      const bg = ctx.createLinearGradient(x, y, x + w, y);
      bg.addColorStop(0, '#4a4a5a');
      bg.addColorStop(1, '#6a6a7a');
      ctx.fillStyle = bg;
    } else {
      ctx.shadowColor = colorStart + '80';
      ctx.shadowBlur = 16;
      ctx.shadowOffsetY = 4;
      const bg = ctx.createLinearGradient(x, y, x + w, y);
      bg.addColorStop(0, colorStart);
      bg.addColorStop(1, colorEnd);
      ctx.fillStyle = bg;
    }

    this._rr(ctx, x, y, w, h, r);
    ctx.fill();
    ctx.shadowBlur = 0;
    ctx.shadowOffsetY = 0;

    // 高光（满员时不显示高光）
    if (!isFull) {
      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.textAlign = 'center';
    ctx.textBaseline = 'middle';
    ctx.font = `bold ${UI_BASE * 0.055}px Arial`;
    ctx.fillStyle = isFull ? 'rgba(255,255,255,0.35)' : '#FFFFFF';

    // 满员时在队伍名后附加"人满"提示，否则显示当前人数/上限
    if (isFull) {
      ctx.fillText(`${label}  已满`, cx, y + h / 2);
    } else {
      const countText = this.perTeamSeats > 0 ? `  ${count}/${this.perTeamSeats}` : '';
      ctx.fillText(`${label}${countText}`, cx, y + h / 2);
    }

    ctx.restore();
  }

  _drawBackBtn(ctx) {
    const { x, y, w, h, r } = this._backBtn;

    ctx.save();

    // 按钮背景
    ctx.fillStyle = 'rgba(60, 40, 100, 0.6)';
    this._rr(ctx, x, y, w, h, r);
    ctx.fill();

    // 边框
    ctx.strokeStyle = 'rgba(167, 139, 250, 0.5)';
    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 = 'rgba(221, 214, 254, 0.9)';
    ctx.fillText('< 返回', x + w / 2, 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();
  }
}
