码桶

发现社区成员的开源项目

main
domains/js/main.js
main.js31.5 KB
/* ===== 全局配置区 ===== */
const FAVICON_URL = 'favicon.svg';

const WHOIS_API_KEY = '';
const WHOIS_API_URL = 'api/whois_proxy.php';

const videoList = [
    './video/video.mp4',
    './video/video2.mp4',
    './video/video3.mp4'
];

/* ===== 全局状态 ===== */
let currentSuffix = 'all';
let domains = [];
let isAdmin = false;
let adminApiUrl = 'admin/api.php';

/* ===== 初始化 favicon ===== */
function initAssets() {
    const tag = document.getElementById('faviconTag');
    if (tag) tag.href = FAVICON_URL;
}

/* ===== 管理员状态检测 ===== */
function checkAdminStatus() {
    const auth = getCookie('admin_auth');
    const path = getCookie('admin_path');
    if (auth === '1' && path) {
        isAdmin = true;
        adminApiUrl = path + '/api.php';
        document.body.classList.add('admin-mode');
        
        // 1. 显示【新增域名】按钮(这个刚才漏掉了)
        const btn = document.getElementById('addDomainBtn');
        if (btn) btn.style.display = '';
        
        // 2. 显示【桌面端】退出按钮
        const logout = document.getElementById('logoutLink');
        if (logout) logout.style.display = '';
        
        // 3. 显示【移动端】退出按钮(这个是新增的)
        const logoutMobile = document.getElementById('logoutLinkMobile');
        if (logoutMobile) logoutMobile.style.display = '';
    }
}


function getCookie(name) {
    const match = document.cookie.match(new RegExp('(^| )' + name + '=([^;]*)'));
    return match ? decodeURIComponent(match[2]) : '';
}

function eraseCookie(name) {
    document.cookie = name + '=; Max-Age=-99999999; path=/';
}

function adminLogout(e) {
    if (e) e.preventDefault();
    fetch(adminApiUrl + '?action=logout', { credentials: 'same-origin' })
        .catch(function(){})
        .finally(function() {
            eraseCookie('admin_auth');
            eraseCookie('admin_path');
            location.reload();
        });
}

/* ===== 星空背景 ===== */
function createStarfield() {
    const layer1 = document.getElementById('starLayer1');
    const layer2 = document.getElementById('starLayer2');
    const totalStars = 120;
    for (let i = 0; i < totalStars; i++) {
        const star = document.createElement('div');
        star.className = 'star';
        star.style.left = Math.random() * 100 + '%';
        star.style.top = Math.random() * 100 + '%';
        const size = Math.random() * 2;
        star.style.width = size + 'px';
        star.style.height = size + 'px';
        star.style.animationDelay = Math.random() * 5 + 's';
        if (i < totalStars / 2) {
            if (size < 1) star.style.width = '1.5px'; star.style.height = '1.5px';
            layer1.appendChild(star);
        } else { layer2.appendChild(star); }
    }
}

/* ===== 域名数据加载 ===== */
function loadDomains() {
    fetch(adminApiUrl + '?action=list')
        .then(function(r){ return r.json(); })
        .then(function(data){
            if (data.status && Array.isArray(data.result)) {
                domains = data.result;
                const hash = window.location.hash || '#/';
                if (!hash.includes('tools') && !hash.includes('contact') && !hash.includes('friends')) {
                    renderDomains(domains);
                }
            }
        })
        .catch(function(err){
            console.error('加载域名失败:', err);
            domains = [
                { name: 'timingme.com', registrar: '阿里云', registrarUrl: 'https://wanwang.aliyun.com/', meaning: '时光与我' }
            ];
            const hash = window.location.hash || '#/';
            if (!hash.includes('tools') && !hash.includes('contact') && !hash.includes('friends')) {
                renderDomains(domains);
            }
        });
}

/* ===== WHOIS 工具函数 ===== */
function formatDate(isoDate) {
    if (!isoDate) return '未知';
    try {
        const d = new Date(isoDate);
        if (isNaN(d.getTime())) return isoDate;
        return d.getFullYear() + '-' + (d.getMonth()+1).toString().padStart(2,'0') + '-' + d.getDate().toString().padStart(2,'0');
    } catch(e) {
        return isoDate;
    }
}

