<footer class="mt-5 py-5 border-top border-secondary bg-darker">
    <div class="container">
        <div class="row g-4 mb-5">
            <div class="col-lg-4 col-md-12">
                <div class="logo-container mb-3">
                    <img src="<?= $site_logo ?>?v=<?= $logo_v ?? time() ?>" height="40" alt="<?= $site_name ?>">
                </div>
                <p class="text-muted small mb-4">
                    <?= __('footer_desc') ?>
                </p>
                <div class="social-links d-flex gap-3 fs-5 text-muted">
                    <a href="#" class="text-reset"><i class="bi bi-twitter-x"></i></a>
                    <a href="#" class="text-reset"><i class="bi bi-telegram"></i></a>
                    <a href="#" class="text-reset"><i class="bi bi-discord"></i></a>
                    <a href="#" class="text-reset"><i class="bi bi-facebook"></i></a>
                    <a href="#" class="text-reset"><i class="bi bi-instagram"></i></a>
                </div>
            </div>
            <div class="col-lg-2 col-md-4">
                <h6 class="fw-bold mb-3"><?php echo __('footer_about'); ?></h6>
                <ul class="list-unstyled small lh-lg">
                    <li><a href="/about.php" class="text-muted text-decoration-none"><?php echo __('about_us'); ?></a></li>
                    <li><a href="/news.php" class="text-muted text-decoration-none"><?php echo __('news'); ?></a></li>
                    <li><a href="/tos.php" class="text-muted text-decoration-none"><?php echo __('terms'); ?></a></li>
                    <li><a href="/help.php" class="text-muted text-decoration-none"><?php echo __('help'); ?></a></li>
                    <li><a href="/legal.php" class="text-muted text-decoration-none"><?php echo __('privacy'); ?></a></li>
                </ul>
            </div>
            <div class="col-lg-2 col-md-4">
                <h6 class="fw-bold mb-3"><?php echo __('footer_product'); ?></h6>
                <ul class="list-unstyled small lh-lg">
                    <li><a href="/binary.php" class="text-muted text-decoration-none"><?php echo __('second_contract'); ?></a></li>
                    <li><a href="/trade.php" class="text-muted text-decoration-none"><?php echo __('spot'); ?></a></li>
                    <li><a href="/contract.php" class="text-muted text-decoration-none"><?php echo __('contract'); ?></a></li>
                    <li><a href="/swap.php" class="text-muted text-decoration-none"><?php echo __('swap'); ?></a></li>
                    <li><a href="/mining.php" class="text-muted text-decoration-none"><?php echo __('mining'); ?></a></li>
                </ul>
            </div>
            <div class="col-lg-2 col-md-4">
                <h6 class="fw-bold mb-3"><?php echo __('footer_support'); ?></h6>
                <ul class="list-unstyled small lh-lg">
                    <li><a href="/support.php" class="text-muted text-decoration-none"><?php echo __('submit_request'); ?></a></li>
                    <li><a href="/api.php" class="text-muted text-decoration-none"><?php echo __('api_doc'); ?></a></li>
                    <li><a href="/fees.php" class="text-muted text-decoration-none"><?php echo __('fee_structure'); ?></a></li>
                    <li><a href="/app.php" class="text-muted text-decoration-none"><?php echo __('app_download'); ?></a></li>
                </ul>
            </div>
        </div>
        <div class="border-top border-secondary pt-4 d-flex flex-column flex-md-row justify-content-between align-items-center gap-3">
            <div class="small text-muted">
                <?php echo __('copyright'); ?>
            </div>
            <div class="d-flex gap-4 small text-muted">
                <span class="d-flex align-items-center gap-2 text-success">
                    <span class="status-indicator"></span>
                    <?php echo __('status_normal'); ?>
                </span>
                <a href="/cookie-policy.php" class="text-reset text-decoration-none"><?php echo __('cookie_policy'); ?></a>
            </div>
        </div>
    </div>
</footer>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/animate.css/4.1.1/animate.min.css"/>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>

<!-- Mobile Bottom Navigation -->
<div class="mobile-nav d-md-none border-top border-secondary bg-surface">
    <a href="/" class="<?= $_SERVER['PHP_SELF'] == '/index.php' ? 'active' : '' ?>">
        <i class="bi bi-house-door"></i>
        <span><?= __('home') ?></span>
    </a>
    <a href="/market.php" class="<?= $_SERVER['PHP_SELF'] == '/market.php' ? 'active' : '' ?>">
        <i class="bi bi-graph-up"></i>
        <span><?= __('market_name') ?></span>
    </a>
    <a href="/trade.php" class="<?= in_array($_SERVER['PHP_SELF'], ['/trade.php', '/contract.php', '/binary.php']) ? 'active' : '' ?>">
        <i class="bi bi-arrow-left-right"></i>
        <span><?= __('trading') ?></span>
    </a>
    <a href="<?= isset($_SESSION['user_id']) ? '/profile.php' : '/auth/login.php' ?>" class="<?= $_SERVER['PHP_SELF'] == '/profile.php' ? 'active' : '' ?>">
        <i class="bi bi-wallet2"></i>
        <span><?= __('assets') ?></span>
    </a>
