<?php
ob_start();
requireAdmin();

// 获取当前配置
$configs = $db->fetchAll("SELECT * FROM quick_login_config ORDER BY sort ASC, id ASC");

// 定义所有支持的登录方式（用于新增）
$available_types = [
    'qq'       => ['name' => 'QQ登录', 'icon' => 'qq.svg', 'color' => '#12B7F5', 'type' => 'independent'],
    'gitee'    => ['name' => 'Gitee登录', 'icon' => 'gitee.svg', 'color' => '#C71D23', 'type' => 'independent'],
    'lhouath'  => ['name' => '麟泓登录', 'icon' => 'lhoauth.svg', 'color' => '#000000', 'type' => 'independent'],
    'wx'       => ['name' => '微信登录', 'icon' => 'wechat.svg', 'color' => '#07C160', 'type' => 'union'],
    'alipay'   => ['name' => '支付宝登录', 'icon' => 'alipay.svg', 'color' => '#1677FF', 'type' => 'union'],
    'github'   => ['name' => 'GitHub登录', 'icon' => 'github.svg', 'color' => '#24292E', 'type' => 'independent'],
    'google'   => ['name' => 'Google登录', 'icon' => 'google.svg', 'color' => '#4285F4', 'type' => 'union'],
    'microsoft'=> ['name' => 'Microsoft登录', 'icon' => 'microsoft.svg', 'color' => '#00A4EF', 'type' => 'union'],
    'facebook' => ['name' => 'Facebook登录', 'icon' => 'facebook.svg', 'color' => '#1877F2', 'type' => 'union'],
    'twitter'  => ['name' => 'Twitter登录', 'icon' => 'twitter.svg', 'color' => '#1DA1F2', 'type' => 'union'],
    'feishu'   => ['name' => '飞书登录', 'icon' => 'feishu.svg', 'color' => '#00C4A0', 'type' => 'union'],
    'wework'   => ['name' => '企业微信登录', 'icon' => 'wework.svg', 'color' => '#2C7A3E', 'type' => 'union'],
    'dingtalk' => ['name' => '钉钉登录', 'icon' => 'dingtalk.svg', 'color' => '#1E9AEF', 'type' => 'union'],
    'sina'     => ['name' => '微博登录', 'icon' => 'weibo.svg', 'color' => '#FF8200', 'type' => 'union'],
    'baidu'    => ['name' => '百度登录', 'icon' => 'baidu.svg', 'color' => '#2932E1', 'type' => 'union'],
    'xiaomi'   => ['name' => '小米登录', 'icon' => 'xiaomi.svg', 'color' => '#FF6900', 'type' => 'union'],
    'huawei'   => ['name' => '华为登录', 'icon' => 'huawei.svg', 'color' => '#FF0000', 'type' => 'union'],
    'douyin'   => ['name' => '抖音登录', 'icon' => 'douyin.svg', 'color' => '#000000', 'type' => 'union'],
];

// 获取已添加的类型
$added_types = array_column($configs, 'type');
?>