function fetchWhoisData(domainName) {
    return fetch(WHOIS_API_URL + '?query=' + encodeURIComponent(domainName), {
        method: 'GET',
        headers: { 'x-api-key': WHOIS_API_KEY, 'Content-Type': 'application/json' }
    })
    .then(function(response) {
        if (!response.ok) {
            if (response.status === 401) throw new Error('API Key 无效或已禁用');
            if (response.status === 403) throw new Error('IP 不在白名单中');
            if (response.status === 429) throw new Error('查询频率过高,请稍后再试');
            throw new Error('请求失败 (HTTP ' + response.status + ')');
        }
        return response.json();
    })
    .then(function(data) {
        if (!data.status || !data.result) {
            throw new Error(data.error || '查询失败:未找到该域名信息');
        }
        const r = data.result;
        return {
            "域名 / Domain Name": r.domain || domainName,
            "注册商 / Registrar": r.registrar || '未知',
            "创建时间 / Creation Date": formatDate(r.creationDate),
            "过期时间 / Expiry Date": formatDate(r.expirationDate),
            "DNS服务器 / Name Server": (r.nameServers && r.nameServers.length > 0) ? r.nameServers.join(', ') : '未知',
            "域名状态 / Domain Status": "ok (正常)",
            "数据来源 / Source": '<a href="https://yisi.yun/" target="_blank">OneFour</a>'
        };
    });
}

function renderWhois(data) {
    if (!data) return '<p style="color: var(--text-muted); text-align:center;">暂无数据</p>';
    let html = '<div class="whois-info-table">';
    for (const key in data) { html += '<div class="whois-row"><span class="whois-key">' + key + '</span><span class="whois-val">' + data[key] + '</span></div>'; }
    html += '</div>';
    return html;
}

function renderWhoisError(message) {
    return '<div class="whois-error"><div class="whois-error-icon">⚠️</div>' + message + '</div>';
}

/* ===== 询价记忆 ===== */
function getInquiredDomains() {
    try { return JSON.parse(localStorage.getItem('inquiredDomains') || '[]'); }
    catch(e) { return []; }
}

function markDomainInquired(domainName) {
    const list = getInquiredDomains();
    if (!list.includes(domainName)) {
        list.push(domainName);
        localStorage.setItem('inquiredDomains', JSON.stringify(list));
    }
}

/* ===== 域名卡片渲染 ===== */
function renderDomains(list) {
    const sortedList = [...list].sort((a, b) => a.name.localeCompare(b.name, 'en', { sensitivity: 'base' }));
    const domainList = document.getElementById('domainList');
    if (!domainList) return;
    domainList.innerHTML = '';
    domainList.style.display = 'grid';
    const inquiredList = getInquiredDomains();

    sortedList.forEach((domain, index) => {
        const card = document.createElement('div');
        card.className = 'domain-card';
        card.style.transitionDelay = (index * 0.05) + 's';
        const firstLetter = domain.name.charAt(0).toUpperCase();
        const restOfName = domain.name.slice(1);
        const displayName = '<span class="first-letter">' + firstLetter + '</span>' + restOfName;
        const domainUrl = 'https://' + domain.name.toLowerCase();
        const isInquired = inquiredList.includes(domain.name);
        const btnHtml = isInquired
            ? '<button class="inquiry-button inquired" disabled>已询价</button>'
            : '<button class="inquiry-button" onclick="openInquiryModal(\'' + domain.name + '\')">询价</button>';

        const adminIcons = isAdmin ? (
            '<div class="card-admin-icons">' +
                '<button class="admin-icon" onclick="openDomainModal(\'edit\',\'' + domain.name + '\')" title="编辑">' +
                    '<svg viewBox="0 0 24 24" width="18" height="18" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M11 4H4a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2v-7"></path><path d="M18.5 2.5a2.121 2.121 0 0 1 3 3L12 15l-4 1 1-4 9.5-9.5z"></path></svg>' +
                '</button>' +
                '<button class="admin-icon delete-icon" onclick="deleteDomain(\'' + domain.name + '\')" title="删除">' +
                    '<svg viewBox="0 0 24 24" width="18" height="18" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><polyline points="3 6 5 6 21 6"></polyline><path d="M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6m3 0V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2"></path></svg>' +
                '</button>' +
            '</div>'
        ) : '';

        card.innerHTML =
            adminIcons +
            '<div class="card-whois-icon" onclick="openWhoisModal(\'' + domain.name + '\')" title="查询WHOIS">' +
                '<svg viewBox="0 0 24 24" width="20" height="20" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"><circle cx="11" cy="11" r="8"></circle><line x1="21" y1="21" x2="16.65" y2="16.65"></line></svg>' +
            '</div>' +
            '<a href="' + domainUrl + '" target="_blank" rel="noopener noreferrer" class="domain-name" title="访问 ' + domain.name + '">' + displayName + '</a>' +
            '<div class="domain-meaning">' + domain.meaning + '</div>' +
            '<div class="card-footer">' +
                '<a href="' + domain.registrarUrl + '" target="_blank" class="registrar-badge">' + domain.registrar + '</a>' +
                btnHtml +
            '</div>';
        domainList.appendChild(card);
    });
    initIntersectionObserver();
}

