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

const MAX_PLAYERS = 2;
const MIN_PLAYERS = 1;

/**
 * 创建房间页面
 * 布局：  −    [ N  vs  N ]    +
 * 一对 +/- 控制两侧人数，最大 3v3
 */
export default class CreateRoomScreen {
  constructor(onConfirm, onBack) {
    this.onConfirm = onConfirm;
    this.onBack = onBack;
    this.visible = true;
    this.playerCount = 1;
    this.gameDuration = 60;

    this._initLayout();

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

  _initLayout() {
    const cx = SCREEN_WIDTH / 2;
    const btnR = UI_BASE * 0.055;

    this._cx = cx;
    this._btnR = btnR;

    // 面板
    const cardW = UI_BASE * 0.78;
    const cardH = SCREEN_HEIGHT * 0.28;
    const cardY = SCREEN_HEIGHT * 0.37;
    this._card = { x: cx - cardW / 2, y: cardY, w: cardW, h: cardH };

    // 上行：N vs N 垂直中心
    this._numRowY = cardY + cardH * 0.36;

    // 下行：+/- 按钮垂直中心
    const btnRowY = cardY + cardH * 0.76;
    this._cy = btnRowY;
    this._btnMinus = { x: cx - UI_BASE * 0.18, y: btnRowY, r: btnR };
    this._btnPlus  = { x: cx + UI_BASE * 0.18, y: btnRowY, r: btnR };

    // 确认按钮
    const cW = UI_BASE * 0.58;
    const cH = SCREEN_HEIGHT * 0.068;
    this._confirmBtn = { x: cx - cW / 2, y: SCREEN_HEIGHT * 0.72, w: cW, h: cH, r: cH / 2 };

    // 返回按钮（左上角）
    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) return;
    const { clientX: x, clientY: y } = e.touches[0];

    if (this._hitCircle(x, y, this._btnMinus)) {
      this.playerCount = Math.max(MIN_PLAYERS, this.playerCount - 1);
      return;
    }
    if (this._hitCircle(x, y, this._btnPlus)) {
      this.playerCount = Math.min(MAX_PLAYERS, this.playerCount + 1);
      return;
    }
    if (this._hitRect(x, y, this._confirmBtn)) {
      this._showDurationInput();
      return;
    }
    if (this._hitRect(x, y, this._backBtn)) {
      this.visible = false;
      this.destroy();
      this.onBack && this.onBack();
    }
  }

  _hitCircle(x, y, btn) {
    return Math.hypot(x - btn.x, y - btn.y) <= btn.r;
  }
  _hitRect(x, y, b) {
    return x >= b.x && x <= b.x + b.w && y >= b.y && y <= b.y + b.h;
  }

  _showDurationInput() {
    const current = this.gameDuration || 60;
    wx.showModal({
      title: '输入游戏时长',
      content: '',
      editable: true,
      placeholderText: `请输入秒数，如 ${current}`,
      confirmText: '确认',
      cancelText: '取消',
      success: (res) => {
        if (!res.confirm) return;

        const input = (res.content || '').trim();
        const value = input ? Number(input) : current;

        if (!/^\d+$/.test(input || String(current)) || value <= 0) {
          wx.showToast({ title: '请输入正整数秒数', icon: 'error', duration: 3000 });
          return;
        }

        if (value > 3600) {
          wx.showToast({ title: '时长请控制在3600秒内', icon: 'error', duration: 3000 });
          return;
        }

        this.gameDuration = value;
        this.visible = false;
        this.destroy();
        this.onConfirm && this.onConfirm(this.playerCount, value);
      },
    });
  }

  // ─── 渲染入口 ─────────────────────────────────────────────

  render(ctx) {
    if (!this.visible) return;
    this._drawBg(ctx);
    this._drawTitle(ctx);
    this._drawPanel(ctx);
    this._drawConfirmBtn(ctx);
    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 = this._cx;
    const titleY = SCREEN_HEIGHT * 0.2;

    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('CREATE ROOM', cx, titleY - SCREEN_HEIGHT * 0.042);

    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);