<div class="quick-login-container">
    <!-- 页面头部 -->
    <div class="page-header">
        <div>
            <h2>
                <img src="https://api.iconify.design/mdi:login.svg?color=%23667eea" width="26" height="26" style="vertical-align: middle; margin-right: 10px;" alt="">
                快捷登录管理
            </h2>
            <p class="page-desc">管理第三方登录方式的启用/禁用、排序和显示</p>
        </div>
        <div class="header-actions">
            <a href="?page=quick_login_config" class="btn btn-secondary">
                <img src="https://api.iconify.design/mdi:cog.svg?color=currentColor" width="18" height="18" style="margin-right: 6px;" alt="">
                登录配置
            </a>
            <button class="btn btn-primary" id="showAddModalBtn">
                <img src="https://api.iconify.design/mdi:plus.svg?color=white" width="18" height="18" style="margin-right: 6px;" alt="">
                添加登录方式
            </button>
        </div>
    </div>
    
    <!-- 配置列表 -->
    <div class="table-wrapper">
        <table class="data-table" id="configTable">
            <thead>
                <tr>
                    <th style="width: 8%;">图标</th>
                    <th style="width: 12%;">类型</th>
                    <th style="width: 15%;">显示名称</th>
                    <th style="width: 15%;">配置类型</th>
                    <th style="width: 8%;">排序</th>
                    <th style="width: 10%;">状态</th>
                    <th style="width: 20%;">操作</th>
                </tr>
            </thead>
            <tbody>
                <?php if (empty($configs)): ?>
                    <tr>
                        <td colspan="7">
                            <div class="empty-state">
                                <img src="https://api.iconify.design/mdi:login-variant.svg?color=%239ca3af" width="48" height="48" alt="">
                                <p>暂无快捷登录方式</p>
                                <span>点击上方按钮添加登录方式</span>
                            </div>
                        </td>
                    </tr>
                <?php else: ?>
                    <?php foreach ($configs as $config): 
                        $type_info = $available_types[$config['type']] ?? ['name' => $config['type'], 'icon' => 'default.svg', 'color' => '#667eea', 'type' => 'union'];
                    ?>
                        <tr id="row-<?php echo $config['id']; ?>">
                            <td>
                                <div class="login-icon" style="background: <?php echo $type_info['color']; ?>;">
                                    <img src="/assets/svg/<?php echo $config['icon'] ?: $type_info['icon']; ?>" alt="<?php echo htmlspecialchars($config['name']); ?>">
                                </div>
                            </td>
                            <td><span class="type-badge"><?php echo htmlspecialchars($config['type']); ?></span></td>
                            <td><strong><?php echo htmlspecialchars($config['name']); ?></strong></td>
                            <td>
                                <span class="config-type-badge <?php echo $type_info['type']; ?>">
                                    <?php echo $type_info['type'] == 'independent' ? '独立配置' : '彩虹聚合'; ?>
                                </span>
                            </td>
                            <td><?php echo $config['sort']; ?></td>
                            <td>
                                <span class="status-badge status-<?php echo $config['enabled'] ? 'active' : 'inactive'; ?>" id="status-badge-<?php echo $config['id']; ?>">
                                    <span class="status-dot"></span>
                                    <?php echo $config['enabled'] ? '启用' : '禁用'; ?>
                                </span>
                            </td>
                            <td class="action-buttons">
                                <button class="action-btn edit-btn" data-id="<?php echo $config['id']; ?>" title="编辑">
                                    <img src="https://api.iconify.design/mdi:pencil.svg?color=%23667eea" width="18" height="18" alt="">
                                </button>
                                <button class="action-btn toggle-btn" data-id="<?php echo $config['id']; ?>" data-status="<?php echo $config['enabled']; ?>" title="<?php echo $config['enabled'] ? '禁用' : '启用'; ?>">
                                    <?php if ($config['enabled']): ?>
                                        <img src="https://api.iconify.design/mdi:eye-off.svg?color=%23ef4444" width="18" height="18" alt="">
                                    <?php else: ?>
                                        <img src="https://api.iconify.design/mdi:eye.svg?color=%2310b981" width="18" height="18" alt="">
                                    <?php endif; ?>
                                </button>
                                <button class="action-btn test-btn" data-type="<?php echo $config['type']; ?>" title="测试配置">
                                    <img src="https://api.iconify.design/mdi:connection.svg?color=%23f59e0b" width="18" height="18" alt="">
                                </button>
                                <button class="action-btn delete-btn" data-id="<?php echo $config['id']; ?>" title="删除">
                                    <img src="https://api.iconify.design/mdi:delete.svg?color=%23ef4444" width="18" height="18" alt="">
                                </button>
                            </td>
                        </tr>
                    <?php endforeach; ?>
                <?php endif; ?>
            </tbody>
        </table>
    </div>
</div>