function initIntersectionObserver() {
    const observer = new IntersectionObserver((entries) => {
        entries.forEach(entry => {
            if (entry.isIntersecting) {
                entry.target.classList.add('visible');
                observer.unobserve(entry.target);
            }
        });
    }, { threshold: 0.1 });
    document.querySelectorAll('.domain-card, .reveal').forEach(el => observer.observe(el));
}

function filterDomains() {
    const keyword = document.getElementById('searchInput').value.toLowerCase();
    const filtered = domains.filter(domain => {
        const matchSuffix = currentSuffix === 'all' || domain.name.toLowerCase().endsWith(currentSuffix);
        const matchKeyword = domain.name.toLowerCase().includes(keyword) || domain.meaning.toLowerCase().includes(keyword);
        return matchSuffix && matchKeyword;
    });
    renderDomains(filtered);
}

function setFilter(element) {
    document.querySelectorAll('.filter-tag').forEach(tag => tag.classList.remove('active'));
    element.classList.add('active');
    currentSuffix = element.getAttribute('data-suffix');
    filterDomains();
    const toolbar = document.getElementById('toolbar');
    if (toolbar) {
        const y = toolbar.getBoundingClientRect().top + window.pageYOffset - 80;
        window.scrollTo({ top: y, behavior: 'smooth' });
    }
}

/* ===== 首页 / 工具页 / 联系页 / 友情链接页 ===== */
function showHome() {
    document.getElementById('toolbar').style.display = 'flex';
    document.getElementById('searchInput').value = '';
    currentSuffix = 'all';
    document.querySelectorAll('.filter-tag').forEach((tag, i) => { tag.classList.toggle('active', i === 0); });
    renderDomains(domains);
    closeMenu();
    window.scrollTo({ top: 0, behavior: 'smooth' });
}

function showContact() {
    document.getElementById('toolbar').style.display = 'none';
    const domainList = document.getElementById('domainList');
    domainList.style.display = 'block';
    domainList.innerHTML = `
        <div class="about-section reveal" >
            <div class="contact-layout">
                <div class="contact-left-info">
                    <h2 style="font-size: 2em; margin-bottom: 20px;">联系</h2>
                    <p style="line-height: 1.8; margin-bottom: 16px;">在浩瀚无垠的数字宇宙中,每一个域名都是一颗独特的星辰,承载着品牌的价值与未来的可能。</p>
                    <p style="line-height: 1.8; margin-bottom: 24px;">如果您有任何疑问、合作意向或需要帮助,请直接通过右侧表单给我们发送星际电波,我们会尽快回复您。</p>
                    
                    <div class="contact-info-list">
                        <div class="contact-info-item">
                            <span style="font-size: 1.2em;">📍</span> 坐标:银河系 · 猎户旋臂 · 蓝色行星
                        </div>
                        <div class="contact-info-item">
                            <span style="font-size: 1.2em;">🌌</span> 服务范围:全宇宙
                        </div>
                    </div>
                </div>
                
                <div class="contact-right-form">
                    <div class="contact-form-card reveal" style="transition-delay: 0.15s;">
                        <h3>给我们留言</h3>
                        <form id="contactForm" class="inquiry-form">
                            <input type="hidden" name="_subject" value="来自联系页的留言">
                            <input type="hidden" name="_template" value="table">
                            <input type="hidden" name="_captcha" value="false">
                            <div class="form-group"><label>您的称呼</label><input type="text" name="name" placeholder="请输入您的姓名" required></div>
                            <div class="form-group"><label>联系邮箱</label><input type="email" name="email" placeholder="请输入您的邮箱" required></div>
                            <div class="form-group"><label>留言内容</label><textarea rows="6" name="message" placeholder="请输入您想对我们说的话..." required></textarea></div>
                            <button type="submit" class="submit-btn" id="contactSubmitBtn">发送电波</button>
                        </form>
                    </div>
                </div>
            </div>
        </div>
    `;
    
    const contactForm = document.getElementById('contactForm');
    contactForm.addEventListener('submit', function(e) {
        handleFormSubmit(e, this, '联系页直接留言');
    });

    closeMenu();
    window.scrollTo({ top: 0, behavior: 'smooth' });
    initIntersectionObserver();
    handleContactLayout();
}