</div>

<style>
.mobile-nav {
    position: fixed;
    bottom: 0;
    left: 0;
    width: 100%;
    height: 70px;
    display: flex;
    justify-content: space-around;
    align-items: center;
    z-index: 10000;
    padding-bottom: env(safe-area-inset-bottom);
    background: rgba(30, 35, 41, 0.98) !important;
    border-top: 1px solid rgba(255, 255, 255, 0.05) !important;
    backdrop-filter: blur(15px);
    box-shadow: 0 -5px 20px rgba(0,0,0,0.3);
}
.mobile-nav a {
    display: flex;
    flex-direction: column;
    align-items: center;
    text-decoration: none !important;
    color: #848e9c;
    font-size: 10px;
    font-weight: 500;
    transition: all 0.2s cubic-bezier(0.4, 0, 0.2, 1);
    flex: 1;
    padding: 10px 0;
}
.mobile-nav a i {
    font-size: 22px;
    margin-bottom: 3px;
    transition: transform 0.2s;
}
.mobile-nav a.active {
    color: var(--primary);
}
.mobile-nav a.active i {
    transform: translateY(-2px);
}
.mobile-nav a span {
    transform: scale(0.9);
}
.mobile-nav a.active span {
    transform: scale(1);
    font-weight: 700;
}
/* Hide desktop elements on mobile if needed */
@media (max-width: 768px) {
    body { padding-bottom: 80px; }
    #cs-widget { bottom: 80px !important; }
}
</style>

<!-- Customer Service Widget -->
<?php
$service_link = getSetting('service_link');
?>
<div id="cs-widget" style="position: fixed; bottom: 30px; right: 30px; z-index: 9999;">
    <?php if ($service_link): ?>
        <a href="<?= htmlspecialchars($service_link) ?>" target="_blank" class="btn btn-primary rounded-circle shadow-lg p-0 d-flex align-items-center justify-content-center transition-all" style="width: 70px; height: 70px; border: none; background: linear-gradient(135deg, #00c6ff, #0072ff); box-shadow: 0 10px 20px rgba(0, 114, 255, 0.4);">
            <div class="position-relative d-flex align-items-center justify-content-center">
                <i class="bi bi-person-fill text-white position-absolute" style="font-size: 1.2rem; margin-top: 4px;"></i>
                <i class="bi bi-headset text-white" style="font-size: 2.4rem;"></i>
            </div>
        </a>
    <?php else: ?>
        <button class="btn btn-primary rounded-circle shadow-lg p-0 d-flex align-items-center justify-content-center transition-all" id="cs-toggle" style="width: 70px; height: 70px; border: none; background: linear-gradient(135deg, #00c6ff, #0072ff); box-shadow: 0 10px 20px rgba(0, 114, 255, 0.4);">
            <div class="position-relative d-flex align-items-center justify-content-center">
                <i class="bi bi-person-fill text-white position-absolute" style="font-size: 1.2rem; margin-top: 4px;"></i>
                <i class="bi bi-headset text-white" style="font-size: 2.4rem;"></i>
            </div>
        </button>
    <?php endif; ?>
    <div class="pulse-ring"></div>
</div>

<style>
.pulse-ring {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  border-radius: 50%;
  background: #0062ff;
  opacity: 0.5;
  animation: pulse 2s infinite;
  z-index: -1;
}
@keyframes pulse {
  0% { transform: scale(1); opacity: 0.5; }
  100% { transform: scale(1.5); opacity: 0; }
}
#cs-toggle:hover, #cs-widget a:hover {
    transform: scale(1.1) rotate(5deg);
    box-shadow: 0 10px 25px rgba(0, 98, 255, 0.4) !important;
}
</style>

