<?php // 此文件仅为纯前端展示 ?>
<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>石头剪刀布 · 人机/联机双模式</title>
    <!-- 优先使用 CDN Font Awesome -->
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css" integrity="sha512-iecdLmaskl7CVkqkXNQ/ZH/XLlvWZOJyj7Yy7tcenmpD1ypASozpmT/E0iPtmFIB46ZmdtAc9eNBvH0H/ZpiBw==" crossorigin="anonymous" referrerpolicy="no-referrer">
    <!-- 本地备份 -->
    <link rel="stylesheet" href="css/all.min.css">
    <style>
        /* ========== 原有样式完全保留 ========== */
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
        }
        
        :root {
            --primary: #6c5ce7;
            --secondary: #a29bfe;
            --accent: #fd79a8;
            --light: #f7f7f7;
            --dark: #2d3436;
            --success: #00b894;
            --warning: #fdcb6e;
            --danger: #e17055;
            --shadow: 0 10px 20px rgba(0,0,0,0.1);
            --radius: 12px;
            --bg-primary: #f0f2f5;
            --bg-panel: #ffffff;
            --text-primary: #2d3436;
            --text-secondary: #636e72;
        }
        
        /* 深色主题 */
        .theme-dark {
            --primary: #6c5ce7;
            --secondary: #a29bfe;
            --accent: #fd79a8;
            --light: #2d3436;
            --dark: #f7f7f7;
            --success: #00b894;
            --warning: #fdcb6e;
            --danger: #e17055;
            --shadow: 0 10px 20px rgba(0,0,0,0.3);
            --bg-primary: #1a1a2e;
            --bg-panel: #16213e;
            --text-primary: #f7f7f7;
            --text-secondary: #b2bec3;
        }
        
        /* 红色主题 */
        .theme-red {
            --primary: #e74c3c;
            --secondary: #e67e22;
            --accent: #f1c40f;
            --light: #f7f7f7;
            --dark: #2d3436;
            --success: #e74c3c;
            --warning: #e67e22;
            --danger: #c0392b;
            --shadow: 0 10px 20px rgba(231, 76, 60, 0.1);
            --bg-primary: #fff5f5;
            --bg-panel: #ffffff;
            --text-primary: #2d3436;
            --text-secondary: #636e72;
        }
        
        /* 绿色主题 */
        .theme-green {
            --primary: #27ae60;
            --secondary: #2ecc71;
            --accent: #f1c40f;
            --light: #f7f7f7;
            --dark: #2d3436;
            --success: #27ae60;
            --warning: #f39c12;
            --danger: #c0392b;
            --shadow: 0 10px 20px rgba(39, 174, 96, 0.1);
            --bg-primary: #f0fff4;
            --bg-panel: #ffffff;
            --text-primary: #2d3436;
            --text-secondary: #636e72;
        }
        
        /* 蓝色主题 */
        .theme-blue {
            --primary: #3498db;
            --secondary: #2980b9;
            --accent: #9b59b6;
            --light: #f7f7f7;
            --dark: #2d3436;
            --success: #3498db;
            --warning: #f39c12;
            --danger: #e74c3c;
            --shadow: 0 10px 20px rgba(52, 152, 219, 0.1);
            --bg-primary: #f0f8ff;
            --bg-panel: #ffffff;
            --text-primary: #2d3436;
            --text-secondary: #636e72;
        }
        
        body {
            background: var(--bg-primary);
            color: var(--text-primary);
            min-height: 100vh;
            padding: 20px;
            display: flex;
            flex-direction: column;
            line-height: 1.6;
            transition: all 0.3s ease;
        }
        
        .container {
            max-width: 900px;
            margin: 0 auto;
            flex: 1;
            display: flex;
            flex-direction: column;
            gap: 25px;
            position: relative;
        }
        
        header {
            text-align: center;
            padding: 25px 0;
            color: white;
            background: rgba(255, 255, 255, 0.1);
            border-radius: var(--radius);
            backdrop-filter: blur(10px);
            box-shadow: var(--shadow);
        }
        
        h1 {
            font-size: 2.8rem;
            text-shadow: 2px 2px 4px rgba(0, 0, 0, 0.3);
            margin-bottom: 10px;
            background: linear-gradient(to right, #fff, var(--accent));
            -webkit-background-clip: text;
            -webkit-text-fill-color: transparent;
        }
        
        .subtitle {
            font-size: 1.2rem;
            opacity: 0.9;
            max-width: 600px;
            margin: 0 auto;
        }
        
        /* 模式切换标签 */
        .mode-tabs {
            display: flex;
            justify-content: center;
            gap: 20px;
            margin-top: 20px;
        }
        .mode-tab {
            padding: 12px 30px;
            border-radius: 40px;
            background: rgba(255,255,255,0.2);
            color: white;
            font-weight: bold;
            cursor: pointer;
            transition: 0.3s;
            backdrop-filter: blur(5px);
            border: 2px solid transparent;
        }
        .mode-tab.active {
            background: var(--primary);
            border-color: white;
            box-shadow: 0 0 20px var(--primary);
        }
        
        .theme-selector {
            position: fixed;
            top: 50%;
            right: 20px;
            transform: translateY(-50%);
            display: flex;
            flex-direction: column;
            gap: 10px;
            background: rgba(255, 255, 255, 0.1);
            padding: 15px;
            border-radius: var(--radius);
            backdrop-filter: blur(10px);
            z-index: 100;
        }
        
        .theme-label {
            color: white;
            font-size: 0.9rem;
            text-align: center;
            margin-bottom: 5px;
        }
        
        .theme-btn {
            width: 30px;
            height: 30px;
            border-radius: 50%;
            border: 2px solid rgba(255, 255, 255, 0.5);
            cursor: pointer;
            transition: all 0.3s ease;
        }
        
        .theme-btn:hover {
            transform: scale(1.1);
            border-color: white;
        }
        
        .theme-btn.active {
            border-color: white;
            transform: scale(1.1);
        }
        
        .theme-light { background: linear-gradient(135deg, #6c5ce7, #a29bfe); }
        .theme-dark { background: linear-gradient(135deg, #2d3436, #636e72); }
        .theme-red { background: linear-gradient(135deg, #e74c3c, #e67e22); }
        .theme-green { background: linear-gradient(135deg, #27ae60, #2ecc71); }
        .theme-blue { background: linear-gradient(135deg, #3498db, #2980b9); }
        
        .panel {
            background: var(--bg-panel);
            border-radius: var(--radius);
            padding: 25px;
            box-shadow: var(--shadow);
            transition: transform 0.3s ease, box-shadow 0.3s ease;
        }
        
        .panel:hover {
            transform: translateY(-5px);
            box-shadow: 0 15px 30px rgba(0,0,0,0.15);
        }
        
        .panel-title {
            font-size: 1.6rem;
            margin-bottom: 20px;
            color: var(--primary);
            display: flex;
            align-items: center;
            justify-content: space-between;
            gap: 10px;
            border-bottom: 2px solid rgba(0,0,0,0.1);
            padding-bottom: 15px;
        }
        
        .panel-title i {
            color: var(--accent);
        }
        
        .panel-actions {
            display: flex;
            gap: 10px;
        }
        
        .action-btn {
            background: var(--primary);
            color: white;
            border: none;
            border-radius: var(--radius);
            padding: 8px 15px;
            font-size: 0.9rem;
            cursor: pointer;
            transition: all 0.3s ease;
            display: flex;
            align-items: center;
            gap: 5px;
        }
        
        .action-btn:hover {
            background: var(--secondary);
        }
        
        .action-btn.danger {
            background: var(--danger);
        }
        
        .action-btn.danger:hover {
            background: #c0392b;
        }
        
        .mode-selector {
            display: flex;
            flex-direction: column;
            gap: 15px;
        }
        
        .mode-btn {
            padding: 18px;
            background: linear-gradient(135deg, var(--primary), var(--secondary));
            color: white;
            border: none;
            border-radius: var(--radius);
            font-size: 1.1rem;
            cursor: pointer;
            transition: all 0.3s ease;
            display: flex;
            align-items: center;
            justify-content: center;
            gap: 15px;
            box-shadow: 0 4px 10px rgba(108, 92, 231, 0.3);
        }
        
        .mode-btn:hover {
            transform: translateY(-3px);
            box-shadow: 0 6px 15px rgba(108, 92, 231, 0.4);
        }
        
        .mode-btn i {
            font-size: 1.5rem;
        }
        
        .form-group {
            margin-bottom: 20px;
        }
        
        label {
            display: block;
            margin-bottom: 10px;
            font-weight: 600;
            color: var(--text-primary);
        }
        
        input, select {
            width: 100%;
            padding: 14px;
            border: 2px solid #e0e0e0;
            border-radius: var(--radius);
            font-size: 1rem;
            transition: border 0.3s ease;
            background: var(--bg-panel);
            color: var(--text-primary);
        }
        
        input:focus, select:focus {
            border-color: var(--primary);
            outline: none;
        }
        
        .btn {
            padding: 14px 24px;
            background: linear-gradient(135deg, var(--primary), var(--secondary));
            color: white;
            border: none;
            border-radius: var(--radius);
            font-size: 1rem;
            font-weight: 600;
            cursor: pointer;
            transition: all 0.3s ease;
            display: inline-flex;
            align-items: center;
            justify-content: center;
            gap: 8px;
            box-shadow: 0 4px 10px rgba(108, 92, 231, 0.3);
        }
        
        .btn:hover {
            transform: translateY(-2px);
            box-shadow: 0 6px 15px rgba(108, 92, 231, 0.4);
        }
        
        .btn-success {
            background: linear-gradient(135deg, var(--success), #00a085);
        }
        
        .btn-danger {
            background: linear-gradient(135deg, var(--danger), #d35400);
        }
        
        .btn:disabled {
            background: #cccccc;
            cursor: not-allowed;
            transform: none;
            box-shadow: none;
        }
        
        .room-info {
            background: rgba(0,0,0,0.05);
            border-radius: var(--radius);
            padding: 20px;
            margin-bottom: 20px;
            border-left: 5px solid var(--primary);
        }
        
        .room-code {
            font-size: 1.8rem;
            font-weight: bold;
            color: var(--primary);
            text-align: center;
            margin-bottom: 10px;
            font-family: 'Courier New', monospace;
        }
        
        .players-list {
            display: flex;
            flex-direction: column;
            gap: 12px;
            margin-bottom: 25px;
        }
        
        .player-card {
            display: flex;
            align-items: center;
            padding: 15px;
            background: rgba(0,0,0,0.05);
            border-radius: var(--radius);
            box-shadow: 0 2px 8px rgba(0,0,0,0.05);
            transition: transform 0.2s ease;
            border-left: 4px solid var(--primary);
        }
        
        .player-card:hover {
            transform: translateX(5px);
        }
        
        .player-avatar {
            width: 50px;
            height: 50px;
            border-radius: 50%;
            background: linear-gradient(135deg, var(--primary), var(--secondary));
            display: flex;
            align-items: center;
            justify-content: center;
            color: white;
            font-weight: bold;
            margin-right: 15px;
            font-size: 1.2rem;
            box-shadow: 0 4px 8px rgba(0,0,0,0.1);
        }
        
        .player-name {
            flex: 1;
            font-weight: 600;
            font-size: 1.1rem;
        }
        
        .player-status {
            font-size: 0.9rem;
            color: var(--text-secondary);
        }
        
        .game-area {
            display: flex;
            flex-direction: column;
            align-items: center;
            gap: 25px;
        }
        
        .game-info {
            display: flex;
            justify-content: space-between;
            width: 100%;
            background: rgba(0,0,0,0.05);
            padding: 15px;
            border-radius: var(--radius);
            margin-bottom: 10px;
        }
        
        .score-display {
            text-align: center;
            font-size: 1.2rem;
            font-weight: bold;
        }
        
        .score-value {
            font-size: 2rem;
            color: var(--primary);
        }
        
        .choices {
            display: flex;
            gap: 20px;
            justify-content: center;
            flex-wrap: wrap;
            margin: 20px 0;
        }
        
        .choice-btn {
            width: 120px;
            height: 120px;
            border-radius: 50%;
            border: none;
            background: white;
            box-shadow: 0 8px 20px rgba(0,0,0,0.1);
            font-size: 3rem;
            cursor: pointer;
            transition: all 0.3s ease;
            display: flex;
            align-items: center;
            justify-content: center;
            position: relative;
            overflow: hidden;
        }
        
        .choice-btn::before {
            content: '';
            position: absolute;
            top: 0;
            left: 0;
            right: 0;
            bottom: 0;
            background: linear-gradient(135deg, rgba(255,255,255,0.2), transparent);
            border-radius: 50%;
        }
        
        .choice-btn:hover {
            transform: translateY(-8px) scale(1.05);
            box-shadow: 0 15px 25px rgba(0,0,0,0.15);
        }
        
        .choice-btn.rock {
            background: linear-gradient(135deg, #ff9f43, #e67e22);
            color: white;
        }
        
        .choice-btn.paper {
            background: linear-gradient(135deg, #54a0ff, #2e86de);
            color: white;
        }
        
        .choice-btn.scissors {
            background: linear-gradient(135deg, #ff6b6b, #ee5a52);
            color: white;
        }
        
        .choice-btn:disabled {
            transform: none;
            box-shadow: 0 4px 10px rgba(0,0,0,0.1);
            opacity: 0.7;
            cursor: not-allowed;
        }
        
        .ai-thinking {
            display: flex;
            flex-direction: column;
            align-items: center;
            gap: 15px;
            padding: 20px;
            background: rgba(0,0,0,0.05);
            border-radius: var(--radius);
            width: 100%;
            margin: 20px 0;
        }
        
        .thinking-text {
            font-size: 1.2rem;
            font-weight: 600;
            color: var(--primary);
        }
        
        .thinking-dots {
            display: flex;
            gap: 8px;
        }
        
        .dot {
            width: 12px;
            height: 12px;
            border-radius: 50%;
            background: var(--primary);
            animation: pulse 1.5s infinite ease-in-out;
        }
        
        .dot:nth-child(2) {
            animation-delay: 0.2s;
        }
        
        .dot:nth-child(3) {
            animation-delay: 0.4s;
        }
        
        @keyframes pulse {
            0%, 100% { transform: scale(1); opacity: 0.7; }
            50% { transform: scale(1.3); opacity: 1; }
        }
        
        .result-area {
            text-align: center;
            padding: 25px;
            background: var(--bg-panel);
            border-radius: var(--radius);
            box-shadow: var(--shadow);
            width: 100%;
            margin-top: 20px;
        }
        
        .result-text {
            font-size: 1.8rem;
            font-weight: bold;
            margin-bottom: 15px;
        }
        
        .result-text.win {
            color: var(--success);
        }
        
        .result-text.lose {
            color: var(--danger);
        }
        
        .result-text.draw {
            color: var(--warning);
        }
        
        .choices-display {
            display: flex;
            justify-content: space-around;
            margin: 25px 0;
        }
        
        .choice-display {
            text-align: center;
            flex: 1;
        }
        
        .choice-icon {
            font-size: 4rem;
            margin-bottom: 10px;
        }
        
        .player-name-display {
            font-weight: bold;
            font-size: 1.2rem;
        }
        
        .history-list {
            max-height: 400px;
            overflow-y: auto;
            padding-right: 10px;
        }
        
        .history-item {
            padding: 15px;
            border-bottom: 1px solid rgba(0,0,0,0.1);
            display: flex;
            justify-content: space-between;
            align-items: center;
            transition: background 0.2s ease;
        }
        
        .history-item:hover {
            background: rgba(0,0,0,0.05);
        }
        
        .history-result {
            font-weight: bold;
            padding: 5px 12px;
            border-radius: 20px;
        }
        
        .history-result.win {
            background: rgba(0, 184, 148, 0.1);
            color: var(--success);
        }
        
        .history-result.lose {
            background: rgba(225, 112, 85, 0.1);
            color: var(--danger);
        }
        
        .history-result.draw {
            background: rgba(253, 203, 110, 0.1);
            color: #e67e22;
        }
        
        footer {
            text-align: center;
            padding: 25px 0;
            color: white;
            font-size: 0.95rem;
            margin-top: 30px;
            background: rgba(255, 255, 255, 0.1);
            border-radius: var(--radius);
            backdrop-filter: blur(10px);
        }
        
        .footer-link {
            color: white;
            text-decoration: none;
            margin: 0 5px;
            transition: color 0.3s ease;
        }
        
        .footer-link:hover {
            color: var(--accent);
            text-decoration: underline;
        }
        
        .hidden {
            display: none !important;
        }
        
        .notification {
            position: fixed;
            top: 20px;
            right: 20px;
            padding: 15px 25px;
            background: var(--success);
            color: white;
            border-radius: var(--radius);
            box-shadow: 0 10px 25px rgba(0,0,0,0.2);
            z-index: 1000;
            transform: translateX(150%);
            transition: transform 0.4s ease;
            display: flex;
            align-items: center;
            gap: 10px;
        }
        
        .notification.show {
            transform: translateX(0);
        }
        
        .notification.error {
            background: var(--danger);
        }
        
        .progress-bar {
            height: 5px;
            background: rgba(255,255,255,0.5);
            border-radius: 10px;
            overflow: hidden;
            margin-top: 10px;
        }
        
        .progress {
            height: 100%;
            background: white;
            width: 100%;
            animation: progress 5s linear;
        }
        
        @keyframes progress {
            from { width: 100%; }
            to { width: 0%; }
        }

        /* ===== 新增聊天样式 ===== */
        .chat-container {
            margin-top: 25px;
            border-top: 1px solid rgba(0,0,0,0.1);
            padding-top: 20px;
        }
        .chat-messages {
            height: 200px;
            overflow-y: auto;
            background: rgba(0,0,0,0.03);
            border-radius: var(--radius);
            padding: 15px;
            margin-bottom: 15px;
            font-size: 0.95rem;
        }
        .chat-message {
            margin-bottom: 10px;
            word-wrap: break-word;
        }
        .chat-message .player {
            font-weight: bold;
            color: var(--primary);
        }
        .chat-message .time {
            font-size: 0.75rem;
            color: var(--text-secondary);
            margin-left: 8px;
        }
        .chat-input-area {
            display: flex;
            gap: 10px;
        }
        .chat-input-area input {
            flex: 1;
            padding: 12px;
            border: 2px solid #e0e0e0;
            border-radius: var(--radius);
            background: var(--bg-panel);
            color: var(--text-primary);
        }
        .chat-input-area button {
            padding: 12px 20px;
            background: var(--primary);
            color: white;
            border: none;
            border-radius: var(--radius);
            cursor: pointer;
            transition: 0.3s;
        }
        .chat-input-area button:hover {
            background: var(--secondary);
        }
        .online-action-buttons {
            display: flex;
            gap: 10px;
            justify-content: center;
            margin-top: 20px;
        }
        
        @media (max-width: 768px) {
            .container {
                gap: 15px;
            }
            
            .panel {
                padding: 20px;
            }
            
            h1 {
                font-size: 2.2rem;
            }
            
            .theme-selector {
                position: static;
                flex-direction: row;
                justify-content: center;
                margin-top: 15px;
                transform: none;
                background: transparent;
                padding: 0;
            }
            
            .theme-label {
                display: none;
            }
            
            .choices {
                gap: 10px;
            }
            
            .choice-btn {
                width: 100px;
                height: 100px;
                font-size: 2.5rem;
            }
            
            .game-info {
                flex-direction: column;
                gap: 15px;
            }
            
            .panel-title {
                flex-direction: column;
                align-items: flex-start;
                gap: 15px;
            }
            
            .panel-actions {
                width: 100%;
                justify-content: flex-end;
            }
        }

        /* ===== 备用图标样式 ===== */
        .icon-fallback {
            display: inline-block;
            width: 1em;
            height: 1em;
            background-color: currentColor;
            mask-size: contain;
            -webkit-mask-size: contain;
            mask-repeat: no-repeat;
            -webkit-mask-repeat: no-repeat;
            mask-position: center;
            -webkit-mask-position: center;
            vertical-align: middle;
        }
        .icon-server {
            mask-image: url('data:image/svg+xml;utf8,<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 512 512"><path d="M480 160c0-17.7-14.3-32-32-32H64c-17.7 0-32 14.3-32 32v192c0 17.7 14.3 32 32 32h384c17.7 0 32-14.3 32-32V160zM64 96h384c35.3 0 64 28.7 64 64v192c0 35.3-28.7 64-64 64H64c-35.3 0-64-28.7-64-64V160c0-35.3 28.7-64 64-64zm32 240c-13.3 0-24 10.7-24 24s10.7 24 24 24 24-10.7 24-24-10.7-24-24-24zm0-96c-13.3 0-24 10.7-24 24s10.7 24 24 24 24-10.7 24-24-10.7-24-24-24zm0-96c-13.3 0-24 10.7-24 24s10.7 24 24 24 24-10.7 24-24-10.7-24-24-24z"/></svg>');
            -webkit-mask-image: url('data:image/svg+xml;utf8,<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 512 512"><path d="M480 160c0-17.7-14.3-32-32-32H64c-17.7 0-32 14.3-32 32v192c0 17.7 14.3 32 32 32h384c17.7 0 32-14.3 32-32V160zM64 96h384c35.3 0 64 28.7 64 64v192c0 35.3-28.7 64-64 64H64c-35.3 0-64-28.7-64-64V160c0-35.3 28.7-64 64-64zm32 240c-13.3 0-24 10.7-24 24s10.7 24 24 24 24-10.7 24-24-10.7-24-24-24zm0-96c-13.3 0-24 10.7-24 24s10.7 24 24 24 24-10.7 24-24-10.7-24-24-24zm0-96c-13.3 0-24 10.7-24 24s10.7 24 24 24 24-10.7 24-24-10.7-24-24-24z"/></svg>');
        }
    </style>
</head>
<body>
    <div class="container">
        <header>
            <h1><i class="fas fa-hand-rock"></i> 石头剪刀布 · 双模式</h1>
            <div class="subtitle">人机对战 或 在线联机，经典玩法全新体验</div>
            <div class="mode-tabs">
                <span class="mode-tab active" id="tab-vs-ai">🤖 人机模式</span>
                <span class="mode-tab" id="tab-online">🌐 联机模式</span>
            </div>
        </header>
        
        <!-- ========== 人机模式面板 ========== -->
        <div class="panel" id="mode-panel">
            <h2 class="panel-title"><i class="fas fa-robot"></i> 开始人机对战</h2>
            <div class="form-group">
                <label for="player-name"><i class="fas fa-user"></i> 你的用户名</label>
                <input type="text" id="player-name" placeholder="输入你的用户名" value="玩家">
            </div>
            <div class="form-group">
                <label for="game-mode"><i class="fas fa-trophy"></i> 胜利规则</label>
                <select id="game-mode">
                    <option value="1">一局定胜负</option>
                    <option value="3">三局两胜</option>
                    <option value="5" selected>五局三胜</option>
                    <option value="10">十局六胜</option>
                </select>
            </div>
            <button class="btn" id="start-game-btn"><i class="fas fa-play"></i> 开始游戏</button>
        </div>
        
        <!-- 人机对战面板 -->
        <div class="panel hidden" id="game-panel">
            <h2 class="panel-title"><i class="fas fa-gamepad"></i> 人机对战进行中</h2>
            <div class="game-info">
                <div class="score-display">
                    <div>玩家得分</div>
                    <div class="score-value" id="player-score">0</div>
                </div>
                <div class="score-display">
                    <div>当前轮次</div>
                    <div class="score-value" id="current-round">1/<span id="total-rounds">5</span></div>
                </div>
                <div class="score-display">
                    <div>AI得分</div>
                    <div class="score-value" id="ai-score">0</div>
                </div>
            </div>
            
            <div class="game-area">
                <div class="choices">
                    <button class="choice-btn rock" data-choice="rock">✊</button>
                    <button class="choice-btn paper" data-choice="paper">✋</button>
                    <button class="choice-btn scissors" data-choice="scissors">✌️</button>
                </div>
                
                <div class="ai-thinking hidden" id="ai-thinking">
                    <div class="thinking-text">AI思考中...</div>
                    <div class="thinking-dots">
                        <div class="dot"></div>
                        <div class="dot"></div>
                        <div class="dot"></div>
                    </div>
                    <div class="progress-bar">
                        <div class="progress"></div>
                    </div>
                </div>
                
                <div class="result-area hidden" id="result-area">
                    <div class="result-text" id="result-text">你赢了！</div>
                    <div class="choices-display">
                        <div class="choice-display">
                            <div class="choice-icon" id="player-choice-icon">✊</div>
                            <div class="player-name-display" id="player-choice-name">你</div>
                        </div>
                        <div class="choice-display">
                            <div style="font-size: 2rem; margin-top: 20px;">VS</div>
                        </div>
                        <div class="choice-display">
                            <div class="choice-icon" id="ai-choice-icon">✌️</div>
                            <div class="player-name-display" id="ai-choice-name">AI玩家</div>
                        </div>
                    </div>
                    <button class="btn" id="next-round-btn"><i class="fas fa-forward"></i> 下一轮</button>
                </div>
            </div>
        </div>
        
        <!-- ========== 联机模式面板 ========== -->
        <!-- 联机大厅（创建/加入房间） -->
        <div class="panel hidden" id="online-lobby-panel">
            <h2 class="panel-title"><i class="fas fa-globe"></i> 联机大厅</h2>
            <div style="display: flex; gap: 20px; flex-wrap: wrap;">
                <!-- 创建房间 -->
                <div style="flex:1; min-width:250px;">
                    <h3><i class="fas fa-plus-circle"></i> 创建房间</h3>
                    <div class="form-group">
                        <label>你的昵称</label>
                        <input type="text" id="online-name" placeholder="输入昵称" value="玩家">
                    </div>
                    <div class="form-group">
                        <label>游戏模式</label>
                        <select id="online-mode">
                            <option value="1">一局定胜负</option>
                            <option value="3">三局两胜</option>
                            <option value="5" selected>五局三胜</option>
                            <option value="10">十局六胜</option>
                        </select>
                    </div>
                    <div class="form-group" style="flex-direction:row; align-items:center;">
                        <input type="checkbox" id="online-private" style="width:auto; margin-right:10px;">
                        <label for="online-private" style="display:inline; margin:0;">私密房间（需密码）</label>
                    </div>
                    <div class="form-group" id="online-password-group" style="display:none;">
                        <label>房间密码</label>
                        <input type="text" id="online-password" placeholder="输入密码">
                    </div>
                    <button class="btn" id="create-room-btn" style="width:100%;"><i class="fas fa-door-open"></i> 创建房间</button>
                </div>
                <!-- 加入房间 -->
                <div style="flex:1; min-width:250px;">
                    <h3><i class="fas fa-sign-in-alt"></i> 加入房间</h3>
                    <div class="form-group">
                        <label>你的昵称</label>
                        <input type="text" id="join-name" placeholder="输入昵称" value="玩家">
                    </div>
                    <div class="form-group">
                        <label>房间号</label>
                        <input type="text" id="join-room-code" placeholder="6位数字" maxlength="6">
                    </div>
                    <div class="form-group">
                        <label>密码（如有）</label>
                        <input type="text" id="join-password" placeholder="密码">
                    </div>
                    <button class="btn" id="join-room-btn" style="width:100%;"><i class="fas fa-door-closed"></i> 加入房间</button>
                </div>
            </div>
        </div>
        
        <!-- 联机游戏面板（包含聊天） -->
        <div class="panel hidden" id="online-game-panel">
            <h2 class="panel-title">
                <span><i class="fas fa-users"></i> 联机对战 · 房间 <span id="online-room-code-display">------</span></span>
                <button class="action-btn" id="online-leave-btn"><i class="fas fa-sign-out-alt"></i> 离开</button>
            </h2>
            <div class="game-info">
                <div class="score-display">
                    <div id="online-player-name">我</div>
                    <div class="score-value" id="online-player-score">0</div>
                </div>
                <div class="score-display">
                    <div>第 <span id="online-current-round">1</span>/<span id="online-max-rounds">5</span> 轮</div>
                    <div style="font-size:1rem;" id="online-opponent-status">等待对手...</div>
                </div>
                <div class="score-display">
                    <div id="online-opponent-name">对手</div>
                    <div class="score-value" id="online-opponent-score">0</div>
                </div>
            </div>
            
            <div class="game-area">
                <div class="choices">
                    <button class="choice-btn rock" data-choice="rock">✊</button>
                    <button class="choice-btn paper" data-choice="paper">✋</button>
                    <button class="choice-btn scissors" data-choice="scissors">✌️</button>
                </div>
                
                <div class="result-area hidden" id="online-result-area">
                    <div class="result-text" id="online-result-text"></div>
                </div>
            </div>

            <!-- 新增聊天区域 -->
            <div class="chat-container">
                <div class="chat-messages" id="chat-messages"></div>
                <div class="chat-input-area">
                    <input type="text" id="chat-input" placeholder="输入消息..." maxlength="200">
                    <button id="chat-send-btn"><i class="fas fa-paper-plane"></i> 发送</button>
                </div>
            </div>

            <!-- 游戏结束后操作按钮 -->
            <div class="online-action-buttons hidden" id="online-gameover-buttons">
                <button class="btn" id="online-rematch-btn"><i class="fas fa-redo-alt"></i> 再玩一局</button>
                <button class="btn btn-danger" id="online-back-to-lobby-btn"><i class="fas fa-door-open"></i> 返回大厅</button>
            </div>
        </div>
        
        <!-- 战绩记录面板（通用） -->
        <div class="panel">
            <h2 class="panel-title">
                <span><i class="fas fa-history"></i> 战绩记录</span>
                <div class="panel-actions">
                    <button class="action-btn danger" id="clear-history-btn"><i class="fas fa-trash"></i> 清除记录</button>
                </div>
            </h2>
            <div class="history-list" id="history-list"><!-- 动态生成 --></div>
        </div>
        
        <footer>
            <div>© 2025 帆船石头剪刀布 · 人机/联机双模式 · 聊天版</div>
            <div><a href="https://beian.miit.gov.cn/" class="footer-link" target="_blank">粤ICP备2025466846号-2</a></div>
        </footer>
    </div>
    
    <!-- 主题选择器 -->
    <div class="theme-selector">
        <div class="theme-label">主题</div>
        <div class="theme-btn theme-light active" data-theme="default"></div>
        <div class="theme-btn theme-dark" data-theme="dark"></div>
        <div class="theme-btn theme-red" data-theme="red"></div>
        <div class="theme-btn theme-green" data-theme="green"></div>
        <div class="theme-btn theme-blue" data-theme="blue"></div>
    </div>
    
    <!-- 通知 -->
    <div class="notification" id="notification"><i class="fas fa-check-circle"></i><div></div></div>

    <script>
        // ================== 全局变量 ==================
        // 人机对战状态
        const gameState = {
            currentPanel: 'mode',
            playerName: '玩家',
            gameMode: 5,
            players: [],
            currentRound: 0,
            playerScore: 0,
            aiScore: 0,
            gameHistory: [],
            maxRounds: 5,
            requiredWins: 3,
            currentTheme: 'default',
            gameFinished: false,
            nonDrawRounds: 0
        };

        // 联机对战状态
        const onlineState = {
            roomCode: null,
            playerToken: null,
            playerNo: null,      // 1或2
            playerName: '',
            opponentName: '',
            mode: 5,
            status: 'waiting',
            currentRound: 1,
            maxRounds: 5,
            requiredWins: 3,
            playerScore: 0,
            opponentScore: 0,
            myChoice: null,
            opponentChoiced: false,
            gameFinished: false,
            pollInterval: null,
            resultSaved: false    // 标记是否已保存记录，避免重复保存
        };

        // 聊天相关变量
        let chatPollInterval = null;
        let lastMessageId = 0;

        // AI玩家名称库
        const aiNames = ['AI-Alex', 'AI-Taylor', 'AI-Jordan', 'AI-Casey', 'AI-Morgan', 'AI-DeepSeek-R1', 'AI-Avery', 'AI-DeepSeek-V3', 'AI-Charlie', '[彩蛋1]AI-Lihua','AI-Dakota', 'AI-Skyler', 'AI-Finley', 'AI-Emerson', 'AI-Rowan', 'AI-Sawyer', 'AI-Phoenix', 'AI-Blake', 'AI-Hayden', 'AI-Mike', 'AI-Ariel', 'AI-Peyton', 'AI-Dream','[彩蛋2]AI-Fanchuan','AI-Steve','AI-Drew'];

        // DOM 元素 - 人机
        const modePanel = document.getElementById('mode-panel');
        const gamePanel = document.getElementById('game-panel');
        const playerNameInput = document.getElementById('player-name');
        const gameModeSelect = document.getElementById('game-mode');
        const startGameBtn = document.getElementById('start-game-btn');
        const choiceBtns = document.querySelectorAll('#game-panel .choice-btn');
        const aiThinking = document.getElementById('ai-thinking');
        const resultArea = document.getElementById('result-area');
        const resultText = document.getElementById('result-text');
        const playerChoiceIcon = document.getElementById('player-choice-icon');
        const aiChoiceIcon = document.getElementById('ai-choice-icon');
        const playerChoiceName = document.getElementById('player-choice-name');
        const aiChoiceName = document.getElementById('ai-choice-name');
        const nextRoundBtn = document.getElementById('next-round-btn');
        const historyList = document.getElementById('history-list');
        const playerScoreDisplay = document.getElementById('player-score');
        const aiScoreDisplay = document.getElementById('ai-score');
        const currentRoundDisplay = document.getElementById('current-round');
        const totalRoundsDisplay = document.getElementById('total-rounds');
        const clearHistoryBtn = document.getElementById('clear-history-btn');

        // DOM 元素 - 联机
        const tabVsAi = document.getElementById('tab-vs-ai');
        const tabOnline = document.getElementById('tab-online');
        const onlineLobby = document.getElementById('online-lobby-panel');
        const onlineGame = document.getElementById('online-game-panel');
        const onlineName = document.getElementById('online-name');
        const onlineMode = document.getElementById('online-mode');
        const onlinePrivate = document.getElementById('online-private');
        const onlinePasswordGroup = document.getElementById('online-password-group');
        const onlinePassword = document.getElementById('online-password');
        const createRoomBtn = document.getElementById('create-room-btn');
        const joinName = document.getElementById('join-name');
        const joinRoomCode = document.getElementById('join-room-code');
        const joinPassword = document.getElementById('join-password');
        const joinRoomBtn = document.getElementById('join-room-btn');
        const onlineLeaveBtn = document.getElementById('online-leave-btn');
        const onlineRoomCodeDisplay = document.getElementById('online-room-code-display');
        const onlinePlayerNameSpan = document.getElementById('online-player-name');
        const onlineOpponentNameSpan = document.getElementById('online-opponent-name');
        const onlinePlayerScore = document.getElementById('online-player-score');
        const onlineOpponentScore = document.getElementById('online-opponent-score');
        const onlineCurrentRound = document.getElementById('online-current-round');
        const onlineMaxRounds = document.getElementById('online-max-rounds');
        const onlineOpponentStatus = document.getElementById('online-opponent-status');
        const onlineChoiceBtns = document.querySelectorAll('#online-game-panel .choice-btn');
        const onlineResultArea = document.getElementById('online-result-area');
        const onlineResultText = document.getElementById('online-result-text');
        const onlineRematchBtn = document.getElementById('online-rematch-btn');
        const onlineBackToLobbyBtn = document.getElementById('online-back-to-lobby-btn');
        const onlineGameoverButtons = document.getElementById('online-gameover-buttons');

        // 聊天DOM
        const chatMessages = document.getElementById('chat-messages');
        const chatInput = document.getElementById('chat-input');
        const chatSendBtn = document.getElementById('chat-send-btn');

        // 通用
        const notification = document.getElementById('notification');
        const themeButtons = document.querySelectorAll('.theme-btn');

        // ================== 初始化 ==================
        document.addEventListener('DOMContentLoaded', () => {
            // 加载人机历史记录
            loadGameHistory();
            // 加载主题
            loadTheme();
            
            // 人机事件
            startGameBtn.addEventListener('click', startGameVsAI);
            nextRoundBtn.addEventListener('click', nextRoundVsAI);
            clearHistoryBtn.addEventListener('click', clearHistory);
            gameModeSelect.addEventListener('change', updateGameMode);
            choiceBtns.forEach(btn => btn.addEventListener('click', (e) => playRoundVsAI(e.target.dataset.choice)));

            // 联机事件
            tabVsAi.addEventListener('click', () => switchMode('ai'));
            tabOnline.addEventListener('click', () => switchMode('online'));
            onlinePrivate.addEventListener('change', () => {
                onlinePasswordGroup.style.display = onlinePrivate.checked ? 'block' : 'none';
            });
            createRoomBtn.addEventListener('click', createRoom);
            joinRoomBtn.addEventListener('click', joinRoom);
            onlineLeaveBtn.addEventListener('click', leaveOnlineGame);
            onlineRematchBtn.addEventListener('click', rematch);
            onlineBackToLobbyBtn.addEventListener('click', () => switchMode('online'));
            onlineChoiceBtns.forEach(btn => btn.addEventListener('click', (e) => makeOnlineMove(e.target.dataset.choice)));

            // 聊天事件
            chatSendBtn.addEventListener('click', sendChatMessage);
            chatInput.addEventListener('keypress', (e) => {
                if (e.key === 'Enter') sendChatMessage();
            });

            // 主题切换
            themeButtons.forEach(btn => btn.addEventListener('click', () => changeTheme(btn.dataset.theme)));
        });

        // ================== 工具函数 ==================
        function showNotification(msg, isError = false) {
            const noti = document.getElementById('notification');
            noti.querySelector('div').textContent = msg;
            noti.className = 'notification' + (isError ? ' error' : '');
            noti.classList.add('show');
            setTimeout(() => noti.classList.remove('show'), 3000);
        }

        function hideAllPanels() {
            modePanel.classList.add('hidden');
            gamePanel.classList.add('hidden');
            onlineLobby.classList.add('hidden');
            onlineGame.classList.add('hidden');
        }

        function switchMode(mode) {
            if (mode === 'ai') {
                tabVsAi.classList.add('active');
                tabOnline.classList.remove('active');
                hideAllPanels();
                modePanel.classList.remove('hidden');
                // 如果正在联机轮询，停止
                if (onlineState.pollInterval) {
                    clearInterval(onlineState.pollInterval);
                    onlineState.pollInterval = null;
                }
                stopChatPolling();
            } else {
                tabOnline.classList.add('active');
                tabVsAi.classList.remove('active');
                hideAllPanels();
                onlineLobby.classList.remove('hidden');
                // 重置联机状态
                onlineState.roomCode = null;
                onlineState.playerToken = null;
                onlineState.resultSaved = false;
                stopChatPolling();
            }
        }

        // ================== 人机对战逻辑 ==================
        function updateGameMode() {
            const mode = gameState.gameMode;
            if (mode === 1) { gameState.maxRounds = 1; gameState.requiredWins = 1; }
            else if (mode === 3) { gameState.maxRounds = 3; gameState.requiredWins = 2; }
            else if (mode === 5) { gameState.maxRounds = 5; gameState.requiredWins = 3; }
            else if (mode === 10) { gameState.maxRounds = 10; gameState.requiredWins = 6; }
            totalRoundsDisplay.textContent = gameState.maxRounds;
        }

        function startGameVsAI() {
            gameState.playerName = playerNameInput.value.trim() || '玩家';
            gameState.gameMode = parseInt(gameModeSelect.value);
            updateGameMode();
            gameState.currentRound = 0;
            gameState.playerScore = 0;
            gameState.aiScore = 0;
            gameState.nonDrawRounds = 0;
            gameState.gameFinished = false;
            const randomName = aiNames[Math.floor(Math.random() * aiNames.length)];
            gameState.players = [{ name: gameState.playerName, isAI: false }, { name: randomName, isAI: true }];
            playerScoreDisplay.textContent = '0';
            aiScoreDisplay.textContent = '0';
            aiChoiceName.textContent = randomName;
            hideAllPanels();
            gamePanel.classList.remove('hidden');
            tabVsAi.classList.add('active');
            tabOnline.classList.remove('active');
            nextRoundVsAI();
            showNotification(`${randomName} 已加入对战！`);
        }

        function nextRoundVsAI() {
            if (gameState.gameFinished) { restartGame(); return; }
            gameState.currentRound++;
            if (gameState.playerScore >= gameState.requiredWins || gameState.aiScore >= gameState.requiredWins || gameState.nonDrawRounds >= gameState.maxRounds) {
                endGameVsAI(); return;
            }
            currentRoundDisplay.textContent = `${gameState.currentRound}`;
            resultArea.classList.add('hidden');
            aiThinking.classList.add('hidden');
            choiceBtns.forEach(btn => btn.disabled = false);
            document.querySelector('#game-panel .panel-title').innerHTML = `<i class="fas fa-gamepad"></i> 第 ${gameState.currentRound} 轮 - 请选择你的出拳`;
        }

        function playRoundVsAI(playerChoice) {
            choiceBtns.forEach(btn => btn.disabled = true);
            const choiceMap = { rock:'✊', paper:'✋', scissors:'✌️' };
            playerChoiceIcon.textContent = choiceMap[playerChoice];
            playerChoiceName.textContent = gameState.playerName;
            aiThinking.classList.remove('hidden');
            setTimeout(() => {
                const aiPlayer = gameState.players.find(p => p.isAI);
                const choices = ['rock','paper','scissors'];
                const aiChoice = choices[Math.floor(Math.random()*3)];
                aiChoiceIcon.textContent = choiceMap[aiChoice];
                aiChoiceName.textContent = aiPlayer.name;
                aiThinking.classList.add('hidden');
                const result = determineWinner(playerChoice, aiChoice);
                if (result === 'win') { gameState.playerScore++; playerScoreDisplay.textContent = gameState.playerScore; resultText.textContent = '你赢了！'; resultText.className = 'result-text win'; gameState.nonDrawRounds++; }
                else if (result === 'lose') { gameState.aiScore++; aiScoreDisplay.textContent = gameState.aiScore; resultText.textContent = '你输了！'; resultText.className = 'result-text lose'; gameState.nonDrawRounds++; }
                else { resultText.textContent = '平局！'; resultText.className = 'result-text draw'; }
                resultArea.classList.remove('hidden');
                saveGameResult(result, playerChoice, aiChoice, aiPlayer.name);
                if (gameState.playerScore >= gameState.requiredWins || gameState.aiScore >= gameState.requiredWins || gameState.nonDrawRounds >= gameState.maxRounds) {
                    nextRoundBtn.textContent = '查看结果'; gameState.gameFinished = true;
                } else { nextRoundBtn.textContent = '下一轮'; }
            }, 3000);
        }

        function determineWinner(p, a) {
            if (p === a) return 'draw';
            if ((p==='rock'&&a==='scissors')||(p==='paper'&&a==='rock')||(p==='scissors'&&a==='paper')) return 'win';
            return 'lose';
        }

        function endGameVsAI() {
            let finalResult;
            if (gameState.playerScore > gameState.aiScore) { finalResult='win'; resultText.textContent = `恭喜！你以 ${gameState.playerScore}:${gameState.aiScore} 获胜！`; resultText.className='result-text win'; }
            else if (gameState.playerScore < gameState.aiScore) { finalResult='lose'; resultText.textContent = `很遗憾！AI以 ${gameState.aiScore}:${gameState.playerScore} 获胜！`; resultText.className='result-text lose'; }
            else { finalResult='draw'; resultText.textContent = `平局！比分 ${gameState.playerScore}:${gameState.aiScore}`; resultText.className='result-text draw'; }
            saveGameResult(finalResult, '', '', 'AI玩家', true);
            nextRoundBtn.textContent = '再来一局';
            resultArea.classList.remove('hidden');
            gameState.gameFinished = true;
        }

        function restartGame() { switchMode('ai'); }

        // 战绩记录（人机用）
        function saveGameResult(result, playerChoice, aiChoice, aiName, isFinal=false) {
            const record = {
                date: new Date().toLocaleString(),
                result,
                playerChoice,
                aiChoice,
                aiName,
                round: gameState.currentRound,
                playerScore: gameState.playerScore,
                aiScore: gameState.aiScore,
                isFinal,
                gameMode: gameState.gameMode,
                gameType: 'ai'   // 标记为人机
            };
            gameState.gameHistory.unshift(record);
            localStorage.setItem('rpsGameHistory', JSON.stringify(gameState.gameHistory));
            updateHistoryList();
        }

        // 联机战绩保存
        function saveOnlineGameResult(data) {
            const myScore = (onlineState.playerNo === 1) ? data.player1.score : data.player2.score;
            const oppScore = (onlineState.playerNo === 1) ? data.player2.score : data.player1.score;
            const myName = onlineState.playerName;
            const oppName = (onlineState.playerNo === 1) ? data.player2.name : data.player1.name;
            
            let result;
            if (data.winner === onlineState.playerNo) result = 'win';
            else if (data.winner === 0) result = 'draw';
            else result = 'lose';

            const record = {
                date: new Date().toLocaleString(),
                result,
                playerScore: myScore,
                opponentScore: oppScore,
                playerName: myName,
                opponentName: oppName,
                gameMode: onlineState.mode,
                isFinal: true,
                gameType: 'online'  // 标记为联机
            };
            gameState.gameHistory.unshift(record);
            localStorage.setItem('rpsGameHistory', JSON.stringify(gameState.gameHistory));
            updateHistoryList();
        }

        function loadGameHistory() {
            const saved = localStorage.getItem('rpsGameHistory');
            if (saved) { gameState.gameHistory = JSON.parse(saved); updateHistoryList(); }
        }

        function updateHistoryList() {
            historyList.innerHTML = '';
            if (!gameState.gameHistory.length) {
                historyList.innerHTML = '<div style="text-align:center; padding:20px; color:var(--text-secondary);">暂无游戏记录</div>';
                return;
            }
            gameState.gameHistory.forEach(r => {
                const item = document.createElement('div');
                item.className = 'history-item';
                const resultClass = r.result==='win'?'win':r.result==='lose'?'lose':'draw';
                
                let displayText = '';
                if (r.gameType === 'online') {
                    displayText = `联机 ${r.playerName} vs ${r.opponentName} · 最终 ${r.playerScore}:${r.opponentScore}`;
                } else {
                    if (r.isFinal) {
                        displayText = `人机最终结果: ${r.playerScore} - ${r.aiScore}`;
                    } else {
                        const choiceMap = { rock:'✊ 石头', paper:'✋ 布', scissors:'✌️ 剪刀' };
                        displayText = `第${r.round}轮: ${choiceMap[r.playerChoice]} vs ${choiceMap[r.aiChoice]}`;
                    }
                }
                
                const modeText = getGameModeText(r.gameMode);
                
                item.innerHTML = `
                    <div>
                        <div>${displayText}</div>
                        <div style="font-size:0.85rem;color:var(--text-secondary);">${r.date} · ${modeText}</div>
                    </div>
                    <div class="history-result ${resultClass}">${r.result==='win'?'胜利':r.result==='lose'?'失败':'平局'}${r.isFinal ? ` (${r.playerScore}:${r.aiScore||r.opponentScore})` : ''}</div>
                `;
                historyList.appendChild(item);
            });
        }

        function getGameModeText(mode) {
            switch(mode) {
                case 1: return "一局定胜负";
                case 3: return "三局两胜";
                case 5: return "五局三胜";
                case 10: return "十局六胜";
                default: return "未知模式";
            }
        }

        function clearHistory() {
            if (confirm('确定清除所有历史记录？')) {
                gameState.gameHistory = [];
                localStorage.removeItem('rpsGameHistory');
                updateHistoryList();
                showNotification('历史记录已清除');
            }
        }

        // ================== 联机功能 ==================
        function createRoom() {
            const name = onlineName.value.trim() || '玩家';
            const mode = parseInt(onlineMode.value);
            const isPrivate = onlinePrivate.checked ? 1 : 0;
            const password = onlinePassword.value;

            fetch('api.php?action=create_room', {
                method: 'POST',
                headers: {'Content-Type': 'application/x-www-form-urlencoded'},
                body: `name=${encodeURIComponent(name)}&mode=${mode}&is_private=${isPrivate}&password=${encodeURIComponent(password)}`
            })
            .then(res => res.json())
            .then(data => {
                if (data.error) { alert(data.error); return; }
                onlineState.roomCode = data.room_code;
                onlineState.playerToken = data.player_token;
                onlineState.playerNo = data.player;
                onlineState.playerName = name;
                onlineState.mode = mode;
                onlineState.resultSaved = false;
                startPolling();
                enterOnlineGamePanel();
                showNotification(`房间创建成功！房间号：${data.room_code}`);
            })
            .catch(err => showNotification('网络错误', true));
        }

        function joinRoom() {
            const roomCode = joinRoomCode.value.trim();
            const name = joinName.value.trim() || '玩家';
            const password = joinPassword.value;
            if (!roomCode) { alert('请输入房间号'); return; }

            fetch('api.php?action=join_room', {
                method: 'POST',
                headers: {'Content-Type': 'application/x-www-form-urlencoded'},
                body: `room_code=${roomCode}&name=${encodeURIComponent(name)}&password=${encodeURIComponent(password)}`
            })
            .then(res => res.json())
            .then(data => {
                if (data.error) { alert(data.error); return; }
                onlineState.roomCode = data.room_code;
                onlineState.playerToken = data.player_token;
                onlineState.playerNo = data.player;
                onlineState.playerName = name;
                onlineState.mode = parseInt(onlineMode.value); // 实际mode由房间决定，但这里先设置
                onlineState.resultSaved = false;
                startPolling();
                enterOnlineGamePanel();
                showNotification(`成功加入房间 ${roomCode}`);
            })
            .catch(err => showNotification('网络错误', true));
        }

        function enterOnlineGamePanel() {
            hideAllPanels();
            onlineGame.classList.remove('hidden');
            onlineRoomCodeDisplay.textContent = onlineState.roomCode;
            onlinePlayerNameSpan.textContent = onlineState.playerName;
            onlineOpponentNameSpan.textContent = '等待对手...';
            onlinePlayerScore.textContent = '0';
            onlineOpponentScore.textContent = '0';
            onlineCurrentRound.textContent = '1';
            onlineMaxRounds.textContent = getMaxRounds(onlineState.mode);
            onlineOpponentStatus.textContent = '等待对手加入...';
            onlineChoiceBtns.forEach(btn => btn.disabled = true);
            onlineResultArea.classList.add('hidden');
            onlineGameoverButtons.classList.add('hidden');
            // 清空聊天
            chatMessages.innerHTML = '';
            lastMessageId = 0;
            startChatPolling();
        }

        function getMaxRounds(mode) {
            if (mode===1) return 1;
            if (mode===3) return 3;
            if (mode===5) return 5;
            return 10;
        }

        function startPolling() {
            if (onlineState.pollInterval) clearInterval(onlineState.pollInterval);
            onlineState.pollInterval = setInterval(pollGameStatus, 2000);
        }

        function pollGameStatus() {
            if (!onlineState.roomCode || !onlineState.playerToken) return;
            fetch(`api.php?action=get_status&room_code=${onlineState.roomCode}&player_token=${onlineState.playerToken}`)
            .then(res => res.json())
            .then(data => {
                if (data.error) {
                    console.error(data.error);
                    if (data.error === '房间不存在') {
                        clearInterval(onlineState.pollInterval);
                        onlineState.pollInterval = null;
                        alert('房间已失效');
                        switchMode('online');
                    }
                    return;
                }
                updateOnlineUI(data);
            })
            .catch(err => console.error('Poll error', err));
        }

        function updateOnlineUI(data) {
            // 更新基本信息
            onlineState.status = data.status;
            onlineState.currentRound = data.current_round;
            onlineState.maxRounds = data.max_rounds;
            onlineState.requiredWins = data.required_wins;
            
            // 更新得分
            if (data.player1 && data.player2) {
                onlineOpponentNameSpan.textContent = (onlineState.playerNo === 1) ? data.player2.name : data.player1.name;
                if (onlineState.playerNo === 1) {
                    onlinePlayerScore.textContent = data.player1.score;
                    onlineOpponentScore.textContent = data.player2.score;
                } else {
                    onlinePlayerScore.textContent = data.player2.score;
                    onlineOpponentScore.textContent = data.player1.score;
                }
            } else {
                onlineOpponentNameSpan.textContent = '等待对手...';
            }

            onlineCurrentRound.textContent = data.current_round;
            onlineMaxRounds.textContent = data.max_rounds;

            // 判断对方是否已出拳
            let opponentHasChoiced = false;
            if (data.player2) {
                if (onlineState.playerNo === 1) opponentHasChoiced = data.player2.has_choiced;
                else opponentHasChoiced = data.player1.has_choiced;
            }
            onlineOpponentStatus.textContent = opponentHasChoiced ? '已出拳' : (data.player2 ? '思考中...' : '等待对手加入');

            // 根据游戏状态启用/禁用按钮
            if (data.status === 'playing' && data.player2) {
                const myHasChoiced = (onlineState.playerNo === 1) ? data.player1.has_choiced : data.player2.has_choiced;
                onlineChoiceBtns.forEach(btn => btn.disabled = myHasChoiced);
            } else {
                onlineChoiceBtns.forEach(btn => btn.disabled = true);
            }

            // 如果游戏结束，显示结果并保存记录，显示操作按钮
            if (data.status === 'finished') {
                if (!onlineState.resultSaved) {
                    onlineState.resultSaved = true;
                    saveOnlineGameResult(data);
                }
                // 显示结果文本（可选）
                if (data.result === 'win') onlineResultText.textContent = '你赢了！';
                else if (data.result === 'lose') onlineResultText.textContent = '你输了...';
                else onlineResultText.textContent = '平局';
                onlineResultArea.classList.remove('hidden');
                onlineGameoverButtons.classList.remove('hidden');
            } else {
                onlineResultArea.classList.add('hidden');
                onlineGameoverButtons.classList.add('hidden');
            }
        }

        function makeOnlineMove(choice) {
            fetch('api.php?action=make_move', {
                method: 'POST',
                headers: {'Content-Type': 'application/x-www-form-urlencoded'},
                body: `room_code=${onlineState.roomCode}&player_token=${onlineState.playerToken}&choice=${choice}`
            })
            .then(res => res.json())
            .then(data => {
                if (data.error) {
                    alert(data.error);
                } else {
                    onlineChoiceBtns.forEach(btn => btn.disabled = true);
                }
            })
            .catch(err => showNotification('网络错误', true));
        }

        function leaveOnlineGame() {
            if (onlineState.pollInterval) {
                clearInterval(onlineState.pollInterval);
                onlineState.pollInterval = null;
            }
            stopChatPolling();
            switchMode('online');
        }

        // 再玩一局（重置房间）
        function rematch() {
            fetch('api.php?action=reset_room', {
                method: 'POST',
                headers: {'Content-Type': 'application/x-www-form-urlencoded'},
                body: `room_code=${onlineState.roomCode}&player_token=${onlineState.playerToken}`
            })
            .then(res => res.json())
            .then(data => {
                if (data.success) {
                    // 重置成功，重新开始轮询状态，隐藏游戏结束按钮
                    onlineGameoverButtons.classList.add('hidden');
                    onlineState.resultSaved = false;
                    startPolling();
                } else {
                    alert(data.error || '重置失败');
                }
            })
            .catch(() => alert('网络错误'));
        }

        // ================== 聊天功能 ==================
        function sendChatMessage() {
            const msg = chatInput.value.trim();
            if (!msg || !onlineState.roomCode || !onlineState.playerToken) return;

            fetch('api.php?action=send_message', {
                method: 'POST',
                headers: {'Content-Type': 'application/x-www-form-urlencoded'},
                body: `room_code=${onlineState.roomCode}&player_token=${onlineState.playerToken}&message=${encodeURIComponent(msg)}`
            })
            .then(res => res.json())
            .then(data => {
                if (data.success) {
                    chatInput.value = '';
                } else {
                    alert(data.error || '发送失败');
                }
            })
            .catch(() => alert('网络错误'));
        }

        function startChatPolling() {
            if (chatPollInterval) clearInterval(chatPollInterval);
            chatPollInterval = setInterval(pollChatMessages, 2000);
        }

        function stopChatPolling() {
            if (chatPollInterval) {
                clearInterval(chatPollInterval);
                chatPollInterval = null;
            }
        }

        function pollChatMessages() {
            if (!onlineState.roomCode) return;
            fetch(`api.php?action=get_messages&room_code=${onlineState.roomCode}&last_id=${lastMessageId}`)
            .then(res => res.json())
            .then(data => {
                if (data.success && data.messages.length > 0) {
                    appendChatMessages(data.messages);
                    lastMessageId = data.messages[data.messages.length-1].id;
                }
            })
            .catch(err => console.error('Chat poll error', err));
        }

        function appendChatMessages(messages) {
            messages.forEach(msg => {
                const div = document.createElement('div');
                div.className = 'chat-message';
                const time = new Date(msg.created_at).toLocaleTimeString();
                div.innerHTML = `<span class="player">${escapeHtml(msg.player_name)}</span><span class="time">${time}</span><br>${escapeHtml(msg.message)}`;
                chatMessages.appendChild(div);
            });
            chatMessages.scrollTop = chatMessages.scrollHeight;
        }

        function escapeHtml(unsafe) {
            return unsafe.replace(/[&<>"]/g, function(m) {
                if(m === '&') return '&amp;';
                if(m === '<') return '&lt;';
                if(m === '>') return '&gt;';
                if(m === '"') return '&quot;';
                return m;
            });
        }

        // ================== 主题 ==================
        function changeTheme(theme) {
            document.body.classList.remove('theme-dark','theme-red','theme-green','theme-blue');
            if (theme !== 'default') document.body.classList.add(`theme-${theme}`);
            localStorage.setItem('rpsTheme', theme);
            themeButtons.forEach(btn => {
                btn.classList.toggle('active', btn.dataset.theme === theme);
            });
        }

        function loadTheme() {
            const saved = localStorage.getItem('rpsTheme');
            changeTheme(saved || 'default');
        }

        // 备用图标检测
        (function() {
            function fixMissingIcons() {
                const testIcon = document.createElement('i');
                testIcon.className = 'fas fa-check';
                document.body.appendChild(testIcon);
                const computed = window.getComputedStyle(testIcon, '::before');
                const content = computed.content;
                document.body.removeChild(testIcon);
                if (content === 'none' || content === 'normal') {
                    console.warn('Font Awesome未加载，启用备用图标');
                    document.querySelectorAll('.fas').forEach(icon => {
                        icon.style.display = 'none';
                        const fallback = document.createElement('span');
                        fallback.className = 'icon-fallback icon-server me-2';
                        icon.parentNode?.insertBefore(fallback, icon);
                    });
                }
            }
            setTimeout(fixMissingIcons, 1500);
        })();
    </script>
</body>
</html>