<!-- 添加/编辑弹窗 -->
<div id="editModal" class="modal" style="display: none;">
    <div class="modal-content">
        <div class="modal-header">
            <h3 id="modalTitle">
                <img src="https://api.iconify.design/mdi:plus.svg?color=%23667eea" width="20" height="20" style="margin-right: 8px;" alt="">
                添加登录方式
            </h3>
            <button type="button" class="modal-close" onclick="closeModal()">
                <img src="https://api.iconify.design/mdi:close.svg?color=%239ca3af" width="20" height="20" alt="">
            </button>
        </div>
        <form id="editForm">
            <input type="hidden" name="id" id="edit_id">
            <div class="modal-body">
                <div class="form-group">
                    <label>
                        <img src="https://api.iconify.design/mdi:login.svg?color=%23667eea" width="16" height="16" style="margin-right: 6px;" alt="">
                        登录类型 <span class="required">*</span>
                    </label>
                    <select name="type" id="edit_type" required <?php echo isset($_GET['edit']) ? 'disabled' : ''; ?>>
                        <option value="">请选择登录类型</option>
                        <?php foreach ($available_types as $key => $info): ?>
                            <?php if (!in_array($key, $added_types) || (isset($_GET['edit']) && $_GET['type'] == $key)): ?>
                            <option value="<?php echo $key; ?>" data-icon="<?php echo $info['icon']; ?>" data-color="<?php echo $info['color']; ?>">
                                <?php echo $info['name']; ?> <?php echo $info['type'] == 'independent' ? '' : ''; ?>
                            </option>
                            <?php endif; ?>
                        <?php endforeach; ?>
                    </select>
                    <small>选择登录类型后不可修改</small>
                </div>
                <div class="form-group">
                    <label>
                        <img src="https://api.iconify.design/mdi:format-title.svg?color=%23667eea" width="16" height="16" style="margin-right: 6px;" alt="">
                        显示名称 <span class="required">*</span>
                    </label>
                    <input type="text" name="name" id="edit_name" required placeholder="例如：QQ登录">
                </div>
                <div class="form-group">
                    <label>
                        <img src="https://api.iconify.design/mdi:image.svg?color=%23667eea" width="16" height="16" style="margin-right: 6px;" alt="">
                        图标文件
                    </label>
                    <input type="text" name="icon" id="edit_icon" placeholder="例如：qq.svg">
                    <small>图标存放在 /assets/svg/ 目录，留空则使用默认图标</small>
                </div>
                <div class="form-row">
                    <div class="form-group" style="flex:1">
                        <label>
                            <img src="https://api.iconify.design/mdi:sort.svg?color=%23667eea" width="16" height="16" style="margin-right: 6px;" alt="">
                            排序
                        </label>
                        <input type="number" name="sort" id="edit_sort" value="0" min="0">
                        <small>数字越小越靠前</small>
                    </div>
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" onclick="closeModal()">
                    <img src="https://api.iconify.design/mdi:close.svg?color=currentColor" width="16" height="16" style="margin-right: 4px;" alt="">
                    取消
                </button>
                <button type="submit" class="btn btn-primary">
                    <img src="https://api.iconify.design/mdi:content-save.svg?color=white" width="16" height="16" style="margin-right: 4px;" alt="">
                    保存
                </button>
            </div>
        </form>
    </div>
</div>

<!-- 测试结果弹窗 -->
<div id="testResultModal" class="modal" style="display: none;">
    <div class="modal-content" style="max-width: 400px;">
        <div class="modal-header">
            <h3 id="testResultTitle">
                <img src="https://api.iconify.design/mdi:connection.svg?color=%23667eea" width="20" height="20" style="margin-right: 8px;" alt="">
                测试结果
            </h3>
            <button type="button" class="modal-close" onclick="closeTestModal()">
                <img src="https://api.iconify.design/mdi:close.svg?color=%239ca3af" width="20" height="20" alt="">
            </button>
        </div>
        <div class="modal-body">
            <div id="testResultContent"></div>
        </div>
        <div class="modal-footer">
            <button type="button" class="btn btn-primary" onclick="closeTestModal()">关闭</button>
        </div>
    </div>
</div>

<style>
.quick-login-container {
    max-width: 100%;
    padding: 4px;
}

.page-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 28px;
    flex-wrap: wrap;
    gap: 16px;
}
.page-header h2 {
    display: flex;
    align-items: center;
    font-size: 24px;
    font-weight: 600;
    color: var(--text-primary);
    margin: 0 0 6px;
}
.page-desc {
    color: var(--text-muted);
    font-size: 14px;
    margin-left: 36px;
}
.header-actions {
    display: flex;
    gap: 10px;
}