function handleContactLayout() {
    const aboutSection = document.querySelector('#domainList > .about-section');
    if (!aboutSection) return;
    const layout = aboutSection.querySelector('.contact-layout');
    const domainList = document.getElementById('domainList');
    const rightForm = domainList.querySelector('.contact-right-form');
    if (!layout || !rightForm) return;
    
    const isMobile = window.matchMedia('(max-width: 1024px)').matches;
    if (isMobile) {
        if (rightForm.parentElement !== aboutSection.parentElement) {
            aboutSection.parentNode.insertBefore(rightForm, aboutSection.nextSibling);
        }
    } else {
        if (rightForm.parentElement !== layout) {
            layout.appendChild(rightForm);
        }
    }
}

function showTools() {
    document.getElementById('toolbar').style.display = 'none';
    const domainList = document.getElementById('domainList');
    domainList.style.display = 'block';
    domainList.innerHTML = `
        <div class="about-section reveal">
            <h2>域名工具箱</h2>
            <p style="margin-bottom: 20px; color: var(--text-secondary);">精选实用域名工具,助力您的数字资产评估与管理。</p>
            
            <div class="tool-section-title reveal" style="transition-delay: 0.1s">🛰️ WHOIS 实时查询</div>
            <div class="whois-search-box reveal" style="transition-delay: 0.15s">
                <input type="text" id="whoisSearchInput" placeholder="例如: vmdisk.com" onkeydown="if(event.key==='Enter') searchWhoisPage()">
                <button onclick="searchWhoisPage()">查询</button>
            </div>

            <div class="tool-section-title reveal" style="transition-delay: 0.2s; margin-top: 40px;">🛠️ 常用外部工具</div>
            <div class="tools-grid reveal" style="transition-delay: 0.25s">
                <a href="https://www.estibot.com/" target="_blank" class="tool-card">
                    <div class="tool-card-title">📊 EstiBot 估价</div>
                    <div class="tool-card-desc">利用大数据算法,快速评估域名的参考价值。</div>
                </a>
                <a href="https://web.archive.org/" target="_blank" class="tool-card">
                    <div class="tool-card-title">🕰️ 历史快照查询</div>
                    <div class="tool-card-desc">查看域名以前做过什么网站,排查是否有黑历史。</div>
                </a>
                <a href="https://www.expireddomains.net/" target="_blank" class="tool-card">
                    <div class="tool-card-title">📉 过期域名查询</div>
                    <div class="tool-card-desc">寻找刚掉落或即将过期的潜在数字资产。</div>
                </a>
                <a href="https://dnschecker.org/" target="_blank" class="tool-card">
                    <div class="tool-card-title">🌐 DNS 全球检测</div>
                    <div class="tool-card-desc">查询域名解析在全球各地的生效传播状态。</div>
                </a>
                <a href="https://ahrefs.com/free-seo-tools" target="_blank" class="tool-card">
                    <div class="tool-card-title">🔗 权重与外链</div>
                    <div class="tool-card-desc">查看域名是否自带老域名权重及外链情况。</div>
                </a>
                <a href="https://www.domcomp.com/" target="_blank" class="tool-card">
                    <div class="tool-card-title">💰 注册商比价</div>
                    <div class="tool-card-desc">对比全球各大域名注册商的注册与续费价格。</div>
                </a>
            </div>
        </div>
    `;
    closeMenu();
    window.scrollTo({ top: 0, behavior: 'smooth' });
    initIntersectionObserver();
}

