🎮ArcadeLab

♛ شطرنج آنلاین رادین عباسیان

by CrystalPanda39
2172 lines92.0 KB
▶ Play
<!DOCTYPE html>
<html lang="fa" dir="rtl">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
<meta name="theme-color" content="#0a4a8a">
<title>♛ شطرنج آنلاین رادین عباسیان</title>
<style>
  * { box-sizing: border-box; -webkit-tap-highlight-color: transparent; }
  html, body { margin: 0; padding: 0; overflow-x: hidden; font-family: Tahoma, -apple-system, sans-serif; }
  body {
    min-height: 100vh;
    background: #f5f5f5;
    color: #333;
    display: flex; flex-direction: column; align-items: center;
    -webkit-user-select: none; user-select: none;
  }
  .screen { display: none; flex-direction: column; width: 100%; max-width: 560px; min-height: 100vh; }
  .screen.active { display: flex; }

  .app-header {
    background: linear-gradient(180deg, #0a4a8a, #083a6a);
    color: #fff;
    display: flex; align-items: center; justify-content: space-between;
    padding: 10px 12px;
    font-size: 15px;
    font-weight: bold;
    box-shadow: 0 2px 8px rgba(0,0,0,.25);
    position: sticky; top: 0; z-index: 50;
  }
  .app-header .title { font-size: 16px; }
  .app-header .icons { display: flex; gap: 14px; font-size: 18px; }
  .app-header .icons span { cursor: pointer; }

  .tab-bar {
    background: linear-gradient(180deg, #0a4a8a, #083a6a);
    display: flex;
    justify-content: space-around;
    padding-bottom: 4px;
    color: #fff;
  }
  .tab-bar .tab {
    flex: 1; text-align: center;
    padding: 8px 4px 10px;
    cursor: pointer; opacity: .55;
    border-bottom: 3px solid transparent;
    transition: all .2s; font-size: 12px;
  }
  .tab-bar .tab .icon { display: block; font-size: 22px; margin-bottom: 3px; }
  .tab-bar .tab.active { opacity: 1; border-bottom-color: #ffd166; }

  .user-bar {
    background: linear-gradient(135deg, #ffd166, #f7a913);
    padding: 12px 16px;
    display: flex; align-items: center; gap: 12px;
    color: #4a2415;
  }
  .user-bar .avatar {
    width: 52px; height: 52px; border-radius: 50%;
    background: linear-gradient(135deg, #2ecc71, #27ae60);
    display: flex; align-items: center; justify-content: center;
    font-size: 26px; color: #fff;
    box-shadow: 0 3px 10px rgba(0,0,0,.25);
    border: 3px solid #fff;
  }
  .user-bar .info { flex: 1; }
  .user-bar .info .name { font-size: 15px; font-weight: bold; }
  .user-bar .info .username { font-size: 11px; color: #7a3d1f; margin-top: 2px; font-family: 'Courier New', monospace; }
  .user-bar .power { font-size: 22px; cursor: pointer; opacity: .7; }

  .content { flex: 1; background: #fff; overflow-y: auto; padding: 0 0 12px; }
  .content.gray { background: #ecf0f1; }

  .menu-item {
    background: #fff; padding: 14px 16px;
    display: flex; align-items: center; gap: 14px;
    border-bottom: 1px solid #eee;
    cursor: pointer; transition: background .15s;
  }
  .menu-item:active { background: #f9f9f9; }
  .menu-item .mi-icon { font-size: 32px; width: 44px; text-align: center; color: #f39c12; }
  .menu-item .mi-text { flex: 1; }
  .menu-item .mi-text .mi-title { font-size: 15px; font-weight: bold; color: #2c3e50; }
  .menu-item .mi-text .mi-sub { font-size: 12px; color: #7f8c8d; margin-top: 3px; }

  .section-header {
    background: linear-gradient(135deg, #ffd166, #f7a913);
    color: #4a2415; padding: 10px 16px;
    font-size: 14px; font-weight: bold;
  }
  .players-scroll {
    background: #fff; padding: 12px;
    display: flex; gap: 10px;
    overflow-x: auto; -webkit-overflow-scrolling: touch;
  }
  .player-card { min-width: 80px; text-align: center; cursor: pointer; }
  .player-card .pavatar {
    width: 60px; height: 60px;
    border-radius: 8px;
    display: flex; align-items: center; justify-content: center;
    font-size: 26px; color: #fff; font-weight: bold;
    position: relative; margin: 0 auto 4px;
    border: 2px solid #fff;
    box-shadow: 0 2px 6px rgba(0,0,0,.2);
  }
  .player-card .pavatar.green { background: linear-gradient(135deg, #2ecc71, #27ae60); }
  .player-card .pavatar.purple { background: linear-gradient(135deg, #9b59b6, #8e44ad); }
  .player-card .pavatar.red { background: linear-gradient(135deg, #e74c3c, #c0392b); }
  .player-card .pavatar.blue { background: linear-gradient(135deg, #3498db, #2980b9); }
  .player-card .pavatar.orange { background: linear-gradient(135deg, #e67e22, #d35400); }
  .player-card .pavatar .star {
    position: absolute; bottom: -6px; left: 50%;
    transform: translateX(-50%);
    background: #2c3e50; color: #ffd166;
    font-size: 10px; padding: 1px 6px;
    border-radius: 8px; font-weight: bold;
    white-space: nowrap; display: flex; align-items: center; gap: 2px;
  }
  .player-card .pname {
    font-size: 11px; color: #2c3e50; margin-top: 8px;
    font-weight: bold; overflow: hidden;
    text-overflow: ellipsis; white-space: nowrap;
    max-width: 80px; margin-left: auto; margin-right: auto;
  }

  .stats-row { display: flex; gap: 8px; padding: 12px; flex-wrap: wrap; }
  .stat-box {
    flex: 1; min-width: calc(33% - 6px);
    background: #fff; border-radius: 10px;
    padding: 10px; text-align: center;
    box-shadow: 0 2px 6px rgba(0,0,0,.08);
  }
  .stat-box .label { font-size: 11px; color: #7f8c8d; margin-bottom: 4px; }
  .stat-box .value { font-size: 20px; font-weight: bold; color: #2c3e50; }
  .stat-box .value.green { color: #27ae60; }
  .stat-box .value.red { color: #e74c3c; }
  .stat-box .value.blue { color: #2980b9; }

  .charts-row { display: flex; padding: 12px; gap: 12px; }
  .chart-box {
    flex: 1; background: #fff;
    border-radius: 10px; padding: 14px 8px;
    text-align: center;
    box-shadow: 0 2px 6px rgba(0,0,0,.08);
  }
  .chart-box .chart-title { font-size: 12px; color: #7f8c8d; margin-bottom: 10px; }
  .donut {
    width: 90px; height: 90px;
    margin: 0 auto; position: relative;
    display: flex; align-items: center; justify-content: center;
  }
  .donut svg { position: absolute; inset: 0; transform: rotate(-90deg); }
  .donut .num { font-size: 22px; font-weight: bold; color: #2c3e50; position: relative; z-index: 1; }
  .donut .num.green { color: #27ae60; }
  .donut .num.orange { color: #e67e22; }

  .store-banner {
    background: linear-gradient(135deg, #ffd166, #f7a913);
    padding: 12px 16px; font-size: 14px;
    font-weight: bold; color: #4a2415;
  }
  .store-desc {
    background: #fff; padding: 14px 16px;
    text-align: center; font-size: 13px; color: #555;
    border-bottom: 1px solid #eee; line-height: 1.6;
  }
  .store-desc .coin-count {
    display: inline-flex; align-items: center; gap: 6px;
    font-size: 15px; color: #2c3e50;
    margin-top: 8px; font-weight: bold;
  }
  .store-desc .coin-count .coin { font-size: 20px; }
  .store-grid {
    padding: 12px;
    display: grid;
    grid-template-columns: 1fr 1fr;
    gap: 10px;
  }
  .coin-pkg {
    background: #fff; border-radius: 10px;
    padding: 12px 8px; text-align: center;
    border: 2px solid #ffd166;
    cursor: pointer; transition: all .15s;
  }
  .coin-pkg:active { transform: scale(.97); }
  .coin-pkg .pkg-coins { color: #e67e22; font-size: 16px; font-weight: bold; margin-bottom: 4px; }
  .coin-pkg .pkg-price { color: #7f8c8d; font-size: 12px; }
  .coin-pkg .pkg-img { font-size: 40px; margin: 8px 0 4px; }
  .coin-pkg.free { background: linear-gradient(135deg, #2ecc71, #27ae60); border-color: #27ae60; }
  .coin-pkg.free .pkg-coins, .coin-pkg.free .pkg-price { color: #fff; }

  #game { background: radial-gradient(ellipse at top, #2a1a10 0%, #150a05 100%); color: #f5e6d3; max-width: none; }
  #game .content { background: transparent; padding: 8px; }

  .player-bar {
    width: 100%; display: flex; align-items: center; gap: 8px;
    background: rgba(0,0,0,.4); border-radius: 12px;
    padding: 6px 10px; margin: 4px 0;
    border: 2px solid rgba(255,209,102,.2);
    transition: all .3s; position: relative;
  }
  .player-bar.active { border-color: #06d6a0; box-shadow: 0 0 16px rgba(6,214,160,.6); background: rgba(6,214,160,.1); }
  .player-bar.thinking { border-color: #b980ff !important; box-shadow: 0 0 20px rgba(185,128,255,.7) !important; background: rgba(185,128,255,.1) !important; }
  .player-bar.thinking::before {
    content: '🤖 فکر می‌کنم...';
    position: absolute; top: -10px; inset-inline-start: 12px;
    background: linear-gradient(180deg, #b980ff, #6f42c1);
    color: #fff; padding: 2px 8px; border-radius: 10px;
    font-size: 10px; font-weight: bold;
    animation: badge-pulse 1s infinite;
  }
  @keyframes badge-pulse { 0%,100% { transform: scale(1); } 50% { transform: scale(1.15); } }
  .bar-chat-btn {
    background: linear-gradient(180deg, #4cc9f0, #1e7fa8);
    color: #fff; border: 2px solid #ffd166;
    border-radius: 50%; width: 38px; height: 38px; min-width: 38px;
    font-size: 18px; cursor: pointer;
    display: flex; align-items: center; justify-content: center;
    position: relative; padding: 0;
  }
  .bar-chat-btn .bar-badge {
    position: absolute; top: -4px; inset-inline-end: -4px;
    background: #ef476f; color: #fff;
    min-width: 18px; height: 18px; border-radius: 9px;
    font-size: 10px; font-weight: bold;
    display: flex; align-items: center; justify-content: center;
    padding: 0 4px;
  }
  .player-bar .info { display: flex; align-items: center; gap: 8px; flex: 1; min-width: 0; }
  .player-bar .avatar {
    width: 32px; height: 32px; min-width: 32px; border-radius: 50%;
    display: flex; align-items: center; justify-content: center; font-size: 18px;
    background: linear-gradient(180deg, #f5e6d3, #c9a961);
    color: #2b1810;
  }
  .player-bar.black .avatar { background: linear-gradient(180deg, #4a2f20, #1a0f08); color: #ffd166; }
  .player-bar.ai .avatar { background: linear-gradient(180deg, #b980ff, #6f42c1); color: #fff; }
  .player-bar .name { font-size: 13px; font-weight: bold; display: flex; align-items: center; gap: 4px; flex-wrap: wrap; color: #fff; }
  .player-bar .coins { font-size: 11px; color: #ffd166; margin-top: 2px; }
  .player-bar .coins::before { content: '🪙 '; }
  .level-badge {
    background: linear-gradient(180deg, #4cc9f0, #1e7fa8);
    color: #fff; padding: 1px 6px; border-radius: 8px;
    font-size: 10px; font-weight: bold;
  }
  .timer-wrap { display: flex; align-items: center; gap: 4px; }
  .timer {
    font-family: 'Courier New', monospace;
    font-size: 20px; font-weight: bold;
    background: rgba(0,0,0,.5); padding: 4px 8px;
    border-radius: 8px; min-width: 68px; text-align: center;
    color: #06d6a0; border: 1px solid rgba(6,214,160,.3);
  }
  .player-bar:not(.active) .timer { color: #b8956a; border-color: rgba(184,149,106,.2); background: rgba(0,0,0,.25); }
  .timer.warn { color: #ffd166 !important; border-color: #ffd166 !important; }
  .timer.critical { color: #ef476f !important; border-color: #ef476f !important; animation: pulse-t 1s infinite; }
  @keyframes pulse-t { 0%,100% { opacity: 1; } 50% { opacity: .4; } }

  #board-wrap {
    position: relative; border-radius: 12px; padding: 6px;
    background: linear-gradient(135deg, #2b1810, #5a3018 50%, #2b1810);
    box-shadow: 0 8px 30px rgba(0,0,0,.6), inset 0 0 0 3px #ffd166;
    width: 100%;
  }
  #board {
    display: grid; grid-template-columns: repeat(8, 1fr); grid-template-rows: repeat(8, 1fr);
    width: 100%; aspect-ratio: 1 / 1;
    border-radius: 6px; overflow: hidden; direction: ltr;
  }
  .cell {
    display: flex; align-items: center; justify-content: center;
    cursor: pointer; position: relative;
  }
  .cell.light { background: #f0d9b5; }
  .cell.dark  { background: #b58863; }
  .cell.selected { box-shadow: inset 0 0 0 4px #06d6a0, inset 0 0 20px #06d6a0; }
  .cell.last-move::before {
    content: ''; position: absolute; inset: 0;
    background: radial-gradient(circle, rgba(247,220,111,.6) 0%, transparent 70%);
    pointer-events: none;
  }
  .cell.check {
    background: radial-gradient(circle, #ef476f 0%, #a01340 50%, transparent 90%) !important;
    animation: check-pulse .8s infinite;
  }
  @keyframes check-pulse {
    0%,100% { box-shadow: inset 0 0 20px #ef476f; }
    50%     { box-shadow: inset 0 0 40px #ef476f; }
  }
  .cell .dot {
    position: absolute; width: 30%; height: 30%; border-radius: 50%;
    background: radial-gradient(circle at 35% 35%, #06d6a0, #04896a);
    box-shadow: 0 0 12px #06d6a0; pointer-events: none;
  }
  .cell.capture-target::after {
    content: ''; position: absolute; inset: 5%;
    border: 4px solid #ef476f; border-radius: 50%;
    box-shadow: 0 0 14px #ef476f; pointer-events: none;
  }
  .piece {
    font-size: clamp(24px, 8.5vw, 52px);
    line-height: 1; pointer-events: none;
    display: flex; align-items: center; justify-content: center;
    width: 100%; height: 100%;
    font-family: "Segoe UI Symbol", "Apple Symbols", serif;
    transition: transform .15s;
    position: relative; z-index: 1;
  }
  .piece.w {
    background: linear-gradient(180deg, #fffdf5 0%, #fef3d0 20%, #e8ce8d 45%, #c9a961 70%, #a07d30 88%, #7a5500 100%);
    -webkit-background-clip: text; background-clip: text; color: transparent;
    -webkit-text-stroke: 1.3px #4a2f20;
    filter: drop-shadow(0 1px 0 #fff8e0) drop-shadow(0 2px 0 #d4b060) drop-shadow(0 3px 0 #a8863f) drop-shadow(0 4px 2px rgba(0,0,0,.55)) drop-shadow(0 0 8px rgba(255,209,102,.4));
  }
  .piece.b {
    background: linear-gradient(180deg, #6a4a35 0%, #4a2f20 25%, #2a1810 55%, #150a05 85%, #000000 100%);
    -webkit-background-clip: text; background-clip: text; color: transparent;
    -webkit-text-stroke: 1.3px #000;
    filter: drop-shadow(0 1px 0 #4a2f20) drop-shadow(0 2px 0 #2a1810) drop-shadow(0 3px 0 #150a05) drop-shadow(0 4px 2px rgba(0,0,0,.75));
  }

  #status-bar { margin: 6px 0; font-size: 13px; font-weight: bold; color: #ffd166; min-height: 18px; text-align: center; }
  #controls-bar { display: flex; gap: 6px; flex-wrap: wrap; justify-content: center; margin-top: 4px; width: 100%; }
  #controls-bar button {
    flex: 1; min-width: 80px; max-width: 130px;
    font-family: Tahoma; font-size: 12px; font-weight: bold;
    padding: 9px 8px; border-radius: 10px; cursor: pointer;
    background: rgba(255,209,102,.1); color: #ffd166;
    border: 1px solid rgba(255,209,102,.35);
  }

  .net-status {
    display: inline-flex; align-items: center; gap: 6px;
    padding: 4px 12px; border-radius: 20px;
    font-size: 11px; font-weight: bold;
    background: rgba(6,214,160,.15); color: #06d6a0;
    border: 1px solid rgba(6,214,160,.4);
    align-self: center; margin-bottom: 4px;
  }
  .net-status.ai { background: rgba(185,128,255,.15); color: #b980ff; border-color: rgba(185,128,255,.4); }
  .net-status::before {
    content: ''; width: 6px; height: 6px; border-radius: 50%;
    background: currentColor; box-shadow: 0 0 6px currentColor;
  }

  .speech-bubble {
    position: absolute; top: -12px; inset-inline-start: 50px;
    background: #fff; color: #2b1810;
    padding: 4px 10px; border-radius: 12px;
    font-size: 12px; font-weight: bold;
    box-shadow: 0 4px 12px rgba(0,0,0,.5);
    z-index: 20; animation: bubble-in .3s;
    max-width: 180px; word-wrap: break-word;
  }
  .speech-bubble.sticker { font-size: 24px; padding: 2px 6px; }
  .speech-bubble::after {
    content: ''; position: absolute; bottom: -6px; inset-inline-start: 16px;
    width: 0; height: 0;
    border-left: 6px solid transparent;
    border-right: 6px solid transparent;
    border-top: 8px solid #fff;
  }
  @keyframes bubble-in {
    from { transform: translateY(6px) scale(.8); opacity: 0; }
    to { transform: translateY(0) scale(1); opacity: 1; }
  }

  #chat-panel {
    position: fixed; bottom: 0; left: 0; right: 0;
    height: 75vh; max-height: 600px;
    background: linear-gradient(180deg, #2a1a10, #0d0603);
    border-top: 3px solid #ffd166;
    border-radius: 20px 20px 0 0;
    transform: translateY(100%);
    transition: transform .32s cubic-bezier(.4,0,.2,1);
    z-index: 160; display: flex; flex-direction: column;
    padding: 8px 10px 10px;
    box-shadow: 0 -12px 40px rgba(0,0,0,.8);
    color: #f5e6d3;
  }
  #chat-panel.open { transform: translateY(0); }
  #chat-panel .handle {
    width: 44px; height: 4px;
    background: #ffd16655; border-radius: 3px;
    margin: 0 auto 8px; cursor: pointer;
  }
  #chat-panel .top { display: flex; justify-content: space-between; align-items: center; margin-bottom: 6px; }
  #chat-panel .top h3 { margin: 0; color: #ffd166; font-size: 14px; }
  #chat-panel .top .who { font-size: 10px; color: #b8956a; margin-top: 2px; }
  #chat-panel .close-btn {
    background: rgba(255,255,255,.08); border: 1px solid rgba(255,255,255,.15);
    color: #f5e6d3; width: 30px; height: 30px; border-radius: 50%;
    font-size: 16px; cursor: pointer;
    display: flex; align-items: center; justify-content: center; padding: 0;
  }
  #chat-feed {
    flex: 1; overflow-y: auto; background: rgba(0,0,0,.4);
    border-radius: 10px; padding: 8px; margin-bottom: 6px;
    display: flex; flex-direction: column; gap: 6px;
    min-height: 60px; -webkit-overflow-scrolling: touch;
  }
  #chat-feed:empty::after {
    content: '💬 چت را شروع کن...'; color: #b8956a;
    font-size: 12px; text-align: center; margin: auto;
  }
  .chat-msg {
    padding: 6px 12px; border-radius: 12px;
    font-size: 13px; max-width: 80%;
    word-wrap: break-word; animation: msg-pop .3s;
    line-height: 1.4;
  }
  @keyframes msg-pop {
    from { transform: translateY(8px) scale(.9); opacity: 0; }
    to { transform: translateY(0) scale(1); opacity: 1; }
  }
  .chat-msg.me { background: linear-gradient(180deg, #06d6a0, #04896a); color: #fff; align-self: flex-start; border-end-start-radius: 4px; }
  .chat-msg.them { background: linear-gradient(180deg, #4a2f20, #2b1810); color: #ffd166; align-self: flex-end; border: 1.5px solid #ffd16655; border-end-end-radius: 4px; }
  .chat-msg .sender-tag { display: block; font-size: 9px; opacity: .85; margin-bottom: 3px; font-weight: bold; }
  .chat-msg.me .sender-tag { color: #b3ffe3; }
  .chat-msg.them .sender-tag { color: #ffd166; }
  .chat-msg.sticker { font-size: 40px; background: transparent !important; padding: 2px 4px; border: none !important; }
  #chat-input-row { display: flex; gap: 6px; margin-bottom: 6px; }
  #chat-input {
    flex: 1; padding: 10px 14px; border-radius: 22px;
    border: 1px solid rgba(255,209,102,.35);
    background: rgba(0,0,0,.5); color: #f5e6d3;
    font-family: Tahoma; font-size: 14px; outline: none;
    -webkit-user-select: text; user-select: text;
  }
  #chat-input:focus { border-color: #ffd166; }
  #chat-send {
    background: linear-gradient(180deg, #4cc9f0, #1e7fa8);
    color: #fff; border: none; border-radius: 50%;
    width: 40px; height: 40px; font-size: 18px; cursor: pointer;
    display: flex; align-items: center; justify-content: center; padding: 0;
  }
  #chat-tabs { display: flex; gap: 4px; margin-bottom: 6px; }
  #chat-tabs button {
    flex: 1; padding: 7px; border-radius: 8px;
    background: rgba(255,209,102,.1); color: #ffd166;
    border: 1px solid rgba(255,209,102,.35);
    font-family: Tahoma; font-size: 12px; font-weight: bold;
    cursor: pointer;
  }
  #chat-tabs button.active { background: linear-gradient(180deg, #ffd166, #f7a913); color: #4a2415; }
  #chat-content { height: 150px; overflow-y: auto; padding-inline-end: 4px; }
  #chat-content.phrases { display: flex; flex-direction: column; gap: 5px; }
  #chat-content.phrases button {
    padding: 8px 12px; background: rgba(255,255,255,.06);
    color: #f5e6d3; border: 1px solid rgba(255,209,102,.25);
    border-radius: 8px; font-family: Tahoma; font-size: 12px;
    cursor: pointer; text-align: right;
  }
  #chat-content.stickers { display: grid; grid-template-columns: repeat(5, 1fr); gap: 5px; }
  #chat-content.stickers button {
    aspect-ratio: 1; font-size: 26px;
    background: rgba(255,255,255,.06);
    border: 1px solid rgba(255,209,102,.25);
    border-radius: 8px; cursor: pointer;
    display: flex; align-items: center; justify-content: center;
    font-family: "Segoe UI Emoji", "Apple Color Emoji", sans-serif;
    padding: 0;
  }

  .modal {
    position: fixed; inset: 0;
    background: rgba(0,0,0,.75);
    display: none; align-items: center; justify-content: center;
    z-index: 300; padding: 20px;
  }
  .modal.show { display: flex; }
  .modal .box {
    background: #fff; border-radius: 16px;
    padding: 20px; text-align: center;
    max-width: 340px; width: 100%;
    color: #333;
  }
  .modal .box h3 { margin: 0 0 14px; color: #0a4a8a; }
  .modal .box p { font-size: 13px; color: #555; line-height: 1.6; }
  .modal .box .btns { display: flex; gap: 8px; margin-top: 16px; }
  .modal .box .btns button {
    flex: 1; padding: 11px;
    border: none; border-radius: 10px;
    font-family: Tahoma; font-size: 14px; font-weight: bold;
    cursor: pointer;
  }
  .modal .box .btns .primary { background: linear-gradient(180deg, #ffd166, #f7a913); color: #4a2415; }
  .modal .box .btns .secondary { background: #ecf0f1; color: #555; }
  .modal .box .btns .danger { background: linear-gradient(180deg, #e74c3c, #c0392b); color: #fff; }

  #promo-modal .box { background: linear-gradient(135deg, #4a2415, #7a3d1f); border: 3px solid #ffd166; color: #f5e6d3; }
  #promo-modal h3 { color: #ffd166; }
  #promo-modal .opts { display: flex; gap: 8px; justify-content: center; }
  #promo-modal .opts button {
    width: 54px; height: 54px; font-size: 34px;
    cursor: pointer; background: #f5e6d3; color: #2b1810;
    border: 2px solid #b84500; border-radius: 10px;
    padding: 0;
    font-family: "Segoe UI Symbol", serif;
  }

  #result { text-align: center; background: radial-gradient(ellipse at top, #2a1a10 0%, #150a05 100%); color: #f5e6d3; max-width: none; }
  #result .big { font-size: 80px; animation: bounce 1s infinite; }
  @keyframes bounce { 0%,100% { transform: translateY(0); } 50% { transform: translateY(-16px); } }
  #result h2 { font-size: clamp(22px, 6vw, 32px); color: #ffd166; margin: 8px 0; }
  #result p { font-size: 14px; margin: 6px 0; line-height: 1.6; }
  #result .amount { color: #ffd166; font-weight: bold; font-size: 20px; }
  .btn-main {
    background: linear-gradient(180deg, #ffd166, #f7a913);
    color: #4a2415; padding: 13px 24px;
    border: none; border-radius: 12px;
    font-family: Tahoma; font-size: 15px; font-weight: bold;
    cursor: pointer; box-shadow: 0 4px 0 #b84500;
    width: 100%; max-width: 320px;
    margin: 6px auto 0; display: block;
  }

  #toast {
    position: fixed; top: 20px; left: 50%;
    transform: translateX(-50%) translateY(-100px);
    background: rgba(0,0,0,.9); color: #ffd166;
    padding: 10px 18px; border-radius: 20px;
    font-size: 13px; font-weight: bold;
    border: 1px solid #ffd16655; z-index: 500;
    pointer-events: none; opacity: 0;
    transition: all .35s; max-width: 90vw; text-align: center;
  }
  #toast.show { opacity: 1; transform: translateX(-50%) translateY(0); }

  #levelup {
    position: fixed; inset: 0;
    display: none; align-items: center; justify-content: center;
    background: radial-gradient(circle, rgba(76,201,240,.5), rgba(0,0,0,.9));
    z-index: 400; flex-direction: column; text-align: center; padding: 20px;
  }
  #levelup.show { display: flex; }
  #levelup .ring {
    width: 120px; height: 120px; border-radius: 50%;
    border: 5px solid #ffd166;
    background: radial-gradient(circle, #4cc9f0, #1e7fa8);
    display: flex; align-items: center; justify-content: center;
    font-size: 60px;
    box-shadow: 0 0 50px #ffd166;
    margin-bottom: 14px;
  }
  #levelup h2 { color: #fff; text-shadow: 0 3px 0 #1e7fa8, 0 0 25px #ffd166; }
  #levelup p { color: #ffd166; font-size: 16px; font-weight: bold; }

  .search-spinner {
    width: 70px; height: 70px;
    border: 4px solid rgba(10,74,138,.15);
    border-top-color: #0a4a8a; border-right-color: #ffd166;
    border-radius: 50%; animation: spin 1s linear infinite;
    margin: 20px auto;
  }
  @keyframes spin { to { transform: rotate(360deg); } }

  #broker-status {
    font-size: 11px;
    color: #7f8c8d;
    margin-top: 8px;
    min-height: 16px;
    text-align: center;
    padding: 0 10px;
  }

  @media (max-width: 400px) {
    .player-bar { padding: 5px 8px; gap: 6px; }
    .timer { font-size: 18px; min-width: 60px; padding: 3px 6px; }
    .bar-chat-btn { width: 34px; height: 34px; min-width: 34px; font-size: 16px; }
    .avatar { width: 28px !important; height: 28px !important; min-width: 28px !important; font-size: 16px !important; }
    .piece { font-size: clamp(22px, 9vw, 46px); }
  }
</style>
</head>
<body>

<!-- ==================== صفحه اصلی ==================== -->
<div id="home" class="screen active">
  <div class="app-header">
    <span class="icons">☰</span>
    <span class="title">♛ شطرنج آنلاین</span>
    <span class="icons"><span>🔔</span><span>⚙️</span></span>
  </div>

  <div class="tab-bar">
    <div class="tab active" data-tab="play"><span class="icon">🏠</span>بازی</div>
    <div class="tab" data-tab="records"><span class="icon">📊</span>رکوردها</div>
    <div class="tab" data-tab="store"><span class="icon">🛒</span>فروشگاه</div>
  </div>

  <div class="user-bar">
    <div class="avatar">👤</div>
    <div class="info">
      <div class="name" id="user-name">رادین عباسیان - ۳۷</div>
      <div class="username" id="user-username">username : c_radin_abbasiyan</div>
    </div>
    <div class="power" onclick="logoutConfirm()">⏻</div>
  </div>

  <div class="content" id="content-play">
    <div class="menu-item" onclick="startAIGame()">
      <div class="mi-icon">🤖</div>
      <div class="mi-text">
        <div class="mi-title">بازی یک نفره</div>
        <div class="mi-sub">بازی تک نفره با پردازنده گوشی</div>
      </div>
    </div>
    <div class="menu-item" onclick="findOnlineMatch()">
      <div class="mi-icon">🎯</div>
      <div class="mi-text">
        <div class="mi-title">بازی تصادفی</div>
        <div class="mi-sub">لیگ هفتگی — حریف ناشناس</div>
      </div>
    </div>
    <div class="menu-item" onclick="showFriendGameInfo()">
      <div class="mi-icon">👥</div>
      <div class="mi-text">
        <div class="mi-title">بازی با دوستان</div>
        <div class="mi-sub">ورودیه شش سکه — جایزه برنده دوازده سکه — بدون امتیاز</div>
      </div>
    </div>
    <div class="section-header">👥 افراد در حال بازی</div>
    <div class="players-scroll" id="players-scroll">
      <div class="player-card" onclick="challengePlayer('kamran')">
        <div class="pavatar blue">👤<span class="star">⭐ ۲۹</span></div>
        <div class="pname">kamran</div>
      </div>
      <div class="player-card" onclick="challengePlayer('talger3194')">
        <div class="pavatar purple">t<span class="star">⭐ ۱</span></div>
        <div class="pname">talger3194</div>
      </div>
      <div class="player-card" onclick="challengePlayer('قربان شاهرخی')">
        <div class="pavatar red">ق<span class="star">⭐ ۳۶</span></div>
        <div class="pname">قربان شاهرخی</div>
      </div>
      <div class="player-card" onclick="challengePlayer('shahin')">
        <div class="pavatar green">ش<span class="star">⭐ ۱۸</span></div>
        <div class="pname">shahin</div>
      </div>
      <div class="player-card" onclick="challengePlayer('ali_pro')">
        <div class="pavatar orange">a<span class="star">⭐ ۴۲</span></div>
        <div class="pname">ali_pro</div>
      </div>
      <div class="player-card" onclick="challengePlayer('sara_1990')">
        <div class="pavatar blue">s<span class="star">⭐ ۲۲</span></div>
        <div class="pname">sara_1990</div>
      </div>
    </div>
  </div>

  <div class="content gray" id="content-records" style="display:none;">
    <div class="section-header">📊 رکوردهای شما</div>
    <div class="stats-row">
      <div class="stat-box"><div class="label">امتیاز شما</div><div class="value blue" id="stat-score">۳۶۱۸</div></div>
      <div class="stat-box"><div class="label">امتیاز حریف‌ها</div><div class="value" id="stat-opp-score">۲۹۵۸</div></div>
      <div class="stat-box"><div class="label">سکه</div><div class="value" id="stat-coins">۷۲۶</div></div>
    </div>
    <div class="stats-row">
      <div class="stat-box"><div class="label">برد</div><div class="value green" id="stat-wins">۲۶۰</div></div>
      <div class="stat-box"><div class="label">باخت</div><div class="value red" id="stat-losses">۴۰۸</div></div>
      <div class="stat-box"><div class="label">تساوی</div><div class="value" id="stat-draws">۱۶</div></div>
    </div>
    <div class="stats-row">
      <div class="stat-box"><div class="label">ناقص</div><div class="value" id="stat-incomplete">۱۴۵</div></div>
      <div class="stat-box"><div class="label">مجموع بازی</div><div class="value" id="stat-total">۸۲۹</div></div>
      <div class="stat-box"><div class="label">سطح</div><div class="value blue" id="stat-level">۱</div></div>
    </div>
    <div class="charts-row">
      <div class="chart-box">
        <div class="chart-title">دیاگرام برد</div>
        <div class="donut">
          <svg viewBox="0 0 36 36">
            <circle cx="18" cy="18" r="15.9" fill="none" stroke="#ecf0f1" stroke-width="4"/>
            <circle id="win-circle" cx="18" cy="18" r="15.9" fill="none" stroke="#27ae60" stroke-width="4" stroke-dasharray="0, 100" stroke-linecap="round"/>
          </svg>
          <div class="num green" id="win-percent">۳۸</div>
        </div>
      </div>
      <div class="chart-box">
        <div class="chart-title">دیاگرام امتیازات</div>
        <div class="donut">
          <svg viewBox="0 0 36 36">
            <circle cx="18" cy="18" r="15.9" fill="none" stroke="#ecf0f1" stroke-width="4"/>
            <circle id="score-circle" cx="18" cy="18" r="15.9" fill="none" stroke="#e67e22" stroke-width="4" stroke-dasharray="0, 100" stroke-linecap="round"/>
          </svg>
          <div class="num orange" id="score-percent">۵۵</div>
        </div>
      </div>
    </div>
  </div>

  <div class="content gray" id="content-store" style="display:none;">
    <div class="section-header">🪙 خرید سکه</div>
    <div class="store-desc">
      خرید سکه برای شرکت در بازیهای آنلاین و خرید درون برنامه
      <div class="coin-count">آخرین موجودی شما: <span id="store-current-coins">۷۲۶</span> سکه <span class="coin">🪙</span></div>
    </div>
    <div class="store-grid">
      <div class="coin-pkg" onclick="buyCoins(70, 7000)"><div class="pkg-coins">۷۰ سکه</div><div class="pkg-price">۷۰۰۰ تومان</div><div class="pkg-img">🎁</div></div>
      <div class="coin-pkg" onclick="buyCoins(160, 15200)"><div class="pkg-coins">۱۶۰ سکه</div><div class="pkg-price">۱۵۲۰۰ تومان</div><div class="pkg-img">📦</div></div>
      <div class="coin-pkg" onclick="buyCoins(300, 27000)"><div class="pkg-coins">۳۰۰ سکه</div><div class="pkg-price">۲۷۰۰۰ تومان</div><div class="pkg-img">💎</div></div>
      <div class="coin-pkg" onclick="buyCoins(450, 38250)"><div class="pkg-coins">۴۵۰ سکه</div><div class="pkg-price">۳۸۲۵۰ تومان</div><div class="pkg-img">👑</div></div>
      <div class="coin-pkg" onclick="buyCoins(600, 48000)"><div class="pkg-coins">۶۰۰ سکه</div><div class="pkg-price">۴۸۰۰۰ تومان</div><div class="pkg-img">🏆</div></div>
      <div class="coin-pkg free" onclick="freeCoins()"><div class="pkg-coins">سکه رایگان</div><div class="pkg-price">تماشای ویدیو</div><div class="pkg-img">🎬</div></div>
    </div>
  </div>
</div>

<!-- ==================== صفحه بازی ==================== -->
<div id="game" class="screen">
  <div class="app-header">
    <span class="icons" onclick="backToSetup()">←</span>
    <span class="title" id="game-title">♛ بازی</span>
    <span class="icons">⚙️</span>
  </div>
  <div class="content">
    <div class="net-status" id="net-status" style="display:none;">آنلاین</div>
    <div class="player-bar black" id="bar-black">
      <button class="bar-chat-btn" onclick="toggleChat()">💬<span class="bar-badge" id="badge-black" style="display:none;">۰</span></button>
      <div class="info">
        <div class="avatar" id="avatar-black">♚</div>
        <div>
          <div class="name" id="name-black">سیاه<span class="level-badge" id="lvl-black">Lv.۱</span></div>
          <div class="coins" id="coins-black">۱۰۰</div>
        </div>
      </div>
      <div class="timer-wrap"><div class="timer" id="timer-black">۳:۰۰</div></div>
    </div>
    <div id="board-wrap"><div id="board"></div></div>
    <div class="player-bar white" id="bar-white">
      <button class="bar-chat-btn" onclick="toggleChat()">💬<span class="bar-badge" id="badge-white" style="display:none;">۰</span></button>
      <div class="info">
        <div class="avatar" id="avatar-white">♔</div>
        <div>
          <div class="name" id="name-white">سفید<span class="level-badge" id="lvl-white">Lv.۱</span></div>
          <div class="coins" id="coins-white">۱۰۰</div>
        </div>
      </div>
      <div class="timer-wrap"><div class="timer" id="timer-white">۳:۰۰</div></div>
    </div>
    <div id="status-bar">نوبت سفید</div>
    <div id="controls-bar">
      <button onclick="resign()">🏳️ تسلیم</button>
      <button onclick="flipBoard()">🔄 چرخش</button>
      <button onclick="backToSetup()">🏠 منو</button>
    </div>
  </div>
</div>

<!-- ==================== صفحه نتیجه ==================== -->
<div id="result" class="screen">
  <div class="content" style="display:flex;flex-direction:column;align-items:center;justify-content:center;padding:40px 20px;">
    <div class="big" id="res-emoji">🏆</div>
    <h2 id="res-title"></h2>
    <p id="res-sub"></p>
    <p>سکه: <span class="amount" id="res-coins">۱۰۰</span></p>
    <p>سطح: <span class="amount" id="res-level">۱</span></p>
    <button class="btn-main" style="margin-top:20px;" onclick="backToSetup()">🏠 منوی اصلی</button>
  </div>
</div>

<!-- ==================== صفحه جستجوی آنلاین ==================== -->
<div id="searching" class="screen">
  <div class="app-header">
    <span class="icons" onclick="cancelSearch()">←</span>
    <span class="title">🔍 جستجوی حریف</span>
    <span class="icons">⚙️</span>
  </div>
  <div class="content" style="display:flex;flex-direction:column;align-items:center;justify-content:center;padding:30px 20px;text-align:center;">
    <div class="search-spinner"></div>
    <h2 style="color:#0a4a8a;margin:6px 0;">در حال یافتن حریف...</h2>
    <div style="background: #e8f4fd; border: 1.5px solid #0a4a8a; border-radius: 12px; padding: 8px 16px; margin: 12px 0; color: #0a4a8a; font-weight: bold;">
      👥 آنلاین: <span id="online-count">۰</span>
    </div>
    <div id="search-status" style="color:#27ae60;font-weight:bold;min-height:22px;">اتصال به سرور...</div>
    <div id="search-timer" style="color:#7f8c8d;font-size:12px;margin-top:8px;">۰ ثانیه</div>
    <div id="broker-status"></div>
    <button class="btn-main" style="background:#ecf0f1;color:#555;box-shadow:0 4px 0 #bdc3c7;margin-top:20px;" onclick="cancelSearch()">لغو</button>
  </div>
</div>

<!-- ==================== چت ==================== -->
<div id="chat-panel">
  <div class="handle" onclick="toggleChat()"></div>
  <div class="top">
    <div>
      <h3>💬 چت زنده</h3>
      <div class="who" id="chat-who">با حریف</div>
    </div>
    <button class="close-btn" onclick="toggleChat()">✕</button>
  </div>
  <div id="chat-feed"></div>
  <div id="chat-input-row">
    <input type="text" id="chat-input" placeholder="پیام..." maxlength="200" autocomplete="off">
    <button id="chat-send" onclick="sendTypedMessage()">➤</button>
  </div>
  <div id="chat-tabs">
    <button class="active" onclick="switchChatTab('phrases')">📝 جملات</button>
    <button onclick="switchChatTab('stickers')">😀 استیکر</button>
  </div>
  <div id="chat-content" class="phrases"></div>
</div>

<!-- ==================== مودال‌ها ==================== -->
<div id="modal-info" class="modal">
  <div class="box">
    <h3 id="modal-title">اطلاعات</h3>
    <p id="modal-body"></p>
    <div class="btns"><button class="primary" onclick="closeModal('modal-info')">باشه</button></div>
  </div>
</div>

<div id="modal-buy" class="modal">
  <div class="box">
    <h3 id="buy-title">خرید سکه</h3>
    <p id="buy-body"></p>
    <div class="btns">
      <button class="secondary" onclick="closeModal('modal-buy')">لغو</button>
      <button class="primary" onclick="confirmBuy()">خرید</button>
    </div>
  </div>
</div>

<div id="modal-difficulty" class="modal">
  <div class="box">
    <h3>🤖 سطح کامپیوتر</h3>
    <p>سطح سختی حریف کامپیوتری را انتخاب کن:</p>
    <div class="btns" style="flex-direction:column;">
      <button class="primary" onclick="chooseDifficulty(1)">🐣 آسان</button>
      <button class="primary" style="background:linear-gradient(180deg,#b980ff,#6f42c1);color:#fff;" onclick="chooseDifficulty(2)">🤖 متوسط</button>
      <button class="primary" style="background:linear-gradient(180deg,#e74c3c,#c0392b);color:#fff;" onclick="chooseDifficulty(3)">🔥 سخت</button>
      <button class="secondary" onclick="closeModal('modal-difficulty')">لغو</button>
    </div>
  </div>
</div>

<div id="promo-modal" class="modal">
  <div class="box">
    <h3>ارتقای سرباز</h3>
    <div class="opts">
      <button onclick="choosePromo('q')">♛</button>
      <button onclick="choosePromo('r')">♜</button>
      <button onclick="choosePromo('b')">♝</button>
      <button onclick="choosePromo('n')">♞</button>
    </div>
  </div>
</div>

<div id="levelup">
  <div class="ring">🏆</div>
  <h2>لِوِل بالا رفت!</h2>
  <p id="levelup-text">حالا سطح ۲ هستی!</p>
</div>

<div id="toast"></div>

<script>
/* ============ محافظت نام ============ */
(function(){
  const NAME = 'رادین عباسیان';
  try { localStorage.setItem('__radin', NAME); } catch(e){}
  try { Object.defineProperty(window, 'AUTHOR_NAME', { value: NAME, writable: false }); } catch(e){}
  setInterval(() => { try { if (localStorage.getItem('__radin') !== NAME) localStorage.setItem('__radin', NAME); } catch(e){} }, 3000);
  document.addEventListener('contextmenu', e => e.preventDefault());
})();

/* ============ صدا ============ */
let AC = null, masterBus, reverbNode;
function initAudio() {
  if (AC) return AC;
  try {
    AC = new (window.AudioContext || window.webkitAudioContext)();
    const comp = AC.createDynamicsCompressor();
    comp.threshold.value = -12; comp.ratio.value = 6;
    masterBus = AC.createGain(); masterBus.gain.value = 1.4;
    masterBus.connect(comp); comp.connect(AC.destination);
    const len = AC.sampleRate * 2;
    const imp = AC.createBuffer(2, len, AC.sampleRate);
    for (let ch = 0; ch < 2; ch++) {
      const d = imp.getChannelData(ch);
      for (let i = 0; i < len; i++) d[i] = (Math.random()*2-1)*Math.pow(1-i/len, 2.5);
    }
    const c = AC.createConvolver(); c.buffer = imp;
    const rg = AC.createGain(); rg.gain.value = 0.5;
    c.connect(rg); rg.connect(masterBus); reverbNode = c;
    if (AC.state === 'suspended') AC.resume();
  } catch(e) {}
  return AC;
}
function note({freq, dur=0.3, type='triangle', vol=0.2, when=0, atk=0.005, rel=0.2, rev=0.3}) {
  const ctx = initAudio(); if (!ctx) return;
  const t = ctx.currentTime + when;
  const o = ctx.createOscillator(), g = ctx.createGain();
  o.type = type; o.frequency.value = freq;
  g.gain.setValueAtTime(0.0001, t);
  g.gain.exponentialRampToValueAtTime(vol, t + atk);
  g.gain.exponentialRampToValueAtTime(0.0001, t + dur + rel);
  o.connect(g); g.connect(masterBus);
  if (rev > 0 && reverbNode) { const rg = ctx.createGain(); rg.gain.value = rev; g.connect(rg); rg.connect(reverbNode); }
  o.start(t); o.stop(t + dur + rel + 0.05);
}
function noiseBuf(dur) {
  const ctx = initAudio(); if (!ctx) return null;
  const len = Math.floor(ctx.sampleRate * dur);
  const b = ctx.createBuffer(1, len, ctx.sampleRate);
  const d = b.getChannelData(0);
  for (let i = 0; i < len; i++) d[i] = Math.random()*2-1;
  return b;
}
function crash(when=0, vol=0.5) {
  const ctx = initAudio(); if (!ctx) return;
  const t = ctx.currentTime + when;
  const buf = noiseBuf(1.4); if (!buf) return;
  const s = ctx.createBufferSource(); s.buffer = buf;
  const hp = ctx.createBiquadFilter(); hp.type='highpass'; hp.frequency.value=4000;
  const g = ctx.createGain();
  g.gain.setValueAtTime(vol, t);
  g.gain.exponentialRampToValueAtTime(0.001, t+1.3);
  s.connect(hp); hp.connect(g); g.connect(masterBus);
  s.start(t); s.stop(t+1.4);
}
function kick(when=0, vol=0.9) {
  const ctx = initAudio(); if (!ctx) return;
  const t = ctx.currentTime + when;
  const o = ctx.createOscillator(), g = ctx.createGain();
  o.type='sine';
  o.frequency.setValueAtTime(160, t);
  o.frequency.exponentialRampToValueAtTime(38, t+0.14);
  g.gain.setValueAtTime(vol, t);
  g.gain.exponentialRampToValueAtTime(0.001, t+0.28);
  o.connect(g); g.connect(masterBus);
  o.start(t); o.stop(t+0.32);
}
function sparkle(freq, when, vol=0.22) {
  note({freq, dur:0.4, type:'sine', vol, when, atk:0.001, rel:0.6, rev:0.7});
  note({freq:freq*2, dur:0.3, type:'triangle', vol:vol*0.5, when, atk:0.001, rel:0.5, rev:0.6});
}
function sfxMove() { note({freq:440, dur:0.06, type:'square', vol:0.1, atk:0.001, rel:0.1}); }
function sfxCapture(){ note({freq:220, dur:0.22, type:'sawtooth', vol:0.28, atk:0.001, rel:0.3}); crash(0.05,0.3); }
function sfxCheck(){ note({freq:880, dur:0.15, type:'square', vol:0.25}); note({freq:1320, dur:0.2, type:'triangle', vol:0.2, when:0.1}); }
function sfxCastle(){ note({freq:523, dur:0.15, type:'triangle', vol:0.2}); note({freq:784, dur:0.2, type:'triangle', vol:0.18, when:0.08}); }
function sfxPromote(){ [523,659,784,1046].forEach((f,i)=>note({freq:f, dur:0.3, type:'triangle', vol:0.22, when:i*0.06})); }
function sfxTick(){ note({freq:1400, dur:0.04, type:'square', vol:0.09}); }
function sfxConnect(){ [523,659,784,1046].forEach((f,i)=>note({freq:f, dur:0.4, type:'triangle', vol:0.22, when:i*0.1})); }
function sfxChat(){ note({freq:660, dur:0.06, type:'sine', vol:0.15}); note({freq:990, dur:0.1, type:'sine', vol:0.12, when:0.05}); }
function sfxReceive(){ note({freq:880, dur:0.1, type:'sine', vol:0.22}); note({freq:1320, dur:0.15, type:'sine', vol:0.18, when:0.08}); }
function sfxSticker(){ note({freq:780, dur:0.08, type:'triangle', vol:0.18}); note({freq:1170, dur:0.12, type:'triangle', vol:0.14, when:0.06}); }
function sfxBuy(){ [659,784,1046,1318].forEach((f,i)=>note({freq:f, dur:0.3, type:'triangle', vol:0.25, when:i*0.08, rev:0.6})); }
function sfxWin() {
  kick(0.8,1.0); kick(1.15,0.9); kick(1.5,1.0);
  crash(0.78,0.6); crash(1.5,0.45);
  [523.25,659.25,783.99,1046.5,1318.5,1568,2093].forEach((f,i)=>sparkle(f, 0.8+i*0.075, 0.26));
}
function sfxLose() {
  kick(0,1.0); kick(0.5,0.9);
  [[523,622,784],[466,554,698],[415,494,622],[349,415,523]].forEach((ch,i)=>{
    ch.forEach(f=>note({freq:f, dur:0.4, type:'sawtooth', vol:0.15, when:0.4+i*0.18}));
  });
  crash(1.15,0.5);
}

/* ============ موتور شطرنج ============ */
const INITIAL_BOARD = [
  ['br','bn','bb','bq','bk','bb','bn','br'],
  ['bp','bp','bp','bp','bp','bp','bp','bp'],
  [null,null,null,null,null,null,null,null],
  [null,null,null,null,null,null,null,null],
  [null,null,null,null,null,null,null,null],
  [null,null,null,null,null,null,null,null],
  ['wp','wp','wp','wp','wp','wp','wp','wp'],
  ['wr','wn','wb','wq','wk','wb','wn','wr']
];
const PIECE_UNICODE = {
  wp:'♟', wn:'♞', wb:'♝', wr:'♜', wq:'♛', wk:'♚',
  bp:'♟', bn:'♞', bb:'♝', br:'♜', bq:'♛', bk:'♚'
};

let G = null;
let flipped = false;
let promoPending = null;
let selectedTime = 180;
let selectedBet = 30;
let aiDepth = 2;

let playerStats = {
  username: 'c_radin_abbasiyan',
  displayName: 'رادین عباسیان - ۳۷',
  coins: 726, score: 3618, oppScore: 2958,
  wins: 260, losses: 408, draws: 16, incomplete: 145, level: 1
};
try {
  const s = localStorage.getItem('shah-stats-v2');
  if (s) playerStats = { ...playerStats, ...JSON.parse(s) };
} catch(e) {}
function saveStats() { try { localStorage.setItem('shah-stats-v2', JSON.stringify(playerStats)); } catch(e) {} }

function refreshStatsUI() {
  document.getElementById('user-name').textContent = playerStats.displayName;
  document.getElementById('user-username').textContent = 'username : ' + playerStats.username;
  document.getElementById('stat-score').textContent = toFa(playerStats.score);
  document.getElementById('stat-opp-score').textContent = toFa(playerStats.oppScore);
  document.getElementById('stat-coins').textContent = toFa(playerStats.coins);
  document.getElementById('stat-wins').textContent = toFa(playerStats.wins);
  document.getElementById('stat-losses').textContent = toFa(playerStats.losses);
  document.getElementById('stat-draws').textContent = toFa(playerStats.draws);
  document.getElementById('stat-incomplete').textContent = toFa(playerStats.incomplete);
  const total = playerStats.wins + playerStats.losses + playerStats.draws + playerStats.incomplete;
  document.getElementById('stat-total').textContent = toFa(total);
  document.getElementById('stat-level').textContent = toFa(playerStats.level);
  document.getElementById('store-current-coins').textContent = toFa(playerStats.coins);
  const winPct = total > 0 ? Math.round((playerStats.wins / total) * 100) : 0;
  const scorePct = (playerStats.score + playerStats.oppScore) > 0 ? Math.round((playerStats.score / (playerStats.score + playerStats.oppScore)) * 100) : 50;
  document.getElementById('win-percent').textContent = toFa(winPct);
  document.getElementById('score-percent').textContent = toFa(scorePct);
  const wc = document.getElementById('win-circle');
  const sc = document.getElementById('score-circle');
  if (wc) wc.setAttribute('stroke-dasharray', `${winPct}, ${100 - winPct}`);
  if (sc) sc.setAttribute('stroke-dasharray', `${scorePct}, ${100 - scorePct}`);
}

document.querySelectorAll('.tab-bar .tab').forEach(t => {
  t.addEventListener('click', () => {
    document.querySelectorAll('.tab-bar .tab').forEach(x => x.classList.remove('active'));
    t.classList.add('active');
    const tab = t.dataset.tab;
    document.getElementById('content-play').style.display = tab === 'play' ? 'block' : 'none';
    document.getElementById('content-records').style.display = tab === 'records' ? 'block' : 'none';
    document.getElementById('content-store').style.display = tab === 'store' ? 'block' : 'none';
    if (tab === 'records' || tab === 'store') refreshStatsUI();
  });
});

/* ============ توابع شطرنج ============ */
function isInside(r, c) { return r >= 0 && r < 8 && c >= 0 && c < 8; }

function genPseudo(board, r, c, state) {
  const piece = board[r][c]; if (!piece) return [];
  const color = piece[0], type = piece[1];
  const moves = [];
  const opp = color === 'w' ? 'b' : 'w';
  if (type === 'p') {
    const dir = color === 'w' ? -1 : 1;
    const startRow = color === 'w' ? 6 : 1;
    const promRow = color === 'w' ? 0 : 7;
    if (isInside(r+dir, c) && !board[r+dir][c]) {
      moves.push({ from:[r,c], to:[r+dir,c], promo:(r+dir === promRow) });
      if (r === startRow && !board[r+2*dir][c]) moves.push({ from:[r,c], to:[r+2*dir,c] });
    }
    for (const dc of [-1, 1]) {
      const nr = r+dir, nc = c+dc;
      if (!isInside(nr, nc)) continue;
      const t = board[nr][nc];
      if (t && t[0] === opp) moves.push({ from:[r,c], to:[nr,nc], promo:(nr===promRow) });
      if (state.ep && state.ep[0] === nr && state.ep[1] === nc && board[r][nc] === opp + 'p')
        moves.push({ from:[r,c], to:[nr,nc], epCapture:[r,nc] });
    }
  } else if (type === 'n') {
    for (const [dr,dc] of [[-2,-1],[-2,1],[-1,-2],[-1,2],[1,-2],[1,2],[2,-1],[2,1]]) {
      const nr = r+dr, nc = c+dc;
      if (!isInside(nr,nc)) continue;
      const t = board[nr][nc];
      if (!t || t[0] === opp) moves.push({ from:[r,c], to:[nr,nc] });
    }
  } else if (type === 'b' || type === 'q') {
    for (const [dr,dc] of [[1,1],[1,-1],[-1,1],[-1,-1]]) {
      let nr = r+dr, nc = c+dc;
      while (isInside(nr,nc)) {
        const t = board[nr][nc];
        if (t && t[0] === color) break;
        moves.push({ from:[r,c], to:[nr,nc] });
        if (t) break;
        nr += dr; nc += dc;
      }
    }
  }
  if (type === 'r' || type === 'q') {
    for (const [dr,dc] of [[1,0],[-1,0],[0,1],[0,-1]]) {
      let nr = r+dr, nc = c+dc;
      while (isInside(nr,nc)) {
        const t = board[nr][nc];
        if (t && t[0] === color) break;
        moves.push({ from:[r,c], to:[nr,nc] });
        if (t) break;
        nr += dr; nc += dc;
      }
    }
  }
  if (type === 'k') {
    for (const [dr,dc] of [[1,0],[-1,0],[0,1],[0,-1],[1,1],[1,-1],[-1,1],[-1,-1]]) {
      const nr = r+dr, nc = c+dc;
      if (!isInside(nr,nc)) continue;
      const t = board[nr][nc];
      if (!t || t[0] === opp) moves.push({ from:[r,c], to:[nr,nc] });
    }
    const homeRow = color === 'w' ? 7 : 0;
    if (r === homeRow && c === 4 && !isSquareAttacked(board, homeRow, 4, opp)) {
      const kRight = color === 'w' ? state.castling.wk : state.castling.bk;
      if (kRight && !board[homeRow][5] && !board[homeRow][6] &&
          !isSquareAttacked(board, homeRow, 5, opp) && !isSquareAttacked(board, homeRow, 6, opp))
        moves.push({ from:[r,c], to:[homeRow,6], castle:'k' });
      const qRight = color === 'w' ? state.castling.wq : state.castling.bq;
      if (qRight && !board[homeRow][3] && !board[homeRow][2] && !board[homeRow][1] &&
          !isSquareAttacked(board, homeRow, 3, opp) && !isSquareAttacked(board, homeRow, 2, opp))
        moves.push({ from:[r,c], to:[homeRow,2], castle:'q' });
    }
  }
  return moves;
}
function isSquareAttacked(board, r, c, byColor) {
  for (let rr = 0; rr < 8; rr++) for (let cc = 0; cc < 8; cc++) {
    const p = board[rr][cc];
    if (!p || p[0] !== byColor) continue;
    const t = p[1];
    if (t === 'p') {
      const dir = byColor === 'w' ? -1 : 1;
      if (rr + dir === r && (cc-1 === c || cc+1 === c)) return true;
      continue;
    }
    if (t === 'n') {
      for (const [dr,dc] of [[-2,-1],[-2,1],[-1,-2],[-1,2],[1,-2],[1,2],[2,-1],[2,1]])
        if (rr+dr === r && cc+dc === c) return true;
      continue;
    }
    if (t === 'k') {
      if (Math.abs(rr-r) <= 1 && Math.abs(cc-c) <= 1 && (rr!==r || cc!==c)) return true;
      continue;
    }
    if (t === 'r' || t === 'q') {
      for (const [dr,dc] of [[1,0],[-1,0],[0,1],[0,-1]]) {
        let nr = rr+dr, nc = cc+dc;
        while (isInside(nr,nc)) {
          if (nr === r && nc === c) return true;
          if (board[nr][nc]) break;
          nr += dr; nc += dc;
        }
      }
    }
    if (t === 'b' || t === 'q') {
      for (const [dr,dc] of [[1,1],[1,-1],[-1,1],[-1,-1]]) {
        let nr = rr+dr, nc = cc+dc;
        while (isInside(nr,nc)) {
          if (nr === r && nc === c) return true;
          if (board[nr][nc]) break;
          nr += dr; nc += dc;
        }
      }
    }
  }
  return false;
}
function findKing(board, color) {
  for (let r = 0; r < 8; r++) for (let c = 0; c < 8; c++) if (board[r][c] === color + 'k') return [r,c];
  return null;
}
function inCheck(board, color) {
  const k = findKing(board, color); if (!k) return false;
  const opp = color === 'w' ? 'b' : 'w';
  return isSquareAttacked(board, k[0], k[1], opp);
}
function applyMoveRaw(board, move, promoType) {
  const nb = board.map(r => [...r]);
  const [fr, fc] = move.from, [tr, tc] = move.to;
  const piece = nb[fr][fc];
  nb[tr][tc] = piece; nb[fr][fc] = null;
  if (move.epCapture) nb[move.epCapture[0]][move.epCapture[1]] = null;
  if (move.castle === 'k') { nb[fr][5] = nb[fr][7]; nb[fr][7] = null; }
  if (move.castle === 'q') { nb[fr][3] = nb[fr][0]; nb[fr][0] = null; }
  if (move.promo && promoType) nb[tr][tc] = piece[0] + promoType;
  return nb;
}
function genLegal(state, r, c) {
  const piece = state.board[r][c]; if (!piece) return [];
  const color = piece[0];
  const pseudo = genPseudo(state.board, r, c, state);
  const legal = [];
  for (const m of pseudo) {
    const nb = applyMoveRaw(state.board, m, m.promo ? 'q' : null);
    if (!inCheck(nb, color)) legal.push(m);
  }
  return legal;
}
function genAllLegal(state, color) {
  const all = [];
  for (let r = 0; r < 8; r++) for (let c = 0; c < 8; c++)
    if (state.board[r][c] && state.board[r][c][0] === color) all.push(...genLegal(state, r, c));
  return all;
}

/* ============ هوش مصنوعی ============ */
const PIECE_VALUES = { p: 100, n: 320, b: 330, r: 500, q: 900, k: 20000 };
const PST = {
  p: [[0,0,0,0,0,0,0,0],[50,50,50,50,50,50,50,50],[10,10,20,30,30,20,10,10],[5,5,10,25,25,10,5,5],[0,0,0,20,20,0,0,0],[5,-5,-10,0,0,-10,-5,5],[5,10,10,-20,-20,10,10,5],[0,0,0,0,0,0,0,0]],
  n: [[-50,-40,-30,-30,-30,-30,-40,-50],[-40,-20,0,0,0,0,-20,-40],[-30,0,10,15,15,10,0,-30],[-30,5,15,20,20,15,5,-30],[-30,0,15,20,20,15,0,-30],[-30,5,10,15,15,10,5,-30],[-40,-20,0,5,5,0,-20,-40],[-50,-40,-30,-30,-30,-30,-40,-50]],
  b: [[-20,-10,-10,-10,-10,-10,-10,-20],[-10,0,0,0,0,0,0,-10],[-10,0,5,10,10,5,0,-10],[-10,5,5,10,10,5,5,-10],[-10,0,10,10,10,10,0,-10],[-10,10,10,10,10,10,10,-10],[-10,5,0,0,0,0,5,-10],[-20,-10,-10,-10,-10,-10,-10,-20]],
  r: [[0,0,0,0,0,0,0,0],[5,10,10,10,10,10,10,5],[-5,0,0,0,0,0,0,-5],[-5,0,0,0,0,0,0,-5],[-5,0,0,0,0,0,0,-5],[-5,0,0,0,0,0,0,-5],[-5,0,0,0,0,0,0,-5],[0,0,0,5,5,0,0,0]],
  q: [[-20,-10,-10,-5,-5,-10,-10,-20],[-10,0,0,0,0,0,0,-10],[-10,0,5,5,5,5,0,-10],[-5,0,5,5,5,5,0,-5],[0,0,5,5,5,5,0,-5],[-10,5,5,5,5,5,0,-10],[-10,0,5,0,0,0,0,-10],[-20,-10,-10,-5,-5,-10,-10,-20]],
  k: [[-30,-40,-40,-50,-50,-40,-40,-30],[-30,-40,-40,-50,-50,-40,-40,-30],[-30,-40,-40,-50,-50,-40,-40,-30],[-30,-40,-40,-50,-50,-40,-40,-30],[-20,-30,-30,-40,-40,-30,-30,-20],[-10,-20,-20,-20,-20,-20,-20,-10],[20,20,0,0,0,0,20,20],[20,30,10,0,0,10,30,20]]
};
function evaluateBoard(state) {
  let score = 0;
  for (let r = 0; r < 8; r++) for (let c = 0; c < 8; c++) {
    const p = state.board[r][c]; if (!p) continue;
    const color = p[0], type = p[1];
    const val = PIECE_VALUES[type];
    const pst = color === 'w' ? PST[type][r][c] : PST[type][7 - r][c];
    score += color === 'w' ? (val + pst) : -(val + pst);
  }
  return score;
}
function cloneState(state) {
  return { board: state.board.map(r => [...r]), turn: state.turn, castling: { ...state.castling }, ep: state.ep ? [...state.ep] : null };
}
function applyMoveAI(state, move, promoType) {
  const S = cloneState(state);
  const [fr, fc] = move.from, [tr, tc] = move.to;
  const piece = S.board[fr][fc]; const color = piece[0];
  S.board[tr][tc] = piece; S.board[fr][fc] = null;
  if (move.epCapture) S.board[move.epCapture[0]][move.epCapture[1]] = null;
  if (move.castle === 'k') { S.board[fr][5] = S.board[fr][7]; S.board[fr][7] = null; }
  if (move.castle === 'q') { S.board[fr][3] = S.board[fr][0]; S.board[fr][0] = null; }
  if (move.promo) S.board[tr][tc] = color + (promoType || 'q');
  if (piece[1] === 'k') { if (color === 'w') { S.castling.wk = false; S.castling.wq = false; } else { S.castling.bk = false; S.castling.bq = false; } }
  if (piece[1] === 'r') {
    if (fr === 7 && fc === 0) S.castling.wq = false;
    if (fr === 7 && fc === 7) S.castling.wk = false;
    if (fr === 0 && fc === 0) S.castling.bq = false;
    if (fr === 0 && fc === 7) S.castling.bk = false;
  }
  if (tr === 7 && tc === 0) S.castling.wq = false;
  if (tr === 7 && tc === 7) S.castling.wk = false;
  if (tr === 0 && tc === 0) S.castling.bq = false;
  if (tr === 0 && tc === 7) S.castling.bk = false;
  const wasPawn = piece[1] === 'p';
  S.ep = (wasPawn && Math.abs(tr - fr) === 2) ? [(fr + tr) / 2, fc] : null;
  S.turn = S.turn === 'w' ? 'b' : 'w';
  return S;
}
function movePriority(board, move) {
  const t = board[move.to[0]][move.to[1]];
  return t ? PIECE_VALUES[t[1]] : 0;
}
function minimax(state, depth, alpha, beta, maximizing, startTime, maxTime) {
  if (Date.now() - startTime > maxTime) return { score: evaluateBoard(state), move: null, timeout: true };
  const color = state.turn;
  const moves = genAllLegal(state, color);
  if (moves.length === 0) {
    if (inCheck(state.board, color)) return { score: color === 'w' ? -100000 - depth : 100000 + depth, move: null };
    return { score: 0, move: null };
  }
  if (depth === 0) return { score: evaluateBoard(state), move: null };
  let bestMove = null;
  if (maximizing) {
    let maxScore = -Infinity;
    moves.sort((a,b) => movePriority(state.board, b) - movePriority(state.board, a));
    for (const move of moves) {
      const next = applyMoveAI(state, move, move.promo ? 'q' : null);
      const r = minimax(next, depth - 1, alpha, beta, false, startTime, maxTime);
      if (r.timeout) return r;
      if (r.score > maxScore) { maxScore = r.score; bestMove = move; }
      alpha = Math.max(alpha, maxScore);
      if (beta <= alpha) break;
    }
    return { score: maxScore, move: bestMove };
  } else {
    let minScore = Infinity;
    moves.sort((a,b) => movePriority(state.board, a) - movePriority(state.board, b));
    for (const move of moves) {
      const next = applyMoveAI(state, move, move.promo ? 'q' : null);
      const r = minimax(next, depth - 1, alpha, beta, true, startTime, maxTime);
      if (r.timeout) return r;
      if (r.score < minScore) { minScore = r.score; bestMove = move; }
      beta = Math.min(beta, minScore);
      if (beta <= alpha) break;
    }
    return { score: minScore, move: bestMove };
  }
}
function findBestMove(state, depth, randomize = 0) {
  const moves = genAllLegal(state, state.turn);
  if (moves.length === 0) return null;
  if (depth === 0 || (randomize > 0 && Math.random() < randomize)) {
    moves.sort((a,b) => movePriority(state.board, b) - movePriority(state.board, a));
    return moves[Math.floor(Math.random() * Math.min(4, moves.length))];
  }
  const result = minimax(cloneState(state), depth, -Infinity, Infinity, state.turn === 'w', Date.now(), 2000);
  if (!result.move) {
    moves.sort((a,b) => movePriority(state.board, b) - movePriority(state.board, a));
    return moves[0];
  }
  return result.move;
}
function makeAIMove() {
  if (!G || G.gameOver || !G.isAI || G.turn !== G.aiColor) return;
  const bar = G.aiColor === 'w' ? document.getElementById('bar-white') : document.getElementById('bar-black');
  if (bar) bar.classList.add('thinking');
  setTimeout(() => {
    if (!G || G.gameOver) { if (bar) bar.classList.remove('thinking'); return; }
    let depth, rnd = 0;
    if (G.aiDepth === 1) { depth = 1; rnd = 0.4; }
    else if (G.aiDepth === 2) { depth = 2; rnd = 0.08; }
    else { depth = 3; rnd = 0; }
    const move = findBestMove(G, depth, rnd);
    if (bar) bar.classList.remove('thinking');
    if (!move) return;
    G.selected = null; G.legalMoves = [];
    executeMove(move, move.promo ? 'q' : null, false);
  }, 300 + Math.random() * 300);
}

/* ============ حالت بازی ============ */
function newGameState(timeSec, bet, online, myColor, isAI, aiColor) {
  return {
    board: INITIAL_BOARD.map(r => [...r]),
    turn: 'w',
    castling: { wk:true, wq:true, bk:true, bq:true },
    ep: null, lastMove: null,
    selected: null, legalMoves: [],
    gameOver: false, initialTime: timeSec,
    white: { time: timeSec, coins: playerStats.coins, level: playerStats.level },
    black: { time: timeSec, coins: 100, level: 1 },
    bet: bet, isOnline: online, isAI: !!isAI, aiColor: aiColor || 'b',
    aiDepth: aiDepth, myColor: myColor || null
  };
}

/* ============ تایمر ============ */
let timerInterval = null;
function startTimer() {
  stopTimer();
  G.lastTickSec = -1;
  let lastTime = performance.now();
  timerInterval = setInterval(() => {
    if (!G || G.gameOver) return;
    if (G.isAI && G.turn === G.aiColor) { lastTime = performance.now(); updateTimers(); return; }
    const now = performance.now();
    const elapsed = (now - lastTime) / 1000;
    lastTime = now;
    const sideObj = G.turn === 'w' ? G.white : G.black;
    sideObj.time = Math.max(0, sideObj.time - elapsed);
    if (sideObj.time <= 0) { endGame(G.turn === 'w' ? 'b' : 'w', 'زمان تمام شد!'); return; }
    updateTimers();
    const t = Math.ceil(sideObj.time);
    if (t <= 10 && t !== G.lastTickSec && t > 0) { G.lastTickSec = t; sfxTick(); }
  }, 100);
}
function stopTimer() { if (timerInterval) { clearInterval(timerInterval); timerInterval = null; } }
function fmtTime(sec) { if (sec < 0) sec = 0; const m = Math.floor(sec / 60), s = Math.floor(sec % 60); return `${m}:${s < 10 ? '0' : ''}${s}`; }
function toFa(n) { return n.toString().replace(/\d/g, d => '۰۱۲۳۴۵۶۷۸۹'[d]); }
function updateTimers() {
  if (!G) return;
  const wt = document.getElementById('timer-white'), bt = document.getElementById('timer-black');
  wt.textContent = toFa(fmtTime(G.white.time));
  bt.textContent = toFa(fmtTime(G.black.time));
  wt.classList.toggle('warn', G.white.time <= 30 && G.white.time > 10);
  bt.classList.toggle('warn', G.black.time <= 30 && G.black.time > 10);
  wt.classList.toggle('critical', G.white.time <= 10);
  bt.classList.toggle('critical', G.black.time <= 10);
  document.getElementById('bar-white').classList.toggle('active', G.turn === 'w' && !G.gameOver);
  document.getElementById('bar-black').classList.toggle('active', G.turn === 'b' && !G.gameOver);
}
function updateLevelBadges() {
  if (!G) return;
  document.getElementById('lvl-white').textContent = 'Lv.' + toFa(G.white.level);
  document.getElementById('lvl-black').textContent = 'Lv.' + toFa(G.black.level);
}

/* ============ اجرای حرکت ============ */
function executeMove(move, promoType, fromNet) {
  const S = G;
  const [fr, fc] = move.from, [tr, tc] = move.to;
  const piece = S.board[fr][fc];
  const color = piece[0];
  const captured = S.board[tr][tc];
  const wasPawn = piece[1] === 'p';
  S.board[tr][tc] = piece; S.board[fr][fc] = null;
  if (move.epCapture) S.board[move.epCapture[0]][move.epCapture[1]] = null;
  if (move.castle === 'k') { S.board[fr][5] = S.board[fr][7]; S.board[fr][7] = null; }
  if (move.castle === 'q') { S.board[fr][3] = S.board[fr][0]; S.board[fr][0] = null; }
  if (move.promo) S.board[tr][tc] = color + (promoType || 'q');
  if (piece[1] === 'k') { if (color === 'w') { S.castling.wk = false; S.castling.wq = false; } else { S.castling.bk = false; S.castling.bq = false; } }
  if (piece[1] === 'r') {
    if (fr === 7 && fc === 0) S.castling.wq = false;
    if (fr === 7 && fc === 7) S.castling.wk = false;
    if (fr === 0 && fc === 0) S.castling.bq = false;
    if (fr === 0 && fc === 7) S.castling.bk = false;
  }
  if (tr === 7 && tc === 0) S.castling.wq = false;
  if (tr === 7 && tc === 7) S.castling.wk = false;
  if (tr === 0 && tc === 0) S.castling.bq = false;
  if (tr === 0 && tc === 7) S.castling.bk = false;
  S.ep = (wasPawn && Math.abs(tr - fr) === 2) ? [(fr + tr) / 2, fc] : null;
  S.lastMove = { from:[fr,fc], to:[tr,tc] };
  if (move.castle) sfxCastle();
  else if (captured || move.epCapture) sfxCapture();
  else if (move.promo) sfxPromote();
  else sfxMove();
  S.turn = S.turn === 'w' ? 'b' : 'w';
  if (S.isOnline && window.__conn && window.__conn.open && !fromNet) {
    try { window.__conn.send({ type: 'move', move: move, promoType: promoType, timeW: S.white.time, timeB: S.black.time }); } catch(e) {}
  }
  const inChk = inCheck(S.board, S.turn);
  const oppMoves = genAllLegal(S, S.turn);
  if (oppMoves.length === 0) {
    if (inChk) endGame(S.turn === 'w' ? 'b' : 'w', 'شاه‌مات!');
    else endGame(null, 'استالمیت — مساوی');
    return;
  } else if (inChk) { sfxCheck(); toast('⚠️ کیش!'); }
  render(); updateStatus(); updateLevelBadges();
  if (S.isAI && S.turn === S.aiColor && !S.gameOver) setTimeout(makeAIMove, 400);
}

/* ============ تعامل ============ */
function onCellClick(r, c) {
  initAudio();
  if (!G || G.gameOver) return;
  if (G.isOnline && G.turn !== G.myColor) return;
  if (G.isAI && G.turn === G.aiColor) return;
  const S = G;
  const piece = S.board[r][c];
  if (S.selected) {
    const move = S.legalMoves.find(m => m.to[0] === r && m.to[1] === c);
    if (move) {
      if (move.promo) {
        promoPending = move;
        document.getElementById('promo-modal').classList.add('show');
        return;
      }
      S.selected = null; S.legalMoves = [];
      executeMove(move, null, false);
      return;
    }
  }
  if (G.isOnline && piece && piece[0] !== G.myColor) return;
  if (piece && piece[0] === S.turn) {
    S.selected = [r,c];
    S.legalMoves = genLegal(S, r, c);
    render();
  } else {
    S.selected = null; S.legalMoves = [];
    render();
  }
}
function choosePromo(type) {
  document.getElementById('promo-modal').classList.remove('show');
  if (promoPending) {
    const m = promoPending;
    promoPending = null;
    G.selected = null; G.legalMoves = [];
    executeMove(m, type, false);
  }
}

/* ============ رندر ============ */
function render() {
  const board = document.getElementById('board');
  board.innerHTML = '';
  const S = G; if (!S) return;
  const rows = flipped ? [7,6,5,4,3,2,1,0] : [0,1,2,3,4,5,6,7];
  const cols = flipped ? [7,6,5,4,3,2,1,0] : [0,1,2,3,4,5,6,7];
  for (const r of rows) {
    for (const c of cols) {
      const cell = document.createElement('div');
      const isLight = (r + c) % 2 === 0;
      cell.className = 'cell ' + (isLight ? 'light' : 'dark');
      if (S.lastMove && ((S.lastMove.from[0]===r && S.lastMove.from[1]===c) || (S.lastMove.to[0]===r && S.lastMove.to[1]===c))) cell.classList.add('last-move');
      if (S.selected && S.selected[0]===r && S.selected[1]===c) cell.classList.add('selected');
      if (S.board[r][c] === S.turn + 'k' && inCheck(S.board, S.turn)) cell.classList.add('check');
      if (S.selected) {
        const m = S.legalMoves.find(mm => mm.to[0]===r && mm.to[1]===c);
        if (m) {
          if (S.board[r][c] || m.epCapture) cell.classList.add('capture-target');
          else {
            const dot = document.createElement('div');
            dot.className = 'dot';
            cell.appendChild(dot);
          }
        }
      }
      const p = S.board[r][c];
      if (p) {
        const sp = document.createElement('span');
        sp.className = 'piece ' + p[0];
        sp.textContent = PIECE_UNICODE[p];
        cell.appendChild(sp);
      }
      cell.addEventListener('click', () => onCellClick(r, c));
      board.appendChild(cell);
    }
  }
}
function updateStatus() {
  const el = document.getElementById('status-bar');
  if (!G || G.gameOver) return;
  if (G.isAI) {
    el.textContent = G.turn === G.aiColor ? '🤖 کامپیوتر در حال فکر...' : '🟢 نوبت شماست';
    el.style.color = G.turn === G.aiColor ? '#b980ff' : '#06d6a0';
  } else if (G.isOnline) {
    el.textContent = G.turn === G.myColor ? '🟢 نوبت شماست' : '⏳ نوبت حریف';
    el.style.color = G.turn === G.myColor ? '#06d6a0' : '#ffd166';
  } else {
    el.textContent = G.turn === 'w' ? 'نوبت سفید ⚪' : 'نوبت سیاه ⚫';
    el.style.color = G.turn === 'w' ? '#fff' : '#ffd166';
  }
  updateTimers();
}
function updateCoinDisplays() {
  if (!G) return;
  document.getElementById('coins-white').textContent = toFa(G.white.coins);
  document.getElementById('coins-black').textContent = toFa(G.black.coins);
}

/* ============ پایان بازی ============ */
function endGame(winner, reason) {
  if (!G || G.gameOver) return;
  G.gameOver = true;
  stopTimer();
  const bet = G.bet;
  let message = '', emoji = '🏆';

  if (winner === 'w') {
    message = `سفید برد! ${toFa(bet)} سکه گرفت.`;
    sfxWin();
    if (!G.isOnline || G.myColor === 'w') { playerStats.wins++; playerStats.coins += bet; }
    else playerStats.losses++;
    playerStats.score += 10;
  } else if (winner === 'b') {
    message = `سیاه برد! ${toFa(bet)} سکه گرفت.`;
    if (!G.isOnline || G.myColor === 'b') { playerStats.wins++; playerStats.coins += bet; }
    else playerStats.losses++;
    sfxLose();
  } else {
    message = 'مساوی!'; emoji = '🤝';
    playerStats.draws++;
  }
  if (winner === 'w' || winner === 'b') {
    if (winner === 'w') G.white.level++;
    else G.black.level++;
    if (!G.isOnline || winner === G.myColor) playerStats.level++;
  }
  saveStats();
  refreshStatsUI();
  updateTimers(); updateCoinDisplays(); updateLevelBadges();

  setTimeout(() => {
    document.getElementById('res-emoji').textContent = emoji;
    document.getElementById('res-title').textContent = reason;
    document.getElementById('res-sub').textContent = message;
    document.getElementById('res-coins').textContent = toFa(playerStats.coins);
    document.getElementById('res-level').textContent = toFa(playerStats.level);
    showScreen('result');
  }, 1000);
}
function resign() {
  if (!G || G.gameOver) return;
  if (!confirm('تسلیم می‌شی؟')) return;
  const loser = G.turn;
  const winner = loser === 'w' ? 'b' : 'w';
  sfxLose();
  if (G.isOnline && window.__conn && window.__conn.open) {
    try { window.__conn.send({ type: 'resign' }); } catch(e) {}
  }
  endGame(winner, (loser === 'w' ? 'سفید' : 'سیاه') + ' تسلیم شد');
}
function flipBoard() { flipped = !flipped; render(); }
function backToSetup() {
  stopTimer();
  if (window.__closeConn) window.__closeConn();
  closeChat();
  showScreen('home');
}
function showScreen(id) {
  document.querySelectorAll('.screen').forEach(s => s.classList.remove('active'));
  document.getElementById(id).classList.add('active');
}

/* ============ شروع بازی ============ */
function startAIGame() {
  initAudio();
  document.getElementById('modal-difficulty').classList.add('show');
}
function chooseDifficulty(level) {
  closeModal('modal-difficulty');
  aiDepth = level;
  flipped = false;
  G = newGameState(selectedTime, selectedBet, false, 'w', true, 'b');
  const ns = document.getElementById('net-status');
  ns.style.display = 'inline-flex'; ns.classList.add('ai');
  const depthName = aiDepth === 1 ? 'آسان' : (aiDepth === 2 ? 'متوسط' : 'سخت');
  ns.textContent = '🤖 کامپیوتر — ' + depthName;
  document.getElementById('chat-feed').innerHTML = '';
  unread = 0; updateUnreadBadge(); renderChatContent();
  document.getElementById('chat-who').textContent = 'چت با کامپیوتر 🤖';
  document.getElementById('name-white').innerHTML = 'شما<span class="level-badge" id="lvl-white">Lv.' + toFa(G.white.level) + '</span>';
  document.getElementById('name-black').innerHTML = '🤖 کامپیوتر<span class="level-badge" id="lvl-black">Lv.' + toFa(G.black.level) + '</span>';
  document.getElementById('avatar-black').textContent = '🤖';
  document.getElementById('avatar-white').textContent = '👤';
  document.getElementById('bar-black').classList.add('ai');
  updateCoinDisplays(); updateTimers(); render(); updateStatus();
  showScreen('game');
  startTimer();
  toast(`🤖 بازی با کامپیوتر (${depthName}) شروع شد!`);
}
function showFriendGameInfo() {
  document.getElementById('modal-title').textContent = '👥 بازی با دوستان';
  document.getElementById('modal-body').innerHTML = 'ورودیه: ۶ سکه<br>جایزه برنده: ۱۲ سکه<br>بدون امتیاز<br><br>این حالت به‌زودی اضافه می‌شود!';
  document.getElementById('modal-info').classList.add('show');
}
function challengePlayer(name) {
  document.getElementById('modal-title').textContent = '🎯 چالش ' + name;
  document.getElementById('modal-body').textContent = 'درخواست بازی برای ' + name + ' فرستاده شد... (نسخه آزمایشی)';
  document.getElementById('modal-info').classList.add('show');
}
function closeModal(id) { document.getElementById(id).classList.remove('show'); }

/* ============ خرید سکه ============ */
let pendingBuy = null;
function buyCoins(amount, price) {
  pendingBuy = { amount, price };
  document.getElementById('buy-title').textContent = 'خرید ' + toFa(amount) + ' سکه';
  document.getElementById('buy-body').innerHTML = 'قیمت: ' + toFa(price) + ' تومان<br>پس از خرید، سکه‌ها به حساب شما اضافه می‌شود.';
  document.getElementById('modal-buy').classList.add('show');
}
function confirmBuy() {
  if (pendingBuy) {
    sfxBuy();
    playerStats.coins += pendingBuy.amount;
    saveStats(); refreshStatsUI();
    closeModal('modal-buy');
    toast('✅ ' + toFa(pendingBuy.amount) + ' سکه اضافه شد!');
    pendingBuy = null;
  }
}
function freeCoins() {
  sfxBuy();
  playerStats.coins += 5;
  saveStats(); refreshStatsUI();
  toast('🎬 ۵ سکه رایگان گرفتی!');
}
function logoutConfirm() {
  if (confirm('از حساب خارج می‌شوی؟')) location.reload();
}

/* ============ چت ============ */
const PHRASES = ['👋 سلام!','بازی خوبی!','حرکت خوبی بود!','اشتباه کردم 😅','قوی بازی می‌کنی','عجب حرکتی! 🔥','کیش!','نزدیک بود!','موفق باشی! 🍀','بزن بریم! 🚀','آفرین! 👏','وای! 😱','جدی؟','دوباره بازی کنیم؟','تسلیم می‌شم','قهرمانی! 🏆','دستت درد نکنه','چه بازی جذابی','داری قوی می‌شی','خوب بود!'];
const STICKERS = ['😀','😂','😎','🤔','😱','😭','🔥','⚡','🏆','👑','💪','👏','🎉','😴','🤯','😅','🤝','🎯','🚀','💯'];
let chatOpen = false, unread = 0, chatTab = 'phrases';
function toggleChat() {
  const panel = document.getElementById('chat-panel');
  chatOpen = !chatOpen;
  panel.classList.toggle('open', chatOpen);
  if (chatOpen) {
    unread = 0; updateUnreadBadge();
    const feed = document.getElementById('chat-feed');
    setTimeout(() => feed.scrollTop = feed.scrollHeight, 100);
  }
}
function closeChat() { document.getElementById('chat-panel').classList.remove('open'); chatOpen = false; }
function switchChatTab(tab) {
  chatTab = tab;
  document.querySelectorAll('#chat-tabs button').forEach((b, i) => {
    b.classList.toggle('active', (i === 0 && tab === 'phrases') || (i === 1 && tab === 'stickers'));
  });
  renderChatContent();
}
function renderChatContent() {
  const el = document.getElementById('chat-content');
  el.innerHTML = ''; el.className = chatTab;
  if (chatTab === 'phrases') {
    PHRASES.forEach(p => {
      const b = document.createElement('button');
      b.textContent = p;
      b.onclick = () => sendChatMessage(p);
      el.appendChild(b);
    });
  } else {
    STICKERS.forEach(s => {
      const b = document.createElement('button');
      b.textContent = s;
      b.onclick = () => sendSticker(s);
      el.appendChild(b);
    });
  }
}
function sendTypedMessage() {
  const input = document.getElementById('chat-input');
  const text = input.value.trim();
  if (!text) return;
  input.value = '';
  sendChatMessage(text);
}
function sendChatMessage(text) {
  if (!G) { toast('اول بازی شروع کن'); return; }
  sfxChat();
  if (G.isAI) {
    addChatMessage(text, true, false, 'me');
    showBubble(text, G.myColor || 'w', false);
    setTimeout(() => {
      const r = ['🤖 ...','حرکت خوبی بود!','در حال محاسبه...','کیش!','جدی؟'][Math.floor(Math.random()*5)];
      sfxReceive();
      addChatMessage(r, false, false, 'them');
      showBubble(r, G.aiColor, false);
    }, 800);
  } else if (G.isOnline) {
    addChatMessage(text, true, false, 'me');
    showBubble(text, G.myColor, false);
    if (window.__conn && window.__conn.open) { try { window.__conn.send({ type: 'chat', text: text }); } catch(e) {} }
  }
}
function sendSticker(emoji) {
  if (!G) { toast('اول بازی شروع کن'); return; }
  sfxSticker();
  if (G.isAI) {
    addChatMessage(emoji, true, true, 'me');
    showBubble(emoji, G.myColor || 'w', true);
  } else if (G.isOnline) {
    addChatMessage(emoji, true, true, 'me');
    showBubble(emoji, G.myColor, true);
    if (window.__conn && window.__conn.open) { try { window.__conn.send({ type: 'sticker', emoji: emoji }); } catch(e) {} }
  }
}
function addChatMessage(content, isMine, isSticker, who) {
  const feed = document.getElementById('chat-feed');
  const div = document.createElement('div');
  let cls = 'chat-msg ';
  if (G && (G.isOnline || G.isAI)) cls += isMine ? 'me' : 'them';
  if (isSticker) cls += ' sticker';
  div.className = cls;
  if (!isSticker) {
    const tag = document.createElement('span');
    tag.className = 'sender-tag';
    if (G && G.isAI) tag.textContent = isMine ? '👤 شما' : '🤖 کامپیوتر';
    else if (G && G.isOnline) tag.textContent = isMine ? '👤 شما' : '👥 حریف';
    div.appendChild(tag);
  }
  div.appendChild(document.createTextNode(content));
  feed.appendChild(div);
  feed.scrollTop = feed.scrollHeight;
  if (!isMine && !chatOpen) { unread++; updateUnreadBadge(); }
}
function updateUnreadBadge() {
  const b1 = document.getElementById('badge-white');
  const b2 = document.getElementById('badge-black');
  const set = (el) => { if (!el) return; if (unread > 0) { el.textContent = toFa(unread); el.style.display = 'flex'; } else el.style.display = 'none'; };
  set(b1); set(b2);
}
function showBubble(text, whoColor, isSticker) {
  let barId;
  if (whoColor === 'w') barId = 'bar-white';
  else if (whoColor === 'b') barId = 'bar-black';
  else barId = G && G.turn === 'w' ? 'bar-white' : 'bar-black';
  const bar = document.getElementById(barId); if (!bar) return;
  const old = bar.querySelector('.speech-bubble'); if (old) old.remove();
  const bubble = document.createElement('div');
  bubble.className = 'speech-bubble' + (isSticker ? ' sticker' : '');
  bubble.textContent = text;
  bar.appendChild(bubble);
  setTimeout(() => {
    bubble.style.transition = 'opacity .4s, transform .4s';
    bubble.style.opacity = '0';
    bubble.style.transform = 'translateY(-8px)';
    setTimeout(() => bubble.remove(), 400);
  }, 3000);
}

/* ============ ابزار ============ */
let toastTimer = null;
function toast(msg) {
  const el = document.getElementById('toast');
  el.textContent = msg;
  el.classList.add('show');
  clearTimeout(toastTimer);
  toastTimer = setTimeout(() => el.classList.remove('show'), 2200);
}
document.getElementById('chat-input').addEventListener('keypress', (e) => { if (e.key === 'Enter') sendTypedMessage(); });

/* ================================================================
   آنلاین — با بروکرهای متعدد و Fallback به AI
================================================================ */
let peer = null, conn = null, myColor = 'w';
let mqttClient = null, myPeerId = null;
let matched = false, attempting = false, wasInitiator = false, onlinePeers = {};
let searchTimerId = null, countIntervalId = null, publishIntervalId = null, searchStartTime = 0;
let libsLoaded = false;
let aiFallbackTimer = null;
let aiFallbackShown = false;

const MQTT_BROKERS = [
  'wss://broker.emqx.io:8084/mqtt',
  'wss://test.mosquitto.org:8081/mqtt',
  'wss://broker.hivemq.com:8884/mqtt',
  'wss://mqtt.eclipseprojects.io:443/mqtt'
];

const ICE_SERVERS = [
  { urls: 'stun:stun.l.google.com:19302' },
  { urls: 'stun:stun1.l.google.com:19302' },
  { urls: 'stun:stun.cloudflare.com:3478' },
  { urls: 'stun:stun.relay.metered.ca:80' },
  { urls: 'stun:openrelay.metered.ca:80' }
];

function loadScript(url) {
  return new Promise((resolve, reject) => {
    const s = document.createElement('script');
    s.src = url; s.onload = resolve;
    s.onerror = () => reject(new Error('fail'));
    document.head.appendChild(s);
    setTimeout(() => reject(new Error('timeout')), 8000);
  });
}
async function ensureLibs() {
  if (libsLoaded) return true;
  const items = [
    ['https://cdn.jsdelivr.net/npm/peerjs@1.5.4/dist/peerjs.min.js', 'https://unpkg.com/peerjs@1.5.4/dist/peerjs.min.js'],
    ['https://cdn.jsdelivr.net/npm/mqtt@4.3.7/dist/mqtt.min.js', 'https://unpkg.com/mqtt@4.3.7/dist/mqtt.min.js']
  ];
  for (const [p, f] of items) {
    try { await loadScript(p); } catch(e) {
      try { await loadScript(f); } catch(e2) { return false; }
    }
  }
  libsLoaded = typeof Peer !== 'undefined' && typeof mqtt !== 'undefined';
  return libsLoaded;
}
function generatePeerId() {
  const chars = 'abcdefghijklmnopqrstuvwxyz0123456789';
  let s = 'shah-';
  for (let i = 0; i < 14; i++) s += chars[Math.floor(Math.random() * chars.length)];
  return s;
}

function setBrokerStatus(txt, color) {
  const el = document.getElementById('broker-status');
  if (el) { el.textContent = txt; el.style.color = color || '#7f8c8d'; }
}

async function findOnlineMatch() {
  initAudio();
  aiFallbackShown = false;
  const status = document.getElementById('search-status');
  const st = document.getElementById('search-timer');
  showScreen('searching');
  status.textContent = '📥 دانلود کتابخانه‌ها...'; status.style.color = '#0a4a8a';
  setBrokerStatus('');

  const ok = await ensureLibs();
  if (!ok) {
    status.textContent = '❌ دانلود ناموفق — اینترنت را چک کن';
    status.style.color = '#e74c3c';
    // بجای گیر کردن، AI پیشنهاد بده
    setTimeout(() => {
      cancelSearch();
      offerAIFallback();
    }, 2500);
    return;
  }
  status.textContent = '🔌 اتصال به سرور...';
  matched = false; attempting = false; wasInitiator = false; onlinePeers = {};
  searchStartTime = Date.now();
  if (searchTimerId) clearInterval(searchTimerId);
  searchTimerId = setInterval(() => {
    const sec = Math.floor((Date.now() - searchStartTime) / 1000);
    st.textContent = toFa(sec) + ' ثانیه';
  }, 500);
  myPeerId = generatePeerId();
  try {
    peer = new Peer(myPeerId, { debug: 0, config: { iceServers: ICE_SERVERS } });
  } catch(e) {
    status.textContent = '❌ خطا'; status.style.color = '#e74c3c';
    setTimeout(() => { cancelSearch(); offerAIFallback(); }, 2000);
    return;
  }
  peer.on('open', () => {
    status.textContent = '⏳ در انتظار حریف...'; status.style.color = '#27ae60';
    connectLobby();
  });
  peer.on('connection', (c) => {
    if (matched) { try { c.close(); } catch(e){} return; }
    matched = true; wasInitiator = false;
    if (aiFallbackTimer) { clearTimeout(aiFallbackTimer); aiFallbackTimer = null; }
    conn = c; window.__conn = c;
    cleanupMatch(); setupOnline();
  });
  peer.on('error', (err) => {
    if (err.type === 'unavailable-id' && !matched) { cleanupPeer(); setTimeout(() => findOnlineMatch(), 500); }
  });
}

/* لیست انتظار — بروکر جایگزین */
function connectLobby() {
  const topic = 'shah-chess-lobby/v4/' + selectedTime + '/' + selectedBet;

  function tryBroker(idx) {
    if (idx >= MQTT_BROKERS.length) {
      setBrokerStatus('⚠️ همه بروکرها ناموفق', '#e74c3c');
      // ۳ ثانیه بعد پیشنهاد AI
      setTimeout(() => { if (!matched && !aiFallbackShown) offerAIFallback(); }, 1500);
      return;
    }
    const url = MQTT_BROKERS[idx];
    setBrokerStatus('در حال اتصال به بروکر ' + toFa(idx + 1) + ' از ' + toFa(MQTT_BROKERS.length) + '...', '#3498db');

    try {
      mqttClient = mqtt.connect(url, {
        clientId: 'shah_' + Math.random().toString(16).slice(2, 10),
        clean: true,
        reconnectPeriod: 0,
        connectTimeout: 5000
      });
    } catch(e) {
      tryBroker(idx + 1);
      return;
    }

    let connected = false;
    const timeout = setTimeout(() => {
      if (!connected && !matched) {
        try { mqttClient.end(true); } catch(e){}
        tryBroker(idx + 1);
      }
    }, 6000);

    mqttClient.on('connect', () => {
      connected = true;
      clearTimeout(timeout);
      setBrokerStatus('✅ متصل به بروکر ' + toFa(idx + 1), '#27ae60');
      mqttClient.subscribe(topic, { qos: 0 });
      publishPresence();
      if (publishIntervalId) clearInterval(publishIntervalId);
      publishIntervalId = setInterval(publishPresence, 2000);

      // ۱۵ ثانیه صبر کن، اگر کسی پیدا نشد پیشنهاد AI
      if (aiFallbackTimer) clearTimeout(aiFallbackTimer);
      aiFallbackTimer = setTimeout(() => {
        if (!matched && !attempting && !aiFallbackShown) offerAIFallback();
      }, 15000);
    });

    mqttClient.on('message', (t, message) => {
      if (matched || attempting || t !== topic) return;
      try {
        const data = JSON.parse(message.toString());
        if (!data.peerId || data.peerId === myPeerId) return;
        if (Date.now() - data.ts > 8000) return;
        onlinePeers[data.peerId] = Date.now();
        updateOnlineCount();
        if (myPeerId > data.peerId && !matched && !attempting) {
          wasInitiator = true;
          tryConnect(data.peerId);
        }
      } catch(e) {}
    });

    mqttClient.on('error', () => {
      clearTimeout(timeout);
      if (!connected && !matched) {
        try { mqttClient.end(true); } catch(e){}
        tryBroker(idx + 1);
      }
    });
  }

  tryBroker(0);

  if (countIntervalId) clearInterval(countIntervalId);
  countIntervalId = setInterval(() => {
    const now = Date.now();
    for (const id in onlinePeers) {
      if (now - onlinePeers[id] > 7000) delete onlinePeers[id];
    }
    updateOnlineCount();
  }, 2000);
}

function publishPresence() {
  if (matched || !mqttClient || !mqttClient.connected) return;
  const topic = 'shah-chess-lobby/v4/' + selectedTime + '/' + selectedBet;
  mqttClient.publish(topic, JSON.stringify({ peerId: myPeerId, ts: Date.now(), time: selectedTime, bet: selectedBet }));
}
function updateOnlineCount() {
  const n = Object.keys(onlinePeers).length + 1;
  const el = document.getElementById('online-count');
  if (el) el.textContent = toFa(n);
}
function tryConnect(remoteId) {
  if (matched || attempting) return;
  attempting = true;
  let c;
  try { c = peer.connect(remoteId, { reliable: true }); }
  catch(e) { attempting = false; return; }
  const timeout = setTimeout(() => { attempting = false; try { c.close(); } catch(e) {} }, 6000);
  c.on('open', () => {
    clearTimeout(timeout);
    if (matched) { try { c.close(); } catch(e) {} return; }
    matched = true;
    if (aiFallbackTimer) { clearTimeout(aiFallbackTimer); aiFallbackTimer = null; }
    conn = c; window.__conn = c;
    cleanupMatch(); setupOnline();
  });
  c.on('error', () => { clearTimeout(timeout); attempting = false; });
}
function cleanupMatch() {
  if (publishIntervalId) { clearInterval(publishIntervalId); publishIntervalId = null; }
  if (countIntervalId) { clearInterval(countIntervalId); countIntervalId = null; }
  if (mqttClient) { try { mqttClient.end(true); } catch(e) {} mqttClient = null; }
  if (searchTimerId) { clearInterval(searchTimerId); searchTimerId = null; }
  if (aiFallbackTimer) { clearTimeout(aiFallbackTimer); aiFallbackTimer = null; }
}
function cleanupPeer() {
  cleanupMatch();
  try { if (conn) conn.close(); } catch(e) {}
  try { if (peer) peer.destroy(); } catch(e) {}
  conn = null; peer = null; window.__conn = null;
}
window.__closeConn = cleanupPeer;
function cancelSearch() {
  cleanupPeer();
  matched = false; attempting = false;
  const m = document.getElementById('ai-fallback-modal');
  if (m) m.remove();
  aiFallbackShown = false;
  showScreen('home');
}

/* ============ پیشنهاد بازی با AI ============ */
function offerAIFallback() {
  if (matched || aiFallbackShown) return;
  aiFallbackShown = true;

  // اگر قبلاً ساخته شده، حذف کن
  const old = document.getElementById('ai-fallback-modal');
  if (old) old.remove();

  const modal = document.createElement('div');
  modal.id = 'ai-fallback-modal';
  modal.className = 'modal show';
  modal.innerHTML = `
    <div class="box">
      <h3>😕 حریفی پیدا نشد</h3>
      <p>
        در حال حاضر بازیکن دیگری آنلاین نیست.<br>
        می‌خواهی با کامپیوتر بازی کنی؟
      </p>
      <div class="btns" style="flex-direction:column;">
        <button class="primary" onclick="acceptAIFallback()">🤖 بله، با کامپیوتر</button>
        <button class="secondary" onclick="continueWaiting()">⏳ بیشتر صبر کن (۱۵ ثانیه)</button>
        <button class="secondary" onclick="cancelAndBack()">❌ لغو</button>
      </div>
    </div>
  `;
  document.body.appendChild(modal);
}

function acceptAIFallback() {
  const m = document.getElementById('ai-fallback-modal');
  if (m) m.remove();
  cleanupPeer();
  matched = false; attempting = false;
  // مستقیماً بازی با AI با سطح متوسط شروع کن
  aiDepth = 2;
  startAIGameDirect();
}

function startAIGameDirect() {
  flipped = false;
  G = newGameState(selectedTime, selectedBet, false, 'w', true, 'b');
  const ns = document.getElementById('net-status');
  ns.style.display = 'inline-flex'; ns.classList.add('ai');
  const depthName = aiDepth === 1 ? 'آسان' : (aiDepth === 2 ? 'متوسط' : 'سخت');
  ns.textContent = '🤖 کامپیوتر — ' + depthName;
  document.getElementById('chat-feed').innerHTML = '';
  unread = 0; updateUnreadBadge(); renderChatContent();
  document.getElementById('chat-who').textContent = 'چت با کامپیوتر 🤖';
  document.getElementById('name-white').innerHTML = 'شما<span class="level-badge" id="lvl-white">Lv.' + toFa(G.white.level) + '</span>';
  document.getElementById('name-black').innerHTML = '🤖 کامپیوتر<span class="level-badge" id="lvl-black">Lv.' + toFa(G.black.level) + '</span>';
  document.getElementById('avatar-black').textContent = '🤖';
  document.getElementById('avatar-white').textContent = '👤';
  document.getElementById('bar-black').classList.add('ai');
  updateCoinDisplays(); updateTimers(); render(); updateStatus();
  showScreen('game');
  startTimer();
  toast(`🤖 بازی با کامپیوتر (${depthName})`);
}

function continueWaiting() {
  const m = document.getElementById('ai-fallback-modal');
  if (m) m.remove();
  aiFallbackShown = false;
  // ۱۵ ثانیه دیگر صبر کن
  aiFallbackTimer = setTimeout(() => {
    if (!matched && !attempting) offerAIFallback();
  }, 15000);
}

function cancelAndBack() {
  const m = document.getElementById('ai-fallback-modal');
  if (m) m.remove();
  cancelSearch();
}

/* ============ اتصال آنلاین ============ */
function setupOnline() {
  sfxConnect();
  document.getElementById('search-status').textContent = '🎉 حریف پیدا شد!';
  conn.on('data', handleRemote);
  conn.on('close', () => {
    toast('حریف قطع شد');
    if (G && !G.gameOver) endGame(myColor, 'حریف قطع شد');
  });
  myColor = wasInitiator ? 'b' : 'w';
  if (myColor === 'w') {
    try {
      conn.send({ type: 'settings', time: selectedTime, bet: selectedBet });
    } catch(e) {}
  }
  setTimeout(() => initOnline(), 400);
}
function handleRemote(data) {
  if (!data) return;
  if (data.type === 'move') {
    if (!G) return;
    G.white.time = data.timeW; G.black.time = data.timeB;
    G.selected = null; G.legalMoves = [];
    executeMove(data.move, data.promoType, true);
    updateTimers();
  } else if (data.type === 'resign') {
    if (!G || G.gameOver) return;
    sfxWin(); endGame(G.myColor, 'حریف تسلیم شد');
  } else if (data.type === 'settings') {
    selectedTime = data.time; selectedBet = data.bet;
  } else if (data.type === 'chat') {
    sfxReceive();
    addChatMessage(data.text, false, false, 'them');
    showBubble(data.text, myColor === 'w' ? 'b' : 'w', false);
    if (!chatOpen) toast('💬 حریف: ' + data.text);
  } else if (data.type === 'sticker') {
    sfxSticker();
    addChatMessage(data.emoji, false, true, 'them');
    showBubble(data.emoji, myColor === 'w' ? 'b' : 'w', true);
    if (!chatOpen) toast('😀 استیکر: ' + data.emoji);
  }
}
function initOnline() {
  flipped = (myColor === 'b');
  G = newGameState(selectedTime, selectedBet, true, myColor, false, null);
  updateCoinDisplays(); updateTimers(); updateLevelBadges(); render(); updateStatus();
  showScreen('game');
  const ns = document.getElementById('net-status');
  ns.style.display = 'inline-flex'; ns.classList.remove('ai');
  ns.textContent = 'آنلاین — ' + (myColor === 'w' ? 'سفید' : 'سیاه');
  document.getElementById('chat-feed').innerHTML = '';
  unread = 0; updateUnreadBadge(); renderChatContent();
  document.getElementById('chat-who').textContent = 'با حریف (' + (myColor === 'w' ? 'سیاه' : 'سفید') + ')';
  document.getElementById('name-white').innerHTML = (myColor === 'w' ? 'شما' : 'حریف') + '<span class="level-badge" id="lvl-white">Lv.۱</span>';
  document.getElementById('name-black').innerHTML = (myColor === 'b' ? 'شما' : 'حریف') + '<span class="level-badge" id="lvl-black">Lv.۱</span>';
  document.getElementById('avatar-black').textContent = '♚';
  document.getElementById('avatar-white').textContent = '♔';
  document.getElementById('bar-black').classList.remove('ai');
  startTimer();
  toast(`🎯 شروع! شما ${myColor === 'w' ? 'سفید' : 'سیاه'} هستید`);
}

/* ============ راه‌اندازی ============ */
document.addEventListener('pointerdown', () => initAudio(), { once: true });
document.addEventListener('touchstart', () => initAudio(), { once: true });
window.addEventListener('beforeunload', () => cleanupPeer());
renderChatContent();
refreshStatsUI();
</script>
</body>
</html>

Game Source: ♛ شطرنج آنلاین رادین عباسیان

Creator: CrystalPanda39

Libraries: none

Complexity: complex (2172 lines, 92.0 KB)

The full source code is displayed above on this page.

Remix Instructions

To remix this game, copy the source code above and modify it. Add a ARCADELAB header at the top with "remix_of: game-crystalpanda39" to link back to the original. Then publish at arcadelab.ai/publish.