<?php
$pageTitle = '双卡通3D数字人婚礼司仪';
require_once 'header.php';
?>

<main class="site-main">
    <section class="page-banner dh-banner">
        <div class="container">
            <h1>👰🤵 双卡通数字人婚礼司仪</h1>
            <p>AI主持人「喜乐」与「喜庆」—— 双人联袂主持，为您的婚礼增添更多温馨与欢乐
                <a href="digital_human_double_screen.php" target="_blank" style="display:inline-block;margin-left:16px;padding:6px 18px;background:rgba(212,168,83,0.2);border:1px solid rgba(212,168,83,0.5);border-radius:20px;color:#d4a853;font-size:13px;text-decoration:none;vertical-align:middle;">📺 大屏展示模式</a>
            </p>
        </div>
    </section>

    <section class="dh-section">
        <div class="container">
            <div class="dh-layout-double">
                <div class="dh-avatar-panel-double">
                    <div class="avatars-container">
                        <div class="avatar-wrapper" id="groomWrapper">
                            <div class="dh-avatar-card groom-card">
                                <div class="dh-avatar" id="groomAvatar">
                                    <div class="avatar-body groom-body">
                                        <div class="avatar-head groom-head">
                                            <div class="avatar-face" id="groomFace">
                                                <div class="avatar-eyes groom-eyes">
                                                    <span class="eye left"></span>
                                                    <span class="eye right"></span>
                                                </div>
                                                <div class="avatar-mouth" id="groomMouth"></div>
                                            </div>
                                        </div>
                                        <div class="avatar-torso groom-torso">
                                            <div class="avatar-tie groom-tie"></div>
                                        </div>
                                    </div>
                                </div>
                                <div class="dh-emotion-indicator" id="groomEmotion">
                                    <span class="emotion-dot"></span>
                                    <span class="emotion-text">温暖</span>
                                </div>
                                <div class="dh-avatar-name">喜乐</div>
                                <div class="dh-avatar-role">婚礼主持（男）</div>
                            </div>
                        </div>

                        <div class="couple-decoration">
                            <span class="decor-heart">💕</span>
                        </div>

                        <div class="avatar-wrapper" id="brideWrapper">
                            <div class="dh-avatar-card bride-card">
                                <div class="dh-avatar" id="brideAvatar">
                                    <div class="avatar-body bride-body">
                                        <div class="avatar-head bride-head">
                                            <div class="avatar-face" id="brideFace">
                                                <div class="avatar-eyes bride-eyes">
                                                    <span class="eye left"></span>
                                                    <span class="eye right"></span>
                                                </div>
                                                <div class="avatar-mouth" id="brideMouth"></div>
                                            </div>
                                            <div class="avatar-veil"></div>
                                        </div>
                                        <div class="avatar-torso bride-torso">
                                            <div class="avatar-dress"></div>
                                        </div>
                                    </div>
                                </div>
                                <div class="dh-emotion-indicator" id="brideEmotion">
                                    <span class="emotion-dot"></span>
                                    <span class="emotion-text">甜蜜</span>
                                </div>
                                <div class="dh-avatar-name">喜庆</div>
                                <div class="dh-avatar-role">婚礼主持（女）</div>
                            </div>
                        </div>
                    </div>

                    <div class="dh-phase-control">
                        <h3><i class="fas fa-list-ol"></i> 婚礼环节</h3>
                        <div class="phase-list" id="phaseList">
                            <button class="phase-btn" data-phase="opening" data-emotion="warm">
                                <span class="phase-icon">🎊</span>
                                <span class="phase-name">开场白</span>
                            </button>
                            <button class="phase-btn" data-phase="bride_entrance" data-emotion="romantic">
                                <span class="phase-icon">👰</span>
                                <span class="phase-name">新娘入场</span>
                            </button>
                            <button class="phase-btn" data-phase="vow" data-emotion="romantic">
                                <span class="phase-icon">💕</span>
                                <span class="phase-name">誓言环节</span>
                            </button>
                            <button class="phase-btn" data-phase="ring" data-emotion="solemn">
                                <span class="phase-icon">💍</span>
                                <span class="phase-name">交换戒指</span>
                            </button>
                            <button class="phase-btn" data-phase="parent_tea" data-emotion="warm">
                                <span class="phase-icon">🍵</span>
                                <span class="phase-name">敬茶改口</span>
                            </button>
                            <button class="phase-btn" data-phase="toast" data-emotion="joyful">
                                <span class="phase-icon">🥂</span>
                                <span class="phase-name">祝酒环节</span>
                            </button>
                            <button class="phase-btn" data-phase="game" data-emotion="joyful">
                                <span class="phase-icon">🎮</span>
                                <span class="phase-name">互动游戏</span>
                            </button>
                            <button class="phase-btn" data-phase="closing" data-emotion="warm">
                                <span class="phase-icon">🎉</span>
                                <span class="phase-name">圆满礼成</span>
                            </button>
                        </div>

                        <div class="voice-settings">
                            <h3><i class="fas fa-microphone-alt"></i> 语音设置</h3>
                            <label class="voice-toggle">
                                <input type="checkbox" id="autoSpeak" checked>
                                <span>自动朗读主持词</span>
                            </label>
                            <div class="voice-slider-group">
                                <label>男主持人音色</label>
                                <select id="ttsVoiceMale" class="voice-select">
                                    <option value="charles" selected>🎙️ 磁性男声</option>
                                    <option value="alex">🎵 沉稳男声</option>
                                    <option value="benjamin">🔊 低沉男声</option>
                                    <option value="david">🎉 欢快男声</option>
                                </select>
                            </div>
                            <div class="voice-slider-group">
                                <label>女主持人音色</label>
                                <select id="ttsVoiceFemale" class="voice-select">
                                    <option value="claire" selected>🌸 温柔女声</option>
                                    <option value="anna">💼 沉稳女声</option>
                                    <option value="bella">🔥 激情女声</option>
                                    <option value="diana">🎊 欢快女声</option>
                                </select>
                            </div>
                            <div class="voice-slider-group">
                                <label>语速 <span id="rateVal">1.0</span>x</label>
                                <input type="range" id="voiceRate" min="0.5" max="2" step="0.1" value="1.0">
                            </div>
                            <div id="ttsStatus" class="tts-status" style="display:none;"></div>
                        </div>
                    </div>
                </div>

                <div class="dh-main-panel">
                    <div class="dh-script-display">
                        <div class="script-header">
                            <h3><i class="fas fa-scroll"></i> 主持词</h3>
                            <div class="script-actions">
                                <button class="btn-icon btn-voice" id="btnVoice" title="朗读"><i class="fas fa-volume-up"></i></button>
                                <button class="btn-icon btn-voice" id="btnStopVoice" title="停止" style="display:none;"><i class="fas fa-stop"></i></button>
                                <button class="btn-icon" id="btnCopyScript" title="复制"><i class="fas fa-copy"></i></button>
                                <button class="btn-icon" id="btnRefreshScript" title="重新生成"><i class="fas fa-sync-alt"></i></button>
                            </div>
                        </div>
                        <div class="script-content" id="scriptContent">
                            <div class="script-placeholder">
                                <p>👈 请选择一个婚礼环节开始</p>
                                <p>两位AI主持人将联袂为您主持婚礼</p>
                            </div>
                        </div>
                    </div>

                    <div class="dh-interaction-area">
                        <div class="interaction-tabs">
                            <button class="tab-btn active" data-tab="chat">💬 对话</button>
                            <button class="tab-btn" data-tab="emotion">🎭 氛围</button>
                            <button class="tab-btn" data-tab="improvise">⚡ 即兴</button>
                        </div>

                        <div class="tab-content active" id="tabChat">
                            <div class="chat-messages" id="chatMessages"></div>
                            <div class="chat-input-area">
                                <input type="text" id="chatInput" placeholder="与主持人对话...">
                                <button id="chatSendBtn"><i class="fas fa-paper-plane"></i></button>
                            </div>
                        </div>

                        <div class="tab-content" id="tabEmotion">
                            <div class="emotion-grid">
                                <button class="emotion-btn" data-atmosphere="warm">
                                    <span class="emotion-icon">😊</span>
                                    <span>温暖</span>
                                </button>
                                <button class="emotion-btn" data-atmosphere="excited">
                                    <span class="emotion-icon">🔥</span>
                                    <span>热烈</span>
                                </button>
                                <button class="emotion-btn" data-atmosphere="romantic">
                                    <span class="emotion-icon">💕</span>
                                    <span>浪漫</span>
                                </button>
                                <button class="emotion-btn" data-atmosphere="solemn">
                                    <span class="emotion-icon">🙏</span>
                                    <span>庄重</span>
                                </button>
                                <button class="emotion-btn" data-atmosphere="joyful">
                                    <span class="emotion-icon">😄</span>
                                    <span>欢快</span>
                                </button>
                                <button class="emotion-btn" data-atmosphere="quiet">
                                    <span class="emotion-icon">🤫</span>
                                    <span>安静</span>
                                </button>
                            </div>
                        </div>

                        <div class="tab-content" id="tabImprovise">
                            <div class="improvise-triggers">
                                <button class="trigger-btn" data-trigger="applause">
                                    <span>👏</span> 掌声响起
                                </button>
                                <button class="trigger-btn" data-trigger="guest_shout">
                                    <span>🗣</span> 来宾互动
                                </button>
                                <button class="trigger-btn" data-trigger="silence">
                                    <span>🤫</span> 现场安静
                                </button>
                                <button class="trigger-btn" data-trigger="delay">
                                    <span>⏰</span> 环节延迟
                                </button>
                                <button class="trigger-btn" data-trigger="weather">
                                    <span>🌧</span> 天气变化
                                </button>
                            </div>
                            <div class="improvise-custom">
                                <textarea id="improviseInput" placeholder="描述现场情况，主持人将即兴发挥..."></textarea>
                                <button id="improviseBtn"><i class="fas fa-magic"></i> 即兴发挥</button>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </section>