/* ===== 友情链接页面 ===== */
function showFriends() {
    document.getElementById('toolbar').style.display = 'none';
    const domainList = document.getElementById('domainList');
    domainList.style.display = 'block';
    domainList.innerHTML = `
        <div class="about-section reveal">
            <h2>友情链接</h2>
            <p style="margin-bottom: 20px; color: var(--text-secondary);">以下是一些值得关注的优质网站</p>
            
            <div class="tool-section-title reveal" style="transition-delay: 0.1s">🌟 常用网站</div>
            <div class="tools-grid reveal" style="transition-delay: 0.15s">
                <a href="https://dalao.net" target="_blank" class="tool-card">
                    <div class="tool-card-title">大佬论坛</div>
                    <div class="tool-card-desc">全球最大的国别域名交易平台。</div>
                </a>
                <a href="https://yisi.yun/" target="_blank" class="tool-card">
                    <div class="tool-card-title">OneFour</div>
                    <div class="tool-card-desc">很好用的Whois查询平台</div>
                </a>
            </div>
            
            <p style="margin-bottom: 20px; color: var(--text-secondary);">值得一逛的朋友们的米表,多一些选择,排名不分先后</p>
            <div class="tool-section-title reveal" style="transition-delay: 0.1s">🌟优质米友</div>
            <div class="tools-grid reveal" style="transition-delay: 0.15s">
                <a href="https://www.shaimi.net/" target="_blank" class="tool-card">
                    <div class="tool-card-title">晒米网</div>
                    <div class="tool-card-desc">有好米的卖米的大佬的卖米网^_^</div>
                </a>
                 <a href="https://u.wales" target="_blank" class="tool-card">
                    <div class="tool-card-title">米袋子</div>
                    <div class="tool-card-desc">有好米的卖米的大佬的卖米网^_^</div>
                </a>
                <a href="https://mi.023.me" target="_blank" class="tool-card">
                    <div class="tool-card-title">023 米表</div>
                    <div class="tool-card-desc">有好米的卖米的大佬的卖米网^_^</div>
                </a>
            </div>
            
            
        </div>
    `;
    closeMenu();
    window.scrollTo({ top: 0, behavior: 'smooth' });
    initIntersectionObserver();
}

/* ===== 路由 ===== */
function router() {
    const hash = window.location.hash || '#/';
    closeInquiryModal();
    closeWhoisModal();
    closeCustomAlert();
    
    // 1. 先判断是不是工具页
    if (hash.includes('tools') || hash.includes('whois')) {
        showTools();
    } 
    // 2. 再判断是不是友情链接页
    else if (hash.includes('friends')) {
        showFriends();
    } 
    // 3. 再判断是不是联系页
    else if (hash.includes('contact')) {
        showContact();
    } 
    // 4. 最后剩下的才默认显示首页
    else {
        showHome();
    }
    
    // 恢复原始逻辑:每次路由切换都立即播放随机视频
    playRandomVideo();
}

function playRandomVideo() {
    // 恢复原始实现:无延迟,无锁,立即加载播放
    const videoElement = document.getElementById('introVideo');
    if (!videoElement) return;
    const randomVideo = videoList[Math.floor(Math.random() * videoList.length)];
    const sourceElement = videoElement.querySelector('source');
    if (sourceElement && sourceElement.src.indexOf(randomVideo) === -1) {
        sourceElement.src = randomVideo;
        videoElement.load();
        videoElement.play().catch(function(){});
    }
}

/* ===== WHOIS 弹窗 ===== */
function searchWhoisPage() {
    const input = document.getElementById('whoisSearchInput').value.trim().toLowerCase();
    if (!input) { showCustomAlert('提示', '请输入域名'); return; }
    if (!input.includes('.')) { showCustomAlert('格式错误', '域名格式不正确,需包含后缀(如.com)'); return; }
    openWhoisModal(input);
}