/* 按钮 */
.btn {
    display: inline-flex;
    align-items: center;
    justify-content: center;
    gap: 6px;
    padding: 10px 20px;
    border-radius: 10px;
    font-size: 14px;
    font-weight: 500;
    text-decoration: none;
    cursor: pointer;
    transition: all 0.2s;
    border: 1px solid transparent;
}
.btn-primary {
    background: var(--primary-color);
    color: white;
    box-shadow: 0 2px 4px rgba(102, 126, 234, 0.2);
}
.btn-primary:hover {
    background: var(--primary-hover);
    transform: translateY(-1px);
}
.btn-secondary {
    background: var(--bg-primary);
    color: var(--text-primary);
    border-color: var(--border-color);
}
.btn-secondary:hover {
    background: var(--bg-secondary);
    border-color: var(--text-muted);
}

/* 表格 */
.table-wrapper {
    overflow-x: auto;
    background: var(--bg-primary);
    border-radius: 16px;
    border: 1px solid var(--border-color);
    box-shadow: var(--shadow-sm);
}
.data-table {
    width: 100%;
    border-collapse: collapse;
    min-width: 800px;
}
.data-table th {
    padding: 16px;
    text-align: left;
    font-weight: 600;
    font-size: 13px;
    color: var(--text-secondary);
    background: var(--bg-secondary);
    border-bottom: 1px solid var(--border-color);
    text-transform: uppercase;
    letter-spacing: 0.3px;
}
.data-table td {
    padding: 16px;
    border-bottom: 1px solid var(--border-color);
    font-size: 14px;
    vertical-align: middle;
}
.data-table tbody tr:hover {
    background: var(--bg-secondary);
}
.data-table tbody tr:last-child td {
    border-bottom: none;
}

/* 登录图标 */
.login-icon {
    width: 40px;
    height: 40px;
    border-radius: 10px;
    display: flex;
    align-items: center;
    justify-content: center;
}
.login-icon img {
    width: 22px;
    height: 22px;
    filter: brightness(0) invert(1);
}

/* 徽章 */
.type-badge {
    display: inline-block;
    padding: 4px 10px;
    background: var(--bg-secondary);
    border-radius: 20px;
    font-size: 12px;
    font-family: monospace;
}
.config-type-badge {
    display: inline-block;
    padding: 4px 10px;
    border-radius: 20px;
    font-size: 12px;
    font-weight: 500;
}
.config-type-badge.independent {
    background: #e0e7ff;
    color: #4338ca;
}
.config-type-badge.union {
    background: #fef3c7;
    color: #92400e;
}

/* 状态徽章 */
.status-badge {
    display: inline-flex;
    align-items: center;
    gap: 6px;
    padding: 5px 12px;
    border-radius: 30px;
    font-size: 12px;
    font-weight: 500;
}
.status-dot {
    width: 6px;
    height: 6px;
    border-radius: 50%;
}
.status-active {
    background: #d1fae5;
    color: #065f46;
}
.status-active .status-dot {
    background: #10b981;
}
.status-inactive {
    background: #fee2e2;
    color: #991b1b;
}
.status-inactive .status-dot {
    background: #ef4444;
}

/* 操作按钮 */
.action-buttons {
    display: flex;
    gap: 6px;
}
.action-btn {
    display: inline-flex;
    align-items: center;
    justify-content: center;
    width: 34px;
    height: 34px;
    background: var(--bg-secondary);
    border: 1px solid var(--border-color);
    border-radius: 8px;
    cursor: pointer;
    transition: all 0.2s;
}
.action-btn:hover {
    background: var(--bg-primary);
    border-color: var(--primary-color);
    transform: translateY(-1px);
    box-shadow: var(--shadow-sm);
}
.delete-btn:hover {
    border-color: var(--danger-color);
    background: #fef2f2;
}
.test-btn:hover {
    border-color: var(--warning-color);
    background: #fef3c7;
}

/* 空状态 */
.empty-state {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    padding: 48px 20px;
    text-align: center;
}
.empty-state img {
    opacity: 0.4;
    margin-bottom: 16px;
}
.empty-state p {
    color: var(--text-secondary);
    font-size: 16px;
    margin: 0 0 4px;
}
.empty-state span {
    color: var(--text-muted);
    font-size: 14px;
}