<div id="cs-box" class="bg-surface border border-secondary shadow-lg d-none" style="position: fixed; bottom: 100px; right: 30px; width: 350px; height: 500px; border-radius: 20px; z-index: 9999; display: flex; flex-direction: column; overflow: hidden; background: #161a1e;">
    <div class="bg-primary p-3 d-flex justify-content-between align-items-center text-white">
        <div class="d-flex flex-column">
            <div class="d-flex align-items-center gap-2">
                <div class="bg-white rounded-circle" style="width: 10px; height: 10px;"></div>
                <span class="fw-bold"><?= __('online_support') ?></span>
            </div>
            <?php if (isset($_SESSION['username'])): ?>
            <div style="font-size: 10px; opacity: 0.8;">
                <?= htmlspecialchars($_SESSION['username']) ?>
            </div>
            <?php endif; ?>
        </div>
        <button class="btn btn-sm text-white border-0" id="cs-close"><i class="bi bi-x-lg"></i></button>
    </div>
    <div id="cs-messages" class="flex-grow-1 p-3 overflow-y-auto" style="scrollbar-width: none;">
        <div class="text-center text-muted small mb-3"><?= __('welcome_support') ?></div>
    </div>
    <div class="p-3 border-top border-secondary bg-black bg-opacity-20">
        <form id="cs-form" class="d-flex gap-2">
            <input type="file" id="cs-file-input" class="d-none" accept="image/*">
            <button type="button" id="cs-upload-btn" class="btn btn-outline-secondary btn-sm border-secondary"><i class="bi bi-plus-lg"></i></button>
            <input type="text" id="cs-input" class="form-control form-control-sm bg-dark border-secondary text-white" placeholder="<?= __('type_message') ?>">
            <button type="submit" class="btn btn-primary btn-sm px-3"><i class="bi bi-send-fill"></i></button>
        </form>
    </div>
</div>