function openWhoisModal(domainName) {
    document.getElementById('whoisDomainName').textContent = domainName;
    const resultBox = document.getElementById('whoisModalResult');
    resultBox.innerHTML = '<div class="whois-loading"><div class="whois-spinner"></div>正在查询星际数据库...</div>';
    document.getElementById('whoisModalOverlay').classList.add('active');
    
    fetchWhoisData(domainName)
        .then(data => { resultBox.innerHTML = renderWhois(data); })
        .catch(error => {
            console.error('WHOIS查询失败:', error);
            let msg = error.message || '查询失败';
            if (error.name === 'TypeError' && error.message.includes('Failed to fetch')) {
                msg = '无法连接查询服务(可能是跨域限制或网络问题),请稍后重试。';
            }
            resultBox.innerHTML = renderWhoisError(msg);
        });
}

function closeWhoisModal() { document.getElementById('whoisModalOverlay').classList.remove('active'); }

/* ===== 自定义提示 ===== */
function showCustomAlert(title, message) {
    document.getElementById('customAlertTitle').textContent = title;
    document.getElementById('customAlertMessage').innerHTML = message;
    document.getElementById('customAlertOverlay').classList.add('active');
}
function closeCustomAlert() { document.getElementById('customAlertOverlay').classList.remove('active'); }

/* ===== 主题 / 菜单 ===== */
function toggleTheme() {
    const newTheme = document.documentElement.getAttribute('data-theme') === 'light' ? 'dark' : 'light';
    document.documentElement.setAttribute('data-theme', newTheme);
    localStorage.setItem('theme', newTheme);
}

function toggleMenu() {
    document.getElementById('hamburger').classList.toggle('active');
    document.getElementById('mobileMenu').classList.toggle('active');
    document.getElementById('overlay').classList.toggle('active');
}
function closeMenu() {
    document.getElementById('hamburger').classList.remove('active');
    document.getElementById('mobileMenu').classList.remove('active');
    document.getElementById('overlay').classList.remove('active');
}

/* ===== 询价弹窗与表单提交 ===== */
let currentInquiryDomain = '';
function openInquiryModal(domainName) {
    currentInquiryDomain = domainName;
    document.getElementById('modalDomainName').textContent = domainName;
    const form = document.getElementById('inquiryForm');
    form.reset();
    const btn = document.getElementById('submitBtn');
    btn.textContent = '提交信息';
    btn.disabled = false;
    document.getElementById('modalOverlay').classList.add('active');
}
function closeInquiryModal() { document.getElementById('modalOverlay').classList.remove('active'); }

function handleFormSubmit(e, formElement, context) {
    e.preventDefault();
    const btn = formElement.querySelector('button[type="submit"]');
    const originalText = btn.textContent;
    btn.textContent = '正在发送星际电波...';
    btn.disabled = true;

    const formData = new FormData(formElement);
    formData.append('Context', context);
    const object = {};
    formData.forEach((value, key) => { object[key] = value; });
    const json = JSON.stringify(object);

    fetch('https://formsubmit.co/ajax/[email protected]', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json', 'Accept': 'application/json' },
        body: json
    })
    .then(response => {
        if (!response.ok) throw new Error('Network response was not ok');
        return response.json();
    })
    .then(data => {
        console.log("Formsubmit response:", data);
        if (context !== '联系页直接留言') {
            markDomainInquired(context);
            const hash = window.location.hash || '#/';
            if (!hash.includes('tools') && !hash.includes('contact') && !hash.includes('friends')) {
                renderDomains(domains);
            }
            closeInquiryModal();
        } else {
            formElement.reset();
            btn.textContent = originalText;
            btn.disabled = false;
        }
        showCustomAlert('发送成功', '我们已收到您的星际电波,会尽快与您联系。');
    })
    .catch(error => {
        console.error('Error:', error);
        showCustomAlert('发送失败', '网络异常,请稍后重试。');
        btn.textContent = originalText;
        btn.disabled = false;
    });
}

/* ===== 域名增删改查 ===== */
function openDomainModal(action, name) {
    const modal = document.getElementById('domainModalOverlay');
    document.getElementById('domainAction').value = action;
    if (action === 'edit') {
        document.getElementById('domainModalTitle').textContent = '编辑域名';
        const domain = domains.find(d => d.name === name);
        if (!domain) return;
        document.getElementById('originalName').value = domain.name;
        document.getElementById('domainNameInput').value = domain.name;
        document.getElementById('domainRegistrarInput').value = domain.registrar;
        document.getElementById('domainRegistrarUrlInput').value = domain.registrarUrl;
        document.getElementById('domainMeaningInput').value = domain.meaning;
    } else {
        document.getElementById('domainModalTitle').textContent = '新增域名';
        document.getElementById('domainForm').reset();
        document.getElementById('originalName').value = '';
    }
    modal.classList.add('active');
}