/* 弹窗 */
.modal {
    position: fixed;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    background: rgba(0, 0, 0, 0.5);
    backdrop-filter: blur(4px);
    display: flex;
    align-items: center;
    justify-content: center;
    z-index: 10000;
}
.modal-content {
    background: var(--bg-primary);
    border-radius: 20px;
    width: 90%;
    max-width: 500px;
    box-shadow: var(--shadow-lg);
}
.modal-header {
    padding: 20px 24px;
    border-bottom: 1px solid var(--border-color);
    display: flex;
    justify-content: space-between;
    align-items: center;
}
.modal-header h3 {
    display: flex;
    align-items: center;
    font-size: 18px;
    font-weight: 600;
    margin: 0;
}
.modal-close {
    background: none;
    border: none;
    cursor: pointer;
    padding: 4px;
    border-radius: 8px;
    transition: background 0.2s;
    display: flex;
}
.modal-close:hover {
    background: var(--bg-secondary);
}
.modal-body {
    padding: 24px;
}
.modal-footer {
    padding: 16px 24px 24px;
    display: flex;
    gap: 12px;
    justify-content: flex-end;
}

/* 表单 */
.form-group {
    margin-bottom: 20px;
}
.form-group label {
    display: flex;
    align-items: center;
    margin-bottom: 8px;
    font-weight: 500;
    font-size: 14px;
    color: var(--text-primary);
}
.required {
    color: var(--danger-color);
    margin-left: 2px;
}
.form-group input,
.form-group select {
    width: 100%;
    padding: 12px 16px;
    border: 1.5px solid var(--border-color);
    border-radius: 10px;
    font-size: 14px;
    background: var(--bg-primary);
    color: var(--text-primary);
    transition: all 0.2s;
}
.form-group input:focus,
.form-group select:focus {
    outline: none;
    border-color: var(--primary-color);
    box-shadow: 0 0 0 3px rgba(102, 126, 234, 0.1);
}
.form-group small {
    display: block;
    margin-top: 6px;
    font-size: 12px;
    color: var(--text-muted);
}
.form-row {
    display: flex;
    gap: 16px;
}

/* 测试结果 */
.test-success {
    display: flex;
    align-items: center;
    gap: 10px;
    padding: 16px;
    background: #d1fae5;
    border-radius: 12px;
    color: #065f46;
}
.test-error {
    display: flex;
    align-items: center;
    gap: 10px;
    padding: 16px;
    background: #fee2e2;
    border-radius: 12px;
    color: #991b1b;
}

/* 响应式 */
@media (max-width: 768px) {
    .page-header {
        flex-direction: column;
        align-items: flex-start;
    }
    .header-actions {
        width: 100%;
    }
    .header-actions .btn {
        flex: 1;
    }
    .form-row {
        flex-direction: column;
        gap: 0;
    }
    .action-buttons {
        flex-wrap: wrap;
    }
}
</style>

<script>
const modal = document.getElementById('editModal');
const form = document.getElementById('editForm');
const testModal = document.getElementById('testResultModal');

// 已添加的类型
const addedTypes = <?php echo json_encode($added_types); ?>;

function openModal(data) {
    const titleEl = document.getElementById('modalTitle');
    const typeSelect = document.getElementById('edit_type');
    
    if (data && !data.error) {
        titleEl.innerHTML = '<img src="https://api.iconify.design/mdi:pencil.svg?color=%23667eea" width="20" height="20" style="margin-right: 8px;" alt="">编辑登录方式';
        document.getElementById('edit_id').value = data.id || '';
        document.getElementById('edit_name').value = data.name || '';
        document.getElementById('edit_icon').value = data.icon || '';
        document.getElementById('edit_sort').value = data.sort || 0;
        
        // 编辑时类型不可修改
        typeSelect.value = data.type;
        typeSelect.disabled = true;
    } else {
        titleEl.innerHTML = '<img src="https://api.iconify.design/mdi:plus.svg?color=%23667eea" width="20" height="20" style="margin-right: 8px;" alt="">添加登录方式';
        document.getElementById('edit_id').value = '';
        document.getElementById('edit_name').value = '';
        document.getElementById('edit_icon').value = '';
        document.getElementById('edit_sort').value = 0;
        typeSelect.value = '';
        typeSelect.disabled = false;
    }
    
    modal.style.display = 'flex';
}