<script>
(function() {
const csToggle = document.getElementById('cs-toggle');
const csBox = document.getElementById('cs-box');
const csClose = document.getElementById('cs-close');
const csForm = document.getElementById('cs-form');
const csInput = document.getElementById('cs-input');
const csMessages = document.getElementById('cs-messages');
const csUploadBtn = document.getElementById('cs-upload-btn');
const csFileInput = document.getElementById('cs-file-input');
const apiPath = (window.REL_PATH || '') + 'api/chat.php';

if (csUploadBtn) csUploadBtn.addEventListener('click', () => csFileInput.click());

if (csFileInput) csFileInput.addEventListener('change', async () => {
    if (!csFileInput.files[0]) return;
    const file = csFileInput.files[0];
    const localUrl = URL.createObjectURL(file);
    const tempId = 'temp_img_' + Date.now();
    const localMsgHtml = `<img src="${localUrl}" class="img-fluid rounded chat-img-preview" style="max-width: 100%; max-height: 250px; object-fit: contain; margin: 5px 0; opacity: 0.6;">`;
    
    appendMessageHTML({ id: tempId, sender: 'user', message: localMsgHtml, created_at: new Date().toISOString() });
    scrollToBottom();

    const formData = new FormData();
    formData.append('file', file);
    formData.append('action', 'upload_image');

    try {
        const resp = await fetch(apiPath, { method: 'POST', body: formData });
        const data = await resp.json();
        document.querySelector(`[data-id="${tempId}"]`)?.remove();
        if (data.success && data.message) {
            appendMessageHTML(data.message);
            scrollToBottom();
            pollMessages();
        } else {
            alert(data.error || '<?= __("send_failed") ?>');
        }
    } catch (err) {
        console.error('Upload error:', err);
        document.querySelector(`[data-id="${tempId}"]`)?.remove();
    }
    csFileInput.value = '';
    setTimeout(() => URL.revokeObjectURL(localUrl), 5000);
});

if (csToggle) csToggle.addEventListener('click', () => {
    csBox.classList.toggle('d-none');
    if (!csBox.classList.contains('d-none')) {
        const now = new Date();
        const timeStr = now.toLocaleTimeString('zh-CN', {hour: '2-digit', minute:'2-digit', second: '2-digit'});
        fetch(apiPath + '?action=ping&user_time=' + encodeURIComponent(timeStr));
        scrollToBottom();
        pollMessages();
    }
});

if (csClose) csClose.addEventListener('click', () => csBox.classList.add('d-none'));

function scrollToBottom() {
    setTimeout(() => { if (csMessages) csMessages.scrollTop = csMessages.scrollHeight; }, 50);
}

if (csForm) csForm.addEventListener('submit', async (e) => {
    e.preventDefault();
    const msg = csInput.value.trim();
    if (!msg) return;
    csInput.value = '';
    const tempId = 'temp_msg_' + Date.now();
    appendMessageHTML({ id: tempId, sender: 'user', message: msg, created_at: new Date().toISOString() });
    scrollToBottom();
    try {
        const resp = await fetch(apiPath + '?action=send_message', {
            method: 'POST',
            headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
            body: `message=${encodeURIComponent(msg)}`
        });
        const data = await resp.json();
        document.querySelector(`[data-id="${tempId}"]`)?.remove();
        if (data.success) {
            appendMessageHTML(data.message);
            scrollToBottom();
            pollMessages();
        }
    } catch (err) { console.error('Failed to send message:', err); }
});

function appendMessageHTML(m) {
    if (!m || !m.id || document.querySelector(`[data-id="${m.id}"]`)) return;
    const sender = m.sender;
    const text = (m.message || '').toString();
    const time = m.created_at || new Date().toISOString();
    const isImage = text.includes('<img') || text.includes('/assets/images/chat/') || text.includes('data:image');
    let displayMsg = text;
    if (isImage) {
        if (!displayMsg.includes('<img')) {
            displayMsg = `<img src="${displayMsg.includes('assets/') ? (window.REL_PATH || '') + displayMsg : displayMsg}" class="img-fluid rounded chat-img-preview" style="max-width: 100%; max-height: 250px; object-fit: contain; margin: 5px 0; cursor: zoom-in;" onclick="window.showLightbox ? window.showLightbox(this.src) : window.open(this.src)">`;
        }
        if (!displayMsg.includes('chat-img-preview')) displayMsg = displayMsg.replace('<img ', '<img class="chat-img-preview" ');
        if (displayMsg.includes('src="assets/')) displayMsg = displayMsg.replace('src="assets/', 'src="' + (window.REL_PATH || '') + 'assets/');
    }
    let dateObj = time.includes('-') ? new Date(time.replace(/-/g, "/")) : new Date(time);
    const timeStr = isNaN(dateObj.getTime()) ? '---' : dateObj.toLocaleTimeString('zh-CN', {hour: '2-digit', minute:'2-digit', second: '2-digit'});
    const msgHtml = `
        <div class="mb-3 d-flex ${sender === 'user' ? 'justify-content-end' : 'justify-content-start'} message-item w-100 animate__animated animate__fadeInUp animate__faster" data-id="${m.id}" style="--animate-duration: 0.3s;">
            <div class="d-flex flex-column ${sender === 'user' ? 'align-items-end' : 'align-items-start'}" style="max-width: 85%;">
                <div class="p-2 px-3 shadow-sm ${sender === 'user' ? 'bg-primary text-white bubble-user' : 'bg-dark text-white border border-secondary bubble-admin'}" style="word-break: break-all; position: relative; padding-bottom: 22px !important; min-width: 60px; ${isImage ? 'padding: 6px !important; padding-bottom: 6px !important; border-radius: 12px !important;' : ''}">
                    <div class="message-text" style="font-size: 14px; line-height: 1.5;">${displayMsg}</div>
                    <div style="font-size: 9px; opacity: 0.7; position: absolute; bottom: 5px; ${sender === 'user' ? 'right: 12px;' : 'left: 12px;'} ${isImage ? 'background: rgba(0,0,0,0.5); padding: 1px 6px; border-radius: 6px; bottom: 10px; right: 10px; backdrop-filter: blur(4px);' : ''}">${timeStr}</div>
                </div>
            </div>
        </div>`;
    csMessages.insertAdjacentHTML('beforeend', msgHtml);
}

let lastChatIds = new Set();
let lastPingTime = 0;
async function pollMessages() {
    if (csBox.classList.contains('d-none')) return;
    const now = Date.now();
    if (now - lastPingTime > 10000) {
        const timeStr = new Date().toLocaleTimeString('zh-CN', {hour: '2-digit', minute:'2-digit', second: '2-digit'});
        fetch(apiPath + '?action=ping&user_time=' + encodeURIComponent(timeStr));
        lastPingTime = now;
    }
    try {
        const resp = await fetch(apiPath + '?action=get_messages');
        const data = await resp.json();
        if (Array.isArray(data)) {
            let hasNew = false;
            data.forEach(m => { if (!lastChatIds.has(m.id)) { appendMessageHTML(m); lastChatIds.add(m.id); hasNew = true; } });
            if (hasNew) scrollToBottom();
        }
    } catch (err) {}
}
setInterval(pollMessages, 2000);
})();
</script>
<style>
.bg-darker { background-color: #080808; }
footer a:hover { color: var(--primary) !important; }
#cs-messages::-webkit-scrollbar { display: none; }
.bubble-user { border-radius: 18px 18px 2px 18px !important; background: linear-gradient(135deg, #00c6ff, #0072ff) !important; }
.bubble-admin { border-radius: 18px 18px 18px 2px !important; background: #1e2329 !important; }
.chat-img-preview { transition: transform 0.2s; }
.chat-img-preview:hover { transform: scale(1.02); }
</style>
</body>
</html>