    ctx.font = `${UI_BASE * 0.032}px Arial`;
    ctx.fillStyle = 'rgba(200,180,255,0.5)';
    ctx.fillText('选择对战人数（最多 2 v 2）', cx, titleY + SCREEN_HEIGHT * 0.055);
  }

  // ─── 核心面板：上行 N vs N，下行 − + ─────────────────────

  _drawPanel(ctx) {
    const { x, y, w, h } = this._card;
    const cx      = this._cx;
    const numRowY = this._numRowY;
    const btnRowY = this._cy;
    const n       = this.playerCount;

    // ── 卡片背景 ──
    ctx.save();
    ctx.shadowColor   = 'rgba(0,0,0,0.55)';
    ctx.shadowBlur    = 24;
    ctx.shadowOffsetY = 8;
    const cg = ctx.createLinearGradient(x, y, x, y + h);
    cg.addColorStop(0, 'rgba(72,40,140,0.88)');
    cg.addColorStop(1, 'rgba(36,18,80,0.92)');
    ctx.fillStyle = cg;
    this._rr(ctx, x, y, w, h, 22);
    ctx.fill();
    ctx.shadowBlur = 0;
    ctx.strokeStyle = 'rgba(139,92,246,0.45)';
    ctx.lineWidth = 1.5;
    this._rr(ctx, x, y, w, h, 22);
    ctx.stroke();
    ctx.restore();

    // ── 上行：左数字 + vs + 右数字 ──
    const numOffX = w * 0.25;
    this._drawNumber(ctx, cx - numOffX, numRowY, n);
    this._drawVS(ctx, cx, numRowY);
    this._drawNumber(ctx, cx + numOffX, numRowY, n);

    // ── 分隔虚线 ──
    ctx.save();
    ctx.strokeStyle = 'rgba(139,92,246,0.2)';
    ctx.lineWidth = 1;
    ctx.setLineDash([4, 6]);
    ctx.beginPath();
    ctx.moveTo(x + 20, (numRowY + btnRowY) / 2);
    ctx.lineTo(x + w - 20, (numRowY + btnRowY) / 2);
    ctx.stroke();
    ctx.setLineDash([]);
    ctx.restore();

    // ── 下行：− 按钮 + 提示文字 + + 按钮 ──
    this._drawCircleBtn(ctx, this._btnMinus.x, btnRowY, this._btnR, '−', n <= MIN_PLAYERS);
    this._drawCircleBtn(ctx, this._btnPlus.x,  btnRowY, this._btnR, '+', n >= MAX_PLAYERS);

    // ── 底部提示：创建者默认在深耕队 ──
    ctx.textAlign = 'center';
    ctx.textBaseline = 'middle';
    ctx.font = `${UI_BASE * 0.03}px Arial`;
    ctx.fillStyle = 'rgba(139,92,246,0.8)';
    ctx.fillText('创建后你将加入深耕队（左侧）', cx, y + h + SCREEN_HEIGHT * 0.045);
  }

  /** 渲染单个数字（带圆形背景光晕） */
  _drawNumber(ctx, cx, cy, n) {
    const r = UI_BASE * 0.1;

    // 外发光
    ctx.save();
    ctx.shadowColor = 'rgba(139,92,246,0.6)';
    ctx.shadowBlur  = 20;

    // 圆形底盘
    const ng = ctx.createRadialGradient(cx, cy - r * 0.1, 0, cx, cy, r);
    ng.addColorStop(0, 'rgba(124,58,237,0.55)');
    ng.addColorStop(1, 'rgba(72,30,150,0.25)');
    ctx.fillStyle = ng;
    ctx.beginPath();
    ctx.arc(cx, cy, r, 0, Math.PI * 2);
    ctx.fill();

    ctx.shadowBlur = 0;

    // 圆形描边
    ctx.strokeStyle = 'rgba(167,139,250,0.5)';
    ctx.lineWidth = 2;
    ctx.beginPath();
    ctx.arc(cx, cy, r, 0, Math.PI * 2);
    ctx.stroke();
    ctx.restore();

    // 数字
    ctx.save();
    ctx.textAlign    = 'center';
    ctx.textBaseline = 'middle';
    ctx.font = `bold ${UI_BASE * 0.15}px Arial`;

    // 金色渐变
    const fg = ctx.createLinearGradient(cx, cy - 30, cx, cy + 30);
    fg.addColorStop(0, '#FDE68A');
    fg.addColorStop(0.5, '#FCD34D');
    fg.addColorStop(1, '#F59E0B');
    ctx.shadowColor = 'rgba(251,191,36,0.4)';
    ctx.shadowBlur  = 12;
    ctx.fillStyle = fg;
    ctx.fillText(String(n), cx, cy + 4);
    ctx.restore();
  }

  /** VS 分隔文字 */
  _drawVS(ctx, cx, cy) {
    ctx.save();
    ctx.textAlign    = 'center';
    ctx.textBaseline = 'middle';

    // 左右短横线
    const lineW = UI_BASE * 0.06;
    ctx.strokeStyle = 'rgba(139,92,246,0.35)';
    ctx.lineWidth = 1.5;
    ctx.beginPath();
    ctx.moveTo(cx - UI_BASE * 0.1 - lineW, cy);
    ctx.lineTo(cx - UI_BASE * 0.1, cy);
    ctx.moveTo(cx + UI_BASE * 0.1, cy);
    ctx.lineTo(cx + UI_BASE * 0.1 + lineW, cy);
    ctx.stroke();

    // VS
    const vg = ctx.createLinearGradient(cx, cy - 18, cx, cy + 18);
    vg.addColorStop(0, '#FDE68A');
    vg.addColorStop(1, '#F59E0B');
    ctx.fillStyle = vg;
    ctx.font = `bold ${UI_BASE * 0.065}px Arial`;
    ctx.shadowColor = 'rgba(251,191,36,0.35)';
    ctx.shadowBlur  = 10;
    ctx.fillText('vs', cx, cy);
    ctx.restore();
  }

  /** 圆形 +/- 按钮 */
  _drawCircleBtn(ctx, cx, cy, r, label, disabled) {
    ctx.save();

    if (!disabled) {
      ctx.shadowColor = 'rgba(139,92,246,0.55)';
      ctx.shadowBlur  = 14;
    }

    const bg = ctx.createRadialGradient(cx - r * 0.25, cy - r * 0.25, 0, cx, cy, r);
    if (disabled) {
      bg.addColorStop(0, 'rgba(70,60,95,0.6)');
      bg.addColorStop(1, 'rgba(45,35,65,0.6)');
    } else {
      bg.addColorStop(0, '#A78BFA');
      bg.addColorStop(1, '#7C3AED');
    }
    ctx.fillStyle = bg;
    ctx.beginPath();
    ctx.arc(cx, cy, r, 0, Math.PI * 2);
    ctx.fill();

    ctx.shadowBlur = 0;

    // 高光弧
    if (!disabled) {
      ctx.save();
      ctx.beginPath();
      ctx.arc(cx, cy, r, 0, Math.PI * 2);
      ctx.clip();
      const hl = ctx.createLinearGradient(cx - r, cy - r, cx + r, cy);
      hl.addColorStop(0, 'rgba(255,255,255,0.22)');
      hl.addColorStop(1, 'rgba(255,255,255,0)');
      ctx.fillStyle = hl;
      ctx.fillRect(cx - r, cy - r, r * 2, r);
      ctx.restore();
    }

    // 边框
    ctx.strokeStyle = disabled ? 'rgba(110,100,130,0.35)' : 'rgba(196,181,253,0.65)';
    ctx.lineWidth = 2;
    ctx.beginPath();
    ctx.arc(cx, cy, r, 0, Math.PI * 2);
    ctx.stroke();

    // 符号
    ctx.textAlign    = 'center';
    ctx.textBaseline = 'middle';
    ctx.font = `bold ${r * 1.05}px Arial`;
    ctx.fillStyle = disabled ? 'rgba(180,170,200,0.35)' : '#FFFFFF';
    ctx.fillText(label, cx, cy + 2);

    ctx.restore();
  }

  // ─── 确认按钮 ──────────────────────────────────────────────

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

    ctx.save();
    ctx.shadowColor = 'rgba(139,92,246,0.65)';
    ctx.shadowBlur  = 20;
    ctx.shadowOffsetY = 5;

    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.55);
    hl.addColorStop(0, 'rgba(255,255,255,0.22)');
    hl.addColorStop(1, 'rgba(255,255,255,0)');
    ctx.fillStyle = hl;
    ctx.fillRect(x, y, w, h * 0.55);
    ctx.restore();

    ctx.strokeStyle = 'rgba(196,181,253,0.55)';
    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.046}px Arial`;
    ctx.fillStyle = '#FFFFFF';
    ctx.shadowColor = 'rgba(0,0,0,0.3)';
    ctx.shadowBlur  = 4;
    ctx.fillText('确认创建', 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();
  }
}