function closeModal() {
    modal.style.display = 'none';
    form.reset();
}

function closeTestModal() {
    testModal.style.display = 'none';
}

// 显示添加弹窗
document.getElementById('showAddModalBtn')?.addEventListener('click', () => openModal(null));

// 编辑按钮
document.querySelectorAll('.edit-btn').forEach(btn => {
    btn.addEventListener('click', function() {
        const id = this.dataset.id;
        // 获取当前行数据
        const row = document.getElementById('row-' + id);
        const name = row.querySelector('td:nth-child(3)').innerText;
        const type = row.querySelector('.type-badge').innerText;
        const sort = row.querySelector('td:nth-child(5)').innerText;
        
        // 查找图标
        const iconImg = row.querySelector('.login-icon img');
        let icon = '';
        if (iconImg) {
            const src = iconImg.src;
            const match = src.match(/\/([^\/]+\.svg)$/);
            icon = match ? match[1] : '';
        }
        
        openModal({ id, name, type, sort, icon });
    });
});

// 关闭弹窗
document.querySelectorAll('.modal-close').forEach(btn => btn.addEventListener('click', closeModal));

// 点击背景关闭
modal.addEventListener('click', function(e) {
    if (e.target === modal) closeModal();
});
testModal.addEventListener('click', function(e) {
    if (e.target === testModal) closeTestModal();
});

// 保存表单
form?.addEventListener('submit', function(e) {
    e.preventDefault();
    const formData = new FormData(this);
    const submitBtn = this.querySelector('button[type="submit"]');
    const originalHtml = submitBtn.innerHTML;
    
    submitBtn.innerHTML = '<span class="loading-spinner"></span> 保存中...';
    submitBtn.disabled = true;
    
    fetch('/api/admin_quick_login_save.php', {
        method: 'POST',
        body: formData
    })
    .then(res => res.json())
    .then(data => {
        if (data.success) {
            window.showToast && window.showToast(data.message, 'success');
            setTimeout(() => location.reload(), 1000);
        } else {
            window.showToast && window.showToast(data.message || '操作失败', 'error');
            submitBtn.innerHTML = originalHtml;
            submitBtn.disabled = false;
        }
        closeModal();
    })
    .catch(err => {
        window.showToast && window.showToast('网络错误', 'error');
        submitBtn.innerHTML = originalHtml;
        submitBtn.disabled = false;
    });
});

// 切换状态
document.querySelectorAll('.toggle-btn').forEach(btn => {
    btn.addEventListener('click', function() {
        const id = this.dataset.id;
        const currentStatus = parseInt(this.dataset.status);
        const newStatus = currentStatus === 1 ? 0 : 1;
        const btnEl = this;
        const originalHtml = btnEl.innerHTML;
        
        btnEl.innerHTML = '<span class="loading-spinner"></span>';
        btnEl.disabled = true;
        
        fetch('/api/admin_quick_login_toggle.php', {
            method: 'POST',
            headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
            body: `id=${id}&status=${newStatus}`
        })
        .then(res => res.json())
        .then(data => {
            if (data.success) {
                const statusBadge = document.getElementById('status-badge-' + id);
                if (newStatus === 1) {
                    statusBadge.className = 'status-badge status-active';
                    statusBadge.innerHTML = '<span class="status-dot"></span>启用';
                    btnEl.innerHTML = '<img src="https://api.iconify.design/mdi:eye-off.svg?color=%23ef4444" width="18" height="18" alt="">';
                    btnEl.setAttribute('title', '禁用');
                } else {
                    statusBadge.className = 'status-badge status-inactive';
                    statusBadge.innerHTML = '<span class="status-dot"></span>禁用';
                    btnEl.innerHTML = '<img src="https://api.iconify.design/mdi:eye.svg?color=%2310b981" width="18" height="18" alt="">';
                    btnEl.setAttribute('title', '启用');
                }
                btnEl.dataset.status = newStatus;
                window.showToast && window.showToast(data.message, 'success');
            } else {
                window.showToast && window.showToast(data.message || '操作失败', 'error');
                btnEl.innerHTML = originalHtml;
            }
            btnEl.disabled = false;
        })
        .catch(err => {
            window.showToast && window.showToast('网络错误', 'error');
            btnEl.innerHTML = originalHtml;
            btnEl.disabled = false;
        });
    });
});