function closeDomainModal() { document.getElementById('domainModalOverlay').classList.remove('active'); }

function submitDomainForm(e) {
    e.preventDefault();
    const btn = document.getElementById('domainSubmitBtn');
    btn.disabled = true;
    btn.textContent = '保存中...';

    const payload = {
        action: document.getElementById('domainAction').value,
        originalName: document.getElementById('originalName').value,
        name: document.getElementById('domainNameInput').value,
        registrar: document.getElementById('domainRegistrarInput').value,
        registrarUrl: document.getElementById('domainRegistrarUrlInput').value,
        meaning: document.getElementById('domainMeaningInput').value
    };

    fetch(adminApiUrl, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(payload),
        credentials: 'same-origin'
    })
    .then(r => r.json())
    .then(data => {
        if (data.status) {
            domains = data.result;
            const hash = window.location.hash || '#/';
            if (!hash.includes('tools') && !hash.includes('contact') && !hash.includes('friends')) renderDomains(domains);
            closeDomainModal();
            showCustomAlert('成功', '操作已成功保存');
        } else {
            showCustomAlert('失败', data.error || '操作失败');
        }
    })
    .catch(() => showCustomAlert('错误', '网络请求失败'))
    .finally(() => { btn.disabled = false; btn.textContent = '保存'; });
}

function deleteDomain(name) {
    if (!confirm('确定要删除 ' + name + ' 吗?')) return;
    fetch(adminApiUrl, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ action: 'delete', name: name }),
        credentials: 'same-origin'
    })
    .then(r => r.json())
    .then(data => {
        if (data.status) {
            domains = data.result;
            const hash = window.location.hash || '#/';
            if (!hash.includes('tools') && !hash.includes('contact') && !hash.includes('friends')) renderDomains(domains);
        }
    });
}

/* ===== 滚动 / 弹窗关闭 / 键盘 ===== */
function scrollToTop() { window.scrollTo({ top: 0, behavior: 'smooth' }); }
window.addEventListener('scroll', function() {
    const backToTopBtn = document.getElementById('backToTop');
    if (window.pageYOffset > 300) backToTopBtn.classList.add('active'); else backToTopBtn.classList.remove('active');
});

document.getElementById('inquiryForm').addEventListener('submit', function(e) {
    handleFormSubmit(e, this, currentInquiryDomain);
});

document.getElementById('modalOverlay').addEventListener('click', function(e) { if (e.target === this) closeInquiryModal(); });
document.getElementById('whoisModalOverlay').addEventListener('click', function(e) { if (e.target === this) closeWhoisModal(); });
document.getElementById('customAlertOverlay').addEventListener('click', function(e) { if (e.target === this) closeCustomAlert(); });
document.getElementById('domainModalOverlay').addEventListener('click', function(e) { if (e.target === this) closeDomainModal(); });

document.addEventListener('keydown', function(e) {
    if (e.key === 'Escape') { closeInquiryModal(); closeWhoisModal(); closeCustomAlert(); closeDomainModal(); closeMenu(); }
});

window.addEventListener('hashchange', router);

/* ===== 启动 ===== */
window.onload = function() {
    initAssets();
    createStarfield();
    checkAdminStatus();
    loadDomains();
    router();
    
    // 首次加载随机选择一个视频(保持原始逻辑)
    const randomVideo = videoList[Math.floor(Math.random() * videoList.length)];
    const videoElement = document.getElementById('introVideo');
    const sourceElement = videoElement.querySelector('source');
    if (sourceElement) {
        sourceElement.src = randomVideo;
        videoElement.load();
    }
    videoElement.play().catch(function(){});

    // 监听断点变化:联系页表单在移动端/PC端之间自动外移或归位
    const contactMql = window.matchMedia('(max-width: 1024px)');
    contactMql.addEventListener('change', handleContactLayout);
};