</main>

<style>
.dh-banner { 
    background: linear-gradient(135deg, #1a1a2e 0%, #16213e 50%, #0f3460 100%); 
    color: #fff; 
}
.dh-section { padding: 30px 0 60px; }
.dh-layout-double { display: grid; grid-template-columns: 380px 1fr; gap: 24px; }

.dh-avatar-panel-double { display: flex; flex-direction: column; gap: 20px; }

.avatars-container {
    display: flex;
    align-items: flex-end;
    justify-content: center;
    gap: 20px;
    background: #fff;
    border-radius: 20px;
    padding: 25px;
    box-shadow: 0 4px 20px rgba(0,0,0,0.08);
    position: relative;
}

.couple-decoration {
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    z-index: 10;
}

.decor-heart {
    font-size: 32px;
    animation: heartBeat 2s ease-in-out infinite;
}

@keyframes heartBeat {
    0%, 100% { transform: scale(1); opacity: 0.8; }
    50% { transform: scale(1.1); opacity: 1; }
}

.avatar-wrapper {
    flex: 1;
    display: flex;
    flex-direction: column;
    align-items: center;
}

.dh-avatar-card {
    text-align: center;
    padding: 15px;
    border-radius: 15px;
    transition: all 0.3s;
}

.groom-card { 
    background: linear-gradient(135deg, #f8f9fa, #e9ecef);
    border: 2px solid #dee2e6;
}

.bride-card { 
    background: linear-gradient(135deg, #fff5f5, #ffe4e6);
    border: 2px solid #fecaca;
}

.dh-avatar-card.speaking {
    transform: scale(1.02);
    box-shadow: 0 8px 25px rgba(0,0,0,0.12);
}

.dh-avatar {
    width: 120px;
    height: 160px;
    margin: 0 auto;
    position: relative;
}

.avatar-body {
    position: relative;
    width: 100%;
    height: 100%;
}

/* 新郎样式 */
.groom-head {
    width: 70px;
    height: 70px;
    background: #ffdbac;
    border-radius: 50%;
    margin: 0 auto;
    position: relative;
    box-shadow: 0 2px 10px rgba(0,0,0,0.1);
}

.groom-eyes {
    display: flex;
    justify-content: center;
    gap: 18px;
    padding-top: 24px;
}

.groom-eyes .eye {
    width: 7px;
    height: 7px;
    background: #333;
    border-radius: 50%;
    display: block;
    position: relative;
}

.groom-eyes .eye::after {
    content: '';
    position: absolute;
    width: 2px;
    height: 2px;
    background: #fff;
    border-radius: 50%;
    top: 1px;
    right: 1px;
}

.groom-face .avatar-mouth {
    width: 18px;
    height: 8px;
    border-bottom: 3px solid #c0392b;
    border-radius: 0 0 50% 50%;
    margin: 10px auto 0;
    transition: all 0.1s;
}

.groom-torso {
    width: 85px;
    height: 70px;
    background: linear-gradient(180deg, #2c3e50 0%, #1a252f 100%);
    border-radius: 8px 8px 0 0;
    margin: 5px auto 0;
    position: relative;
}

.groom-tie {
    width: 12px;
    height: 35px;
    background: linear-gradient(180deg, #c0392b 0%, #a93226 100%);
    margin: 0 auto;
    clip-path: polygon(50% 0%, 100% 30%, 50% 100%, 0% 30%);
    position: relative;
    top: 5px;
}

/* 新娘样式 */
.bride-head {
    width: 70px;
    height: 70px;
    background: #ffe4e1;
    border-radius: 50%;
    margin: 0 auto;
    position: relative;
    box-shadow: 0 2px 10px rgba(0,0,0,0.1);
}

.avatar-veil {
    position: absolute;
    top: -20px;
    left: -15px;
    width: 100px;
    height: 60px;
    background: linear-gradient(180deg, rgba(255,255,255,0.95) 0%, rgba(255,255,255,0.6) 100%);
    border-radius: 50% 50% 0 0;
    z-index: -1;
}

.bride-eyes {
    display: flex;
    justify-content: center;
    gap: 18px;
    padding-top: 24px;
}

.bride-eyes .eye {
    width: 7px;
    height: 7px;
    background: #333;
    border-radius: 50%;
    display: block;
    position: relative;
}

.bride-eyes .eye::after {
    content: '';
    position: absolute;
    width: 2px;
    height: 2px;
    background: #fff;
    border-radius: 50%;
    top: 1px;
    right: 1px;
}

.bride-face .avatar-mouth {
    width: 16px;
    height: 7px;
    border-bottom: 3px solid #e91e63;
    border-radius: 0 0 50% 50%;
    margin: 10px auto 0;
    transition: all 0.1s;
}

.bride-head::before {
    content: '';
    position: absolute;
    top: 5px;
    left: 50%;
    transform: translateX(-50%);
    width: 50px;
    height: 20px;
    background: linear-gradient(180deg, #4a4a4a 0%, #3a3a3a 100%);
    border-radius: 50% 50% 0 0;
}

.bride-torso {
    width: 85px;
    height: 75px;
    background: linear-gradient(180deg, #fff 0%, #fef5f5 100%);
    border-radius: 50% 50% 0 0;
    margin: 5px auto 0;
    position: relative;
    border: 2px solid #ffe4e6;
}

.avatar-dress {
    width: 100%;
    height: 100%;
    position: absolute;
    top: 0;
    left: 0;
}

.avatar-dress::before {
    content: '';
    position: absolute;
    top: 10px;
    left: 50%;
    transform: translateX(-50%);
    width: 60px;
    height: 40px;
    border: 2px solid #ffc0cb;
    border-radius: 50% 50% 0 0;
}

.avatar-dress::after {
    content: '';
    position: absolute;
    top: 5px;
    left: 50%;
    transform: translateX(-50%);
    width: 20px;
    height: 15px;
    background: #ffc0cb;
    border-radius: 50%;
}

/* 说话动画 */
.dh-avatar.speaking .avatar-mouth {
    animation: speak 0.3s infinite alternate;
}

@keyframes speak {
    0% { height: 4px; }
    100% { height: 12px; }
}

.dh-emotion-indicator {
    display: inline-flex;
    align-items: center;
    gap: 6px;
    margin-top: 8px;
    padding: 4px 12px;
    background: #f0f0f0;
    border-radius: 20px;
    font-size: 12px;
}

.emotion-dot {
    width: 8px;
    height: 8px;
    border-radius: 50%;
    background: #27ae60;
}

.dh-avatar-name {
    font-size: 16px;
    font-weight: 700;
    margin-top: 10px;
    color: #2c3e50;
}

.dh-avatar-role {
    font-size: 12px;
    color: #999;
    margin-top: 2px;
}

.dh-phase-control {
    background: #fff;
    border-radius: 20px;
    padding: 20px;
    box-shadow: 0 4px 20px rgba(0,0,0,0.08);
}

.dh-phase-control h3 {
    font-size: 15px;
    margin-bottom: 12px;
    color: #333;
}

.voice-settings {
    margin-bottom: 16px;
    padding-bottom: 16px;
    border-bottom: 1px solid #f0f0f0;
}

.voice-settings h3 {
    font-size: 14px;
    margin-bottom: 10px;
}

.voice-toggle {
    display: flex;
    align-items: center;
    gap: 8px;
    font-size: 13px;
    cursor: pointer;
    margin-bottom: 10px;
}

.voice-toggle input {
    width: 16px;
    height: 16px;
    accent-color: #b64a2a;
}

.voice-slider-group {
    margin-bottom: 10px;
}

.voice-slider-group label {
    font-size: 12px;
    color: #666;
    display: flex;
    justify-content: space-between;
    margin-bottom: 4px;
}

.voice-slider-group input[type="range"] {
    width: 100%;
    height: 4px;
    accent-color: #b64a2a;
}

.voice-select {
    width: 100%;
    padding: 6px 8px;
    border: 1px solid #ddd;
    border-radius: 8px;
    font-size: 12px;
    margin-top: 4px;
    outline: none;
}

.voice-select:focus {
    border-color: #b64a2a;
}

.tts-status {
    margin-top: 8px;
    padding: 6px 10px;
    border-radius: 8px;
    font-size: 12px;
    text-align: center;
}

.tts-status.loading {
    background: #fff3cd;
    color: #856404;
}

.tts-status.error {
    background: #f8d7da;
    color: #721c24;
}

.tts-status.success {
    background: #d4edda;
    color: #155724;
}

.btn-voice {
    color: #b64a2a !important;
}

.btn-voice.speaking {
    background: #b64a2a !important;
    color: #fff !important;
    animation: voicePulse 1s infinite;
}

@keyframes voicePulse {
    0%, 100% { box-shadow: 0 0 0 0 rgba(182,74,42,0.4); }
    50% { box-shadow: 0 0 0 6px rgba(182,74,42,0); }
}

.script-text {
    position: relative;
}

.script-text .speaking-highlight {
    background: #fff3cd;
    border-radius: 3px;
    padding: 0 2px;
}

.phase-list {
    display: grid;
    grid-template-columns: 1fr 1fr;
    gap: 6px;
}

.phase-btn {
    display: flex;
    align-items: center;
    gap: 8px;
    padding: 10px 12px;
    border: 1px solid #eee;
    border-radius: 12px;
    background: #fff;
    cursor: pointer;
    transition: all 0.2s;
    font-size: 13px;
    text-align: left;
}

.phase-btn:hover {
    background: #f8f0ed;
    border-color: #b64a2a;
}

.phase-btn.active {
    background: #b64a2a;
    color: #fff;
    border-color: #b64a2a;
}

.phase-icon {
    font-size: 16px;
}

.dh-main-panel {
    display: flex;
    flex-direction: column;
    gap: 20px;
}

.dh-script-display {
    background: #fff;
    border-radius: 20px;
    box-shadow: 0 4px 20px rgba(0,0,0,0.08);
    overflow: hidden;
}

.script-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 16px 20px;
    border-bottom: 1px solid #f0f0f0;
}

.script-header h3 {
    font-size: 15px;
    color: #333;
    margin: 0;
}

.script-actions {
    display: flex;
    gap: 8px;
}

.btn-icon {
    width: 32px;
    height: 32px;
    border: none;
    background: #f5f5f5;
    border-radius: 8px;
    cursor: pointer;
    color: #666;
    transition: all 0.2s;
}

.btn-icon:hover {
    background: #b64a2a;
    color: #fff;
}

.script-content {
    padding: 24px;
    min-height: 250px;
    line-height: 1.8;
    font-size: 15px;
    color: #444;
}

.script-placeholder {
    text-align: center;
    color: #bbb;
    padding: 40px 0;
}

.script-placeholder p {
    margin: 8px 0;
}

.dh-interaction-area {
    background: #fff;
    border-radius: 20px;
    box-shadow: 0 4px 20px rgba(0,0,0,0.08);
    overflow: hidden;
}

.interaction-tabs {
    display: flex;
    border-bottom: 1px solid #f0f0f0;
}

.tab-btn {
    flex: 1;
    padding: 12px;
    border: none;
    background: none;
    cursor: pointer;
    font-size: 14px;
    color: #999;
    transition: all 0.2s;
}

.tab-btn.active {
    color: #b64a2a;
    border-bottom: 2px solid #b64a2a;
}

.tab-content {
    display: none;
    padding: 16px;
}

.tab-content.active {
    display: block;
}

.chat-messages {
    max-height: 200px;
    overflow-y: auto;
    margin-bottom: 12px;
}

.chat-messages .msg {
    padding: 8px 12px;
    margin-bottom: 8px;
    border-radius: 12px;
    font-size: 14px;
    line-height: 1.6;
    max-width: 80%;
}

.chat-messages .msg.user {
    background: #b64a2a;
    color: #fff;
    margin-left: auto;
    border-bottom-right-radius: 4px;
}

.chat-messages .msg.agent.groom {
    background: #e9ecef;
    color: #2c3e50;
    border-bottom-left-radius: 4px;
    border-left: 3px solid #495057;
}

.chat-messages .msg.agent.bride {
    background: #ffe4e6;
    color: #c2185b;
    border-bottom-left-radius: 4px;
    border-left: 3px solid #e91e63;
}

.chat-input-area {
    display: flex;
    gap: 8px;
}

.chat-input-area input {
    flex: 1;
    padding: 10px 16px;
    border: 1px solid #ddd;
    border-radius: 24px;
    font-size: 14px;
    outline: none;
}

.chat-input-area input:focus {
    border-color: #b64a2a;
}

.chat-input-area button {
    width: 40px;
    height: 40px;
    border: none;
    background: #b64a2a;
    color: #fff;
    border-radius: 50%;
    cursor: pointer;
}

.emotion-grid {
    display: grid;
    grid-template-columns: repeat(3, 1fr);
    gap: 10px;
}

.emotion-btn {
    display: flex;
    flex-direction: column;
    align-items: center;
    gap: 4px;
    padding: 14px 8px;
    border: 1px solid #eee;
    border-radius: 12px;
    background: #fff;
    cursor: pointer;
    transition: all 0.2s;
}

.emotion-btn:hover {
    background: #f8f0ed;
    border-color: #b64a2a;
}

.emotion-btn.active {
    background: #b64a2a;
    color: #fff;
    border-color: #b64a2a;
}

.emotion-icon {
    font-size: 24px;
}

.improvise-triggers {
    display: flex;
    flex-wrap: wrap;
    gap: 8px;
    margin-bottom: 12px;
}

.trigger-btn {
    padding: 8px 14px;
    border: 1px solid #eee;
    border-radius: 20px;
    background: #fff;
    cursor: pointer;
    font-size: 13px;
    transition: all 0.2s;
}

.trigger-btn:hover {
    background: #f8f0ed;
    border-color: #b64a2a;
}

.improvise-custom {
    display: flex;
    flex-direction: column;
    gap: 8px;
}

.improvise-custom textarea {
    width: 100%;
    padding: 10px;
    border: 1px solid #ddd;
    border-radius: 12px;
    font-size: 14px;
    resize: none;
    height: 60px;
    outline: none;
}

.improvise-custom textarea:focus {
    border-color: #b64a2a;
}

.improvise-custom button {
    padding: 10px;
    border: none;
    background: #b64a2a;
    color: #fff;
    border-radius: 12px;
    cursor: pointer;
    font-size: 14px;
}

@media (max-width: 992px) {
    .dh-layout-double {
        grid-template-columns: 1fr;
    }
    .avatars-container {
        flex-wrap: wrap;
    }
    .phase-list {
        grid-template-columns: 1fr;
    }
}

@media (max-width: 768px) {
    .emotion-grid {
        grid-template-columns: repeat(2, 1fr);
    }
}
</style>

<script>
(function() {
    var currentPhase = null;
    var currentEmotion = 'warm';
    var isLoading = false;
    var currentSpeaker = 'groom';

    var emotionLabels = {
        warm: '温暖', excited: '热烈', romantic: '浪漫',
        solemn: '庄重', joyful: '欢快', quiet: '安静'
    };

    var currentAudio = null;
    var isSpeaking = false;
    var browserSynth = window.speechSynthesis;
    var browserVoices = [];

    var emotionSpeedMap = {
        warm: 0.95, excited: 1.15, romantic: 0.85,
        solemn: 0.9, joyful: 1.1, quiet: 0.8
    };

    function loadBrowserVoices() {
        browserVoices = browserSynth ? browserSynth.getVoices() : [];
    }
    if (browserSynth && browserSynth.onvoiceschanged !== undefined) {
        browserSynth.onvoiceschanged = loadBrowserVoices;
    }
    setTimeout(loadBrowserVoices, 500);

    function showTtsStatus(type, msg) {
        var el = document.getElementById('ttsStatus');
        el.className = 'tts-status ' + type;
        el.textContent = msg;
        el.style.display = '';
        if (type === 'success') setTimeout(function() { el.style.display = 'none'; }, 2000);
    }

    function speak(text, speaker) {
        if (!text) return;
        stopSpeaking();
        
        currentSpeaker = speaker || 'groom';
        var voiceSelect = speaker === 'bride' ? 'ttsVoiceFemale' : 'ttsVoiceMale';
        var voice = document.getElementById(voiceSelect).value;
        
        if (voice === 'browser') {
            speakBrowser(text, speaker);
        } else {
            speakSiliconflow(text, voice, speaker);
        }
    }

    function speakSiliconflow(text, voice, speaker) {
        var speed = parseFloat(document.getElementById('voiceRate').value) || 1.0;
        var finalSpeed = speed * (emotionSpeedMap[currentEmotion] || 1.0);

        showTtsStatus('loading', '🎙️ 正在合成语音...');
        setAvatarSpeaking(speaker, true);
        document.getElementById('btnVoice').classList.add('speaking');
        document.getElementById('btnStopVoice').style.display = '';
        document.getElementById('btnVoice').style.display = 'none';

        var xhr = new XMLHttpRequest();
        xhr.open('POST', 'api/tts_proxy.php', true);
        xhr.setRequestHeader('Content-Type', 'application/json');
        xhr.timeout = 60000;

        xhr.onload = function() {
            var resp;
            try {
                resp = JSON.parse(xhr.responseText);
            } catch(e) {
                showTtsStatus('error', '❌ 响应解析失败，切换浏览器语音');
                speakBrowser(text, speaker);
                return;
            }
            if (xhr.status === 200 && resp && resp.success) {
                showTtsStatus('success', '✅ 语音就绪');
                playAudio(resp.audio_url, speaker);
            } else {
                var errMsg = (resp && resp.message) || '语音合成失败';
                showTtsStatus('error', '❌ ' + errMsg + '，切换浏览器语音');
                speakBrowser(text, speaker);
            }
        };
        xhr.onerror = function() {
            showTtsStatus('error', '❌ 网络错误，切换浏览器语音');
            speakBrowser(text, speaker);
        };
        xhr.ontimeout = function() {
            showTtsStatus('error', '❌ 请求超时，切换浏览器语音');
            speakBrowser(text, speaker);
        };

        xhr.send(JSON.stringify({
            text: text,
            voice: voice,
            speed: finalSpeed,
            emotion: currentEmotion
        }));
    }

    function playAudio(url, speaker) {
        if (currentAudio) {
            currentAudio.pause();
            currentAudio = null;
        }

        currentAudio = new Audio(url);
        currentAudio.volume = 1.0;

        currentAudio.onplay = function() {
            isSpeaking = true;
            setAvatarSpeaking(speaker, true);
            document.getElementById('btnVoice').classList.add('speaking');
            document.getElementById('btnStopVoice').style.display = '';
            document.getElementById('btnVoice').style.display = 'none';
        };

        currentAudio.onended = function() {
            isSpeaking = false;
            setAvatarSpeaking(speaker, false);
            document.getElementById('btnVoice').classList.remove('speaking');
            document.getElementById('btnStopVoice').style.display = 'none';
            document.getElementById('btnVoice').style.display = '';
        };

        currentAudio.onerror = function() {
            isSpeaking = false;
            setAvatarSpeaking(speaker, false);
            document.getElementById('btnVoice').classList.remove('speaking');
            document.getElementById('btnStopVoice').style.display = 'none';
            document.getElementById('btnVoice').style.display = '';
            showTtsStatus('error', '❌ 音频播放失败');
        };

        currentAudio.play().catch(function() {
            isSpeaking = false;
            setAvatarSpeaking(speaker, false);
        });
    }

    function speakBrowser(text, speaker) {
        if (!browserSynth) return;

        var cleanText = text.replace(/<br\s*\/?>/gi, '\n').replace(/<[^>]+>/g, '').replace(/&nbsp;/g, ' ').replace(/&amp;/g, '&').replace(/&lt;/g, '<').replace(/&gt;/g, '>').trim();
        if (!cleanText) return;

        var utterance = new SpeechSynthesisUtterance(cleanText);
        var isMale = speaker === 'groom';
        var voice = browserVoices.find(function(v) { 
            var langMatch = v.lang.indexOf('zh') > -1;
            var genderMatch = isMale ? v.name.toLowerCase().indexOf('male') > -1 : v.name.toLowerCase().indexOf('female') > -1;
            return langMatch && genderMatch;
        }) || browserVoices.find(function(v) { return v.lang.indexOf('zh') > -1; });
        
        if (voice) utterance.voice = voice;

        utterance.rate = parseFloat(document.getElementById('voiceRate').value) || 1.0;
        utterance.pitch = isMale ? 0.8 : 1.1;
        utterance.volume = 1.0;
        utterance.lang = 'zh-CN';

        utterance.onstart = function() {
            isSpeaking = true;
            setAvatarSpeaking(speaker, true);
            document.getElementById('btnVoice').classList.add('speaking');
            document.getElementById('btnStopVoice').style.display = '';
            document.getElementById('btnVoice').style.display = 'none';
        };
        utterance.onend = function() {
            isSpeaking = false;
            setAvatarSpeaking(speaker, false);
            document.getElementById('btnVoice').classList.remove('speaking');
            document.getElementById('btnStopVoice').style.display = 'none';
            document.getElementById('btnVoice').style.display = '';
        };
        utterance.onerror = function() {
            isSpeaking = false;
            setAvatarSpeaking(speaker, false);
            document.getElementById('btnVoice').classList.remove('speaking');
            document.getElementById('btnStopVoice').style.display = 'none';
            document.getElementById('btnVoice').style.display = '';
        };

        browserSynth.speak(utterance);
    }

    function stopSpeaking() {
        if (currentAudio) {
            currentAudio.pause();
            currentAudio.currentTime = 0;
            currentAudio = null;
        }
        if (browserSynth) browserSynth.cancel();
        isSpeaking = false;
        setAvatarSpeaking('groom', false);
        setAvatarSpeaking('bride', false);
        document.getElementById('btnVoice').classList.remove('speaking');
        document.getElementById('btnStopVoice').style.display = 'none';
        document.getElementById('btnVoice').style.display = '';
    }

    document.getElementById('btnVoice').addEventListener('click', function() {
        var text = document.getElementById('scriptContent').innerText;
        if (text) speak(text, currentSpeaker);
    });
    document.getElementById('btnStopVoice').addEventListener('click', stopSpeaking);

    document.getElementById('voiceRate').addEventListener('input', function() {
        document.getElementById('rateVal').textContent = parseFloat(this.value).toFixed(1);
    });

    function apiCall(method, path, params, callback) {
        var xhr = new XMLHttpRequest();
        var url = 'api/api_router.php/' + path;
        if (method === 'GET' && params) {
            var qs = Object.keys(params).map(function(k) { return k + '=' + encodeURIComponent(params[k]); }).join('&');
            url += '?' + qs;
        }
        xhr.open(method, url, true);
        xhr.timeout = 30000;
        xhr.onload = function() {
            if (xhr.status === 200) {
                try {
                    var resp = JSON.parse(xhr.responseText);
                    callback(null, resp);
                } catch(e) {
                    callback(e);
                }
            } else {
                callback(new Error('HTTP ' + xhr.status));
            }
        };
        xhr.onerror = function() { callback(new Error('网络错误')); };
        xhr.ontimeout = function() { callback(new Error('请求超时')); };

        if (method === 'POST' && params) {
            xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
            var body = Object.keys(params).map(function(k) { return k + '=' + encodeURIComponent(params[k]); }).join('&');
            xhr.send(body);
        } else {
            xhr.send();
        }
    }

    function setLoading(loading) {
        isLoading = loading;
        var content = document.getElementById('scriptContent');
        if (loading) {
            content.innerHTML = '<div class="script-placeholder"><p>⏳ AI主持人正在准备...</p></div>';
        }
    }

    function setAvatarSpeaking(speaker, speaking) {
        var avatar = document.getElementById(speaker + 'Avatar');
        var card = avatar.parentElement;
        
        if (speaking) {
            avatar.classList.add('speaking');
            card.classList.add('speaking');
            if (speaker === 'groom') {
                document.getElementById('brideAvatar').classList.remove('speaking');
                document.getElementById('brideAvatar').parentElement.classList.remove('speaking');
            } else {
                document.getElementById('groomAvatar').classList.remove('speaking');
                document.getElementById('groomAvatar').parentElement.classList.remove('speaking');
            }
        } else {
            avatar.classList.remove('speaking');
            card.classList.remove('speaking');
        }
    }

    function updateEmotionIndicator(emotion, speaker) {
        currentEmotion = emotion;
        var indicator = document.getElementById((speaker || 'groom') + 'Emotion');
        var colors = { warm: '#27ae60', excited: '#e74c3c', romantic: '#e91e63', solemn: '#2c3e50', joyful: '#f39c12', quiet: '#95a5a6' };
        indicator.querySelector('.emotion-dot').style.background = colors[emotion] || '#27ae60';
        indicator.querySelector('.emotion-text').textContent = emotionLabels[emotion] || emotion;

        document.querySelectorAll('.emotion-btn').forEach(function(btn) {
            btn.classList.toggle('active', btn.dataset.atmosphere === emotion);
        });
    }

    document.querySelectorAll('.phase-btn').forEach(function(btn) {
        btn.addEventListener('click', function() {
            if (isLoading) return;
            stopSpeaking();
            var phase = this.dataset.phase;
            var emotion = this.dataset.emotion;
            currentPhase = phase;

            document.querySelectorAll('.phase-btn').forEach(function(b) { b.classList.remove('active'); });
            this.classList.add('active');

            setLoading(true);
            setAvatarSpeaking('groom', true);
            updateEmotionIndicator(emotion, 'groom');

            apiCall('POST', 'digital-human/host/phase', {
                phase: phase,
                context: JSON.stringify({ groom_name: '新郎', bride_name: '新娘', double_host: true })
            }, function(err, resp) {
                setLoading(false);
                setAvatarSpeaking('groom', false);
                if (err || !resp.success || !resp.data) {
                    document.getElementById('scriptContent').innerHTML = '<div class="script-placeholder"><p>❌ 生成失败，请重试</p></div>';
                    return;
                }
                var data = resp.data;
                var scripts = data.scripts || [{ speaker: 'groom', text: data.script || '' }];
                
                displayScripts(scripts);
                
                if (data.emotion) updateEmotionIndicator(data.emotion, 'groom');
                if (document.getElementById('autoSpeak').checked && scripts.length > 0) {
                    speakTurnByTurn(scripts, 0);
                }
            });
        });
    });

    function displayScripts(scripts) {
        var html = '';
        scripts.forEach(function(item) {
            var speakerClass = item.speaker === 'bride' ? 'bride-script' : 'groom-script';
            var speakerName = item.speaker === 'bride' ? '喜庆：' : '喜乐：';
            html += '<div class="script-turn ' + speakerClass + '"><strong>' + speakerName + '</strong>' + item.text.replace(/\n/g, '<br>') + '</div>';
        });
        document.getElementById('scriptContent').innerHTML = '<div class="script-text">' + html + '</div>';
    }

    function speakTurnByTurn(scripts, index) {
        if (index >= scripts.length) {
            setAvatarSpeaking('groom', false);
            setAvatarSpeaking('bride', false);
            return;
        }
        
        var item = scripts[index];
        var speaker = item.speaker;
        
        updateEmotionIndicator(currentEmotion, speaker);
        
        speak(item.text, speaker);
        
        var textLength = item.text.length;
        var estimatedTime = textLength * 0.08 + 1;
        
        setTimeout(function() {
            speakTurnByTurn(scripts, index + 1);
        }, estimatedTime * 1000);
    }

    document.getElementById('chatSendBtn').addEventListener('click', sendChat);
    document.getElementById('chatInput').addEventListener('keydown', function(e) {
        if (e.key === 'Enter') sendChat();
    });

    function sendChat() {
        var input = document.getElementById('chatInput');
        var msg = input.value.trim();
        if (!msg || isLoading) return;
        input.value = '';

        addChatMessage('user', msg);
        setAvatarSpeaking('groom', true);

        apiCall('POST', 'digital-human/host/chat', { message: msg, double_host: true }, function(err, resp) {
            setAvatarSpeaking('groom', false);
            if (err || !resp.success || !resp.data) {
                addChatMessage('agent', '抱歉，我暂时无法回应。', 'groom');
                return;
            }
            
            var replies = resp.data.replies || [{ speaker: 'groom', text: resp.data.reply || '' }];
            displayChatReplies(replies);
        });
    }

    function displayChatReplies(replies) {
        var index = 0;
        
        function displayNext() {
            if (index >= replies.length) return;
            
            var item = replies[index];
            addChatMessage('agent', item.text, item.speaker);
            
            if (document.getElementById('autoSpeak').checked) {
                speak(item.text, item.speaker);
            }
            
            index++;
            setTimeout(displayNext, item.text.length * 0.05 * 1000 + 500);
        }
        
        displayNext();
    }

    function addChatMessage(role, text, speaker) {
        var container = document.getElementById('chatMessages');
        var div = document.createElement('div');
        if (role === 'agent') {
            div.className = 'msg ' + role + ' ' + (speaker || 'groom');
        } else {
            div.className = 'msg ' + role;
        }
        div.textContent = text;
        container.appendChild(div);
        container.scrollTop = container.scrollHeight;
    }

    document.querySelectorAll('.emotion-btn').forEach(function(btn) {
        btn.addEventListener('click', function() {
            var atmosphere = this.dataset.atmosphere;
            updateEmotionIndicator(atmosphere, 'groom');
            updateEmotionIndicator(atmosphere, 'bride');
            apiCall('POST', 'digital-human/host/emotion', { atmosphere: atmosphere, confidence: 0.9 }, function() {});
        });
    });

    document.querySelectorAll('.trigger-btn').forEach(function(btn) {
        btn.addEventListener('click', function() {
            if (isLoading) return;
            var trigger = this.dataset.trigger;
            setLoading(true);
            setAvatarSpeaking('groom', true);
            apiCall('POST', 'digital-human/host/improvise', { trigger: trigger, double_host: true }, function(err, resp) {
                setLoading(false);
                setAvatarSpeaking('groom', false);
                if (err || !resp.success || !resp.data) return;
                
                var scripts = resp.data.scripts || [{ speaker: 'groom', text: resp.data.script || '' }];
                displayScripts(scripts);
                
                if (resp.data.emotion) updateEmotionIndicator(resp.data.emotion, 'groom');
                if (document.getElementById('autoSpeak').checked && scripts.length > 0) {
                    speakTurnByTurn(scripts, 0);
                }
            });
        });
    });

    document.getElementById('improviseBtn').addEventListener('click', function() {
        if (isLoading) return;
        var msg = document.getElementById('improviseInput').value.trim();
        if (!msg) return;
        document.getElementById('improviseInput').value = '';
        setLoading(true);
        setAvatarSpeaking('groom', true);
        apiCall('POST', 'digital-human/host/improvise', { trigger: 'custom', message: msg, double_host: true }, function(err, resp) {
            setLoading(false);
            setAvatarSpeaking('groom', false);
            if (err || !resp.success || !resp.data) return;
            
            var scripts = resp.data.scripts || [{ speaker: 'groom', text: resp.data.script || '' }];
            displayScripts(scripts);
            
            if (document.getElementById('autoSpeak').checked && scripts.length > 0) {
                speakTurnByTurn(scripts, 0);
            }
        });
    });

    document.querySelectorAll('.tab-btn').forEach(function(btn) {
        btn.addEventListener('click', function() {
            document.querySelectorAll('.tab-btn').forEach(function(b) { b.classList.remove('active'); });
            document.querySelectorAll('.tab-content').forEach(function(c) { c.classList.remove('active'); });
            this.classList.add('active');
            document.getElementById('tab' + this.dataset.tab.charAt(0).toUpperCase() + this.dataset.tab.slice(1)).classList.add('active');
        });
    });

    document.getElementById('btnCopyScript').addEventListener('click', function() {
        var text = document.getElementById('scriptContent').innerText;
        navigator.clipboard.writeText(text).then(function() {
            this.innerHTML = '<i class="fas fa-check"></i>';
            setTimeout(function() { document.getElementById('btnCopyScript').innerHTML = '<i class="fas fa-copy"></i>'; }, 1500);
        }.bind(this));
    });

    document.getElementById('btnRefreshScript').addEventListener('click', function() {
        if (currentPhase && !isLoading) {
            var activeBtn = document.querySelector('.phase-btn.active');
            if (activeBtn) activeBtn.click();
        }
    });
})();
</script>

<?php require_once 'footer.php'; ?>