// 删除
document.querySelectorAll('.delete-btn').forEach(btn => {
    btn.addEventListener('click', function() {
        if (!confirm('确定删除此登录方式吗？')) return;
        
        const id = this.dataset.id;
        const row = document.getElementById('row-' + id);
        const btnEl = this;
        const originalHtml = btnEl.innerHTML;
        
        btnEl.innerHTML = '<span class="loading-spinner"></span>';
        btnEl.disabled = true;
        
        fetch('/api/admin_quick_login_delete.php', {
            method: 'POST',
            headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
            body: `id=${id}`
        })
        .then(res => res.json())
        .then(data => {
            if (data.success) {
                row.style.transition = 'opacity 0.3s';
                row.style.opacity = '0';
                setTimeout(() => {
                    row.remove();
                    window.showToast && window.showToast(data.message, 'success');
                    if (document.querySelectorAll('#configTable tbody tr').length === 1) {
                        location.reload();
                    }
                }, 300);
            } else {
                window.showToast && window.showToast(data.message || '删除失败', 'error');
                btnEl.innerHTML = originalHtml;
                btnEl.disabled = false;
            }
        })
        .catch(err => {
            window.showToast && window.showToast('网络错误', 'error');
            btnEl.innerHTML = originalHtml;
            btnEl.disabled = false;
        });
    });
});

// 测试配置
document.querySelectorAll('.test-btn').forEach(btn => {
    btn.addEventListener('click', function() {
        const type = this.dataset.type;
        const btnEl = this;
        const originalHtml = btnEl.innerHTML;
        
        btnEl.innerHTML = '<span class="loading-spinner"></span>';
        btnEl.disabled = true;
        
        fetch('/api/admin_quick_login_test.php?type=' + encodeURIComponent(type))
            .then(res => res.json())
            .then(data => {
                const titleEl = document.getElementById('testResultTitle');
                const contentEl = document.getElementById('testResultContent');
                
                if (data.success) {
                    titleEl.innerHTML = '<img src="https://api.iconify.design/mdi:check-circle.svg?color=%2310b981" width="20" height="20" style="margin-right: 8px;" alt="">测试成功';
                    contentEl.innerHTML = `
                        <div class="test-success">
                            <img src="https://api.iconify.design/mdi:check-circle.svg?color=%23065f46" width="24" height="24" alt="">
                            <div>
                                <strong>${data.message}</strong><br>
                                <span style="font-size: 13px;">配置文件可正常读取</span>
                            </div>
                        </div>
                    `;
                } else {
                    titleEl.innerHTML = '<img src="https://api.iconify.design/mdi:alert-circle.svg?color=%23ef4444" width="20" height="20" style="margin-right: 8px;" alt="">测试失败';
                    contentEl.innerHTML = `
                        <div class="test-error">
                            <img src="https://api.iconify.design/mdi:alert-circle.svg?color=%23991b1b" width="24" height="24" alt="">
                            <div>
                                <strong>${data.message}</strong><br>
                                <span style="font-size: 13px;">请检查配置文件是否正确</span>
                            </div>
                        </div>
                    `;
                }
                
                testModal.style.display = 'flex';
                btnEl.innerHTML = originalHtml;
                btnEl.disabled = false;
            })
            .catch(err => {
                window.showToast && window.showToast('网络错误', 'error');
                btnEl.innerHTML = originalHtml;
                btnEl.disabled = false;
            });
    });
});

// 加载动画样式
const style = document.createElement('style');
style.textContent = `
    .loading-spinner {
        display: inline-block;
        width: 16px;
        height: 16px;
        border: 2px solid rgba(102, 126, 234, 0.3);
        border-radius: 50%;
        border-top-color: var(--primary-color);
        animation: spin 0.6s linear infinite;
    }
    @keyframes spin { to { transform: rotate(360deg); } }
`;
document.head.appendChild(style);
